Search completed in 1.09 seconds.
4908 results for "create":
Your results are loading. Please wait...
Object.create() - JavaScript
the object.create() method creates a new object, using an existing object as the prototype of the newly created object.
... syntax object.create(proto, [propertiesobject]) parameters proto the object which should be the prototype of the newly-created object.
... propertiesobject optional if specified and not undefined, an object whose enumerable own properties (that is, those properties defined upon itself and not enumerable properties along its prototype chain) specify property descriptors to be added to the newly-created object, with the corresponding property names.
...And 18 more matches
RTCPeerConnection.createOffer() - Web APIs
the createoffer() method of the rtcpeerconnection interface initiates the creation of an sdp offer for the purpose of starting a new webrtc connection to a remote peer.
... the return value is a promise which, when the offer has been created, is resolved with a rtcsessiondescription object containing the newly-created offer.
... syntax apromise = mypeerconnection.createoffer([options]); mypeerconnection.createoffer(successcallback, failurecallback, [options]) parameters options optional an rtcofferoptions dictionary providing options requested for the offer.
...And 11 more matches
IDBObjectStore.createIndex() - Web APIs
the createindex() method of the idbobjectstore interface creates and returns a new idbindex object in the connected database.
... it creates a new field/column defining a new data point for each database record to contain.
... syntax var myidbindex = objectstore.createindex(indexname, keypath); var myidbindex = objectstore.createindex(indexname, keypath, objectparameters); parameters indexname the name of the index to create.
...And 9 more matches
Document.createElement() - Web APIs
in an html document, the document.createelement() method creates the html element specified by tagname, or an htmlunknownelement if tagname isn't recognized.
... syntax let element = document.createelement(tagname[, options]); parameters tagname a string that specifies the type of element to be created.
... the nodename of the created element is initialized with the value of tagname.
...And 7 more matches
DOMImplementation.createDocument() - Web APIs
the domimplementation.createdocument() method creates and returns an xmldocument.
... syntax var doc = document.implementation.createdocument(namespaceuri, qualifiednamestr, documenttype); parameters namespaceuri is a domstring containing the namespace uri of the document to be created, or null if the document doesn't belong to one.
... qualifiednamestr is a domstring containing the qualified name, that is an optional prefix and colon plus the local root element name, of the document to be created.
...And 6 more matches
Document.createElementNS() - Web APIs
creates an element with the specified namespace uri and qualified name.
... to create an element without specifying a namespace uri, use the createelement() method.
... syntax var element = document.createelementns(namespaceuri, qualifiedname[, options]); parameters namespaceuri a string that specifies the namespace uri to associate with the element.
...And 6 more matches
Document.createEvent() - Web APIs
many methods used with createevent, such as initcustomevent, are deprecated.
... creates an event of the type specified.
... syntax var event = document.createevent(type); event is the created event object.
...And 6 more matches
IDBDatabase.createObjectStore() - Web APIs
the createobjectstore() method of the idbdatabase interface creates and returns a new object store or index.
... syntax idbdatabase.createobjectstore(name); idbdatabase.createobjectstore(name, options); parameters name the name of the new object store to be created.
... note that it is possible to create an object store with an empty name.
...And 6 more matches
RTCPeerConnection.createAnswer() - Web APIs
the createanswer() method on the rtcpeerconnection interface creates an sdp answer to an offer received from a remote peer during the offer/answer negotiation of a webrtc connection.
... syntax apromise = rtcpeerconnection.createanswer([options]); rtcpeerconnection.createanswer(successcallback, failurecallback[, options]); parameters options optional an object which contains options which customize the answer; this is based on the rtcansweroptions dictionary.
...you should update any existing code to use the promise-based version of createanswer() instead.
...And 6 more matches
AudioContext.createMediaStreamDestination() - Web APIs
the createmediastreamdestination() method of the audiocontext interface is used to create a new mediastreamaudiodestinationnode object associated with a webrtc mediastream representing an audio stream, which may be stored in a local file or sent to another computer.
... the mediastream is created when the node is created and is accessible via the mediastreamaudiodestinationnode's stream attribute.
... syntax var audioctx = new audiocontext(); var destination = audioctx.createmediastreamdestination(); returns a mediastreamaudiodestinationnode.
...And 5 more matches
BaseAudioContext.createBuffer() - Web APIs
the createbuffer() method of the baseaudiocontext interface is used to create a new, empty audiobuffer object, which can then be populated by data, and played via an audiobuffersourcenode for more details about audio buffers, check out the audiobuffer reference page.
... note: createbuffer() used to be able to take compressed data and give back decoded samples, but this ability was removed from the spec, because all the decoding was done on the main thread, therefore createbuffer() was blocking other code execution.
... syntax var buffer = baseaudiocontext.createbuffer(numofchannels, length, samplerate); parameters note: for an in-depth explanation of how audio buffers work, and what these parameters mean, read audio buffers: frames, samples and channels from our basic concepts guide.
...And 5 more matches
CanvasRenderingContext2D.createPattern() - Web APIs
the canvasrenderingcontext2d.createpattern() method of the canvas 2d api creates a pattern using the specified image and repetition.
...the pattern it creates must be assigned to the canvasrenderingcontext2d.fillstyle or canvasrenderingcontext2d.strokestyle properties, after which it is applied to any subsequent drawing.
... syntax canvaspattern ctx.createpattern(image, repetition); parameters image a canvasimagesource to be used as the pattern's image.
...And 5 more matches
URL.createObjectURL() - Web APIs
the url.createobjecturl() static method creates a domstring containing a url representing the object given in the parameter.
... the url lifetime is tied to the document in the window on which it was created.
... note: this feature is not available in service workers due to its potential to create memory leaks.
...And 5 more matches
create fancy boxes - Learn web development
the border-radius property is made to create a rounded corner applied to boxes, but what happens if the radius size is equal or larger than the actual width of the box?
...i want to be fancy.</div> okay, let's have fun with backgrounds: .fancy { padding : 1em; width: 100%; height: 200px; box-sizing: border-box; /* at the bottom of our background stack, let's have a misty grey solid color */ background-color: #e4e4d9; /* we stack linear gradients on top of each other to create our color strip effect.
... pseudo-elements when styling a single box, you could find yourself limited and could wish to have more boxes to create even more amazing styles.
...And 4 more matches
AudioContext.createMediaStreamTrackSource() - Web APIs
the createmediastreamtracksource() method of the audiocontext interface creates and returns a mediastreamtrackaudiosourcenode which represents an audio source whose data comes from the specified mediastreamtrack.
... this differs from createmediastreamsource(), which creates a mediastreamaudiosourcenode whose audio comes from the audio track in a specified mediastream whose id is first, lexicographically (alphabetically).
... syntax var audioctx = new audiocontext(); var track = audioctx.createmediastreamtracksource(track); parameters track the mediastreamtrack to use as the source of all audio data for the new node.
...And 4 more matches
BaseAudioContext.createConvolver() - Web APIs
the createconvolver() method of the baseaudiocontext interface creates a convolvernode, which is commonly used to apply reverb effects to your audio.
... syntax baseaudiocontext.createconvolver(); returns a convolvernode.
... example the following example shows basic usage of an audiocontext to create a convolver node.
...And 4 more matches
DOMImplementation.createHTMLDocument() - Web APIs
the domimplementation.createhtmldocument() method creates a new html document.
... syntax const newdoc = document.implementation.createhtmldocument(title) parameters title optional (except in ie) a domstring containing the title to give the new html document.
... example this example creates a new html document and inserts it into an <iframe> in the current document.
...And 4 more matches
Document.createAttribute() - Web APIs
the document.createattribute() method creates a new attribute node, and returns it.
... the object created a node implementing the attr interface.
... syntax attribute = document.createattribute(name) parameters name is a string containing the name of the attribute.
...And 4 more matches
Document.createProcessingInstruction() - Web APIs
createprocessinginstruction() generates a new processing instruction node and returns it.
... syntax pinode = document.createprocessinginstruction(target, data) parameters pinode is the resulting processinginstruction node.
... example var doc = new domparser().parsefromstring('<foo />', 'application/xml'); var pi = doc.createprocessinginstruction('xml-stylesheet', 'href="mycss.css" type="text/css"'); doc.insertbefore(pi, doc.firstchild); console.log(new xmlserializer().serializetostring(doc)); // displays: <?xml-stylesheet href="mycss.css" type="text/css"?><foo/> specifications specification status comment domthe definition of 'createprocessinginstruction()' in that specification.
...And 4 more matches
FileSystemFlags.create - Web APIs
the create property on the filesystemflags dictionary is used to indicate whether or not the file should be created if it's missing.
... syntax filesystemflags.create = booleanvalue values the table below describes the result of each possible combination of these flags depending on whether or not the target file or directory path already exists.
... option values file/directory condition result create exclusive false n/a[1] path exists and matches the desired type (depending on whether the function called is getfile() or getdirectory() the successcallback is called with a filesystemfileentry if getfile() was called or a filesystemdirectoryentry if getdirectory() was called.
...And 4 more matches
RTCPeerConnection.createDataChannel() - Web APIs
the createdatachannel() method on the rtcpeerconnection interface creates a new channel linked with the remote peer, over which any kind of data may be transmitted.
... syntax datachannel = rtcpeerconnection.createdatachannel(label[, options]); parameters label a human-readable name for the channel.
... negotiated optional by default (false), data channels are negotiated in-band, where one side calls createdatachannel, and the other side listens to the rtcdatachannelevent event using the ondatachannel eventhandler .
...And 4 more matches
PR_CreatePipe
creates an anonymous pipe and retrieves file descriptors for the read and write ends of the pipe.
... syntax #include <prio.h> prstatus pr_createpipe( prfiledesc **readpipe, prfiledesc **writepipe); parameters the function has the following parameters: readpipe a pointer to a prfiledesc pointer.
... returns the function returns one of these values: if the pipe is successfully created, pr_success.
...And 3 more matches
PR_CreateThread
creates a new thread.
... syntax #include <prthread.h> prthread* pr_createthread( prthreadtype type, void (*start)(void *arg), void *arg, prthreadpriority priority, prthreadscope scope, prthreadstate state, pruint32 stacksize); parameters pr_createthread has the following parameters: type specifies that the thread is either a user thread (pr_user_thread) or a system thread (pr_system_thread).
... priority the initial priority of the newly created thread.
...And 3 more matches
JS::CreateError
this article covers features introduced in spidermonkey 38 create an error object.
... syntax // added in spidermonkey 45 bool js::createerror(jscontext *cx, jsexntype type, handleobject stack, handlestring filename, uint32_t linenumber, uint32_t columnnumber, jserrorreport *report, handlestring message, mutablehandlevalue rval); // obsolete since jsapi 39 bool js::createerror(jscontext *cx, jsexntype type, handlestring stack, handlestring filename, uint32_t linenumber, uint32_t columnnumber, jserrorreport *report, handlestring message, mutablehandlevalue rval); name type description cx jscontext * pointer to a js context from which to derive runtime information.
...receives the created error object.
...And 3 more matches
Components.utils.createObjectIn
components.utils.createobjectin creates a new javascript object in the scope of the specified object's compartment.
... note that this function is now mostly obsolete when you are using sandbox, because you can create an object in a different compartment using new.
... for example, to create a new object in the compartment identified by contentwindow: var newobject = new contentwindow.object(); but it is really needeed from firefox 30 onwards when trying to manipulate the dom window.
...And 3 more matches
AudioContext.createMediaElementSource() - Web APIs
the createmediaelementsource() method of the audiocontext interface is used to create a new mediaelementaudiosourcenode object, given an existing html <audio> or <video> element, the audio from which can then be played and manipulated.
... syntax var audioctx = new audiocontext(); var source = audioctx.createmediaelementsource(mymediaelement); parameters mymediaelement an htmlmediaelement object that you want to feed into an audio processing graph to manipulate.
... example this simple example creates a source from an <audio> element using createmediaelementsource(), then passes the audio through a gainnode before feeding it into the audiodestinationnode for playback.
...And 3 more matches
BaseAudioContext.createBufferSource() - Web APIs
the createbuffersource() method of the baseaudiocontext interface is used to create a new audiobuffersourcenode, which can be used to play audio data contained within an audiobuffer object.
... audiobuffers are created using baseaudiocontext.createbuffer or returned by baseaudiocontext.decodeaudiodata when it successfully decodes an audio track.
... syntax var source = baseaudiocontext.createbuffersource(); returns an audiobuffersourcenode.
...And 3 more matches
BaseAudioContext.createDelay() - Web APIs
the createdelay() method of the baseaudiocontext interface is used to create a delaynode, which is used to delay the incoming audio signal by a certain amount of time.
... syntax var delaynode = audioctx.createdelay(maxdelaytime); parameters maxdelaytime optional the maximum amount of time, in seconds, that the audio signal can be delayed by.
... example we have created a simple example that allows you to play three different samples on a constant loop — see create-delay (you can also view the source code).
...And 3 more matches
BaseAudioContext.createPeriodicWave() - Web APIs
the createperiodicwave() method of the baseaudiocontext interface is used to create a periodicwave, which is used to define a periodic waveform that can be used to shape the output of an oscillatornode.
... syntax var wave = audiocontext.createperiodicwave(real, imag[, constraints]); returns a periodicwave.
... example the following example illustrates simple usage of createperiodicwave(), to create a periodicwave object containing a simple sine wave.
...And 3 more matches
BaseAudioContext.createWaveShaper() - Web APIs
the createwaveshaper() method of the baseaudiocontext interface creates a waveshapernode, which represents a non-linear distortion.
... syntax baseaudioctx.createwaveshaper(); returns a waveshapernode.
... example the following example shows basic usage of an audiocontext to create a wave shaper node.
...And 3 more matches
CanvasRenderingContext2D.createImageData() - Web APIs
the canvasrenderingcontext2d.createimagedata() method of the canvas 2d api creates a new, blank imagedata object with the specified dimensions.
... syntax imagedata ctx.createimagedata(width, height); imagedata ctx.createimagedata(imagedata); parameters width the width to give the new imagedata object.
... examples creating a blank imagedata object this snippet creates a blank imagedata object using the createimagedata() method.
...And 3 more matches
CanvasRenderingContext2D.createRadialGradient() - Web APIs
the canvasrenderingcontext2d.createradialgradient() method of the canvas 2d api creates a radial gradient using the size and coordinates of two circles.
... syntax canvasgradient ctx.createradialgradient(x0, y0, r0, x1, y1, r1); the createradialgradient() method is specified by six parameters, three defining the gradient's start circle, and three defining the end circle.
... examples filling a rectangle with a radial gradient this example initializes a radial gradient using the createradialgradient() method.
...And 3 more matches
Document.createNSResolver() - Web APIs
creates an xpathnsresolver which resolves namespaces with respect to the definitions in scope for a specified node.
... syntax nsresolver = document.creatensresolver(node); parameters node is the node to be used as a context for namespace resolution.
...to match default elements in a non-null namespace, you either have to refer to a particular element using a form such as *namespace-uri()=http://www.w3.org/1999/xhtml and name()=p[@id='_myid'] (this approach works well for dynamic xpath expressions where the namespaces might not be known) or use prefixed name tests, and create a namespace resolver mapping the prefix to the namespace.
...And 3 more matches
Document.createTreeWalker() - Web APIs
the document.createtreewalker() creator method returns a newly created treewalker object.
... syntax document.createtreewalker(root, whattoshow[, filter[, entityreferenceexpansion]]); parameters root a root node of this treewalker traversal.
... whattoshow optional a unsigned long representing a bitmask created by combining the constant properties of nodefilter.
...And 3 more matches
FileSystemDirectoryEntry.createReader() - Web APIs
the filesystemdirectoryentry interface's method createreader() returns a filesystemdirectoryreader object which can be used to read the entries in the directory.
... syntax directoryreader = filesystemdirectoryentry.createreader(); parameters none.
... example this example creates a method called readdirectory(), which fetches all of the entries in the specified filesystemdirectoryentry and returns them in an array.
...And 3 more matches
FileSystemFileEntry.createWriter() - Web APIs
the filesystemfileentry interface's method createwriter() returns a filewriter object which can be used to write data into the file represented by the directory entry.
... syntax filesystemfileentry.createwriter(successcallback[, errorcallback]); parameters successcallback a callback function which is called when the filewriter has been created successfully; the filewriter is passed into the callback as the only parameter.
... errorcallback optional if provided, this must be a method which is caled when an error occurs while trying to create the filewriter.
...And 3 more matches
HTMLTableElement.createCaption() - Web APIs
the htmltableelement.createcaption() method returns the <caption> element associated with a given <table>.
... if no <caption> element exists on the table, this method creates it, and then returns it.
... note: if no caption exists, createcaption() inserts a new caption directly into the table.
...And 3 more matches
dirCreate - Archive of obsolete content
dircreate creates a new directory.
... method of file object syntax int dircreate( filespecobject dirtocreate ); parameters the dircreate method has the following parameters: dirtocreate a filespecobject representing the pathname of the directory to create.
...description the input parameter is a filespecobject that you have already created with the install object's getfolder method.
...And 2 more matches
FC_CreateObject
name fc_createobject - create a new object.
... syntax ck_rv fc_createobject( ck_session_handle hsession, ck_attribute_ptr ptemplate, ck_ulong ulcount, ck_object_handle_ptr phobject ); parameters hsession [in] session handle.
... description fc_createobject creates an object using the attributes specified in the template.
...And 2 more matches
AudioContext.createMediaStreamSource() - Web APIs
the createmediastreamsource() method of the audiocontext interface is used to create a new mediastreamaudiosourcenode object, given a media stream (say, from a mediadevices.getusermedia instance), the audio from which can then be played and manipulated.
... syntax audiosourcenode = audiocontext.createmediastreamsource(stream); parameters stream a mediastream to serve as an audio source to be fed into an audio processing graph for use and manipulation.
...maudiosourcenode // also output the visuals into a video element if (navigator.mediadevices) { console.log('getusermedia supported.'); navigator.mediadevices.getusermedia ({audio: true, video: true}) .then(function(stream) { video.srcobject = stream; video.onloadedmetadata = function(e) { video.play(); video.muted = true; }; // create a mediastreamaudiosourcenode // feed the htmlmediaelement into it var audioctx = new audiocontext(); var source = audioctx.createmediastreamsource(stream); // create a biquadfilter var biquadfilter = audioctx.createbiquadfilter(); biquadfilter.type = "lowshelf"; biquadfilter.frequency.value = 1000; biquadfilter.gain.value = range.va...
...And 2 more matches
BaseAudioContext.createAnalyser() - Web APIs
the createanalyser() method of the baseaudiocontext interface creates an analysernode, which can be used to expose audio time and frequency data and create data visualisations.
... syntax var analysernode = baseaudiocontext.createanalyser(); returns an analysernode.
... example the following example shows basic usage of an audiocontext to create an analyser node, then use requestanimationframe() to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input.
...And 2 more matches
BaseAudioContext.createBiquadFilter() - Web APIs
the createbiquadfilter() method of the baseaudiocontext interface creates a biquadfilternode, which represents a second order filter configurable as several different common filter types.
... syntax baseaudiocontext.createbiquadfilter(); returns a biquadfilternode.
... example the following example shows basic usage of an audiocontext to create a biquad filter node.
...And 2 more matches
BaseAudioContext.createChannelMerger() - Web APIs
the createchannelmerger() method of the baseaudiocontext interface creates a channelmergernode, which combines channels from multiple audio streams into a single audio stream.
... syntax baseaudiocontext.createchannelmerger(numberofinputs); parameters numberofinputs the number of channels in the input audio streams, which the output stream will contain; the default is 6 if this parameter is not specified.
... var ac = new audiocontext(); ac.decodeaudiodata(somestereobuffer, function(data) { var source = ac.createbuffersource(); source.buffer = data; var splitter = ac.createchannelsplitter(2); source.connect(splitter); var merger = ac.createchannelmerger(2); // reduce the volume of the left channel only var gainnode = ac.creategain(); gainnode.gain.setvalueattime(0.5, ac.currenttime); splitter.connect(gainnode, 0); // connect the splitter back to the second input of the merger: we // effectivel...
...And 2 more matches
BaseAudioContext.createChannelSplitter() - Web APIs
the createchannelsplitter() method of the baseaudiocontext interface is used to create a channelsplitternode, which is used to access the individual channels of an audio stream and process them separately.
... syntax baseaudiocontext.createchannelsplitter(numberofoutputs); parameters numberofoutputs the number of channels in the input audio stream that you want to output separately; the default is 6 if this parameter is not specified.
... var ac = new audiocontext(); ac.decodeaudiodata(somestereobuffer, function(data) { var source = ac.createbuffersource(); source.buffer = data; var splitter = ac.createchannelsplitter(2); source.connect(splitter); var merger = ac.createchannelmerger(2); // reduce the volume of the left channel only var gainnode = ac.creategain(); gainnode.gain.setvalueattime(0.5, ac.currenttime); splitter.connect(gainnode, 0); // connect the splitter back to the second input of the merger: we // effectivel...
...And 2 more matches
BaseAudioContext.createDynamicsCompressor() - Web APIs
the createdynamicscompressor() method of the baseaudiocontext interface is used to create a dynamicscompressornode, which can be used to apply compression to an audio signal.
... syntax baseaudioctx.createdynamicscompressor(); returns a dynamicscompressornode.
... example the below code demonstrates a simple usage of createdynamicscompressor() to add compression to an audio track.
...And 2 more matches
BaseAudioContext.createGain() - Web APIs
the creategain() method of the baseaudiocontext interface creates a gainnode, which can be used to control the overall gain (or volume) of the audio graph.
... syntax var gainnode = audiocontext.creategain(); return value a gainnode which takes as input one or more audio sources and outputs audio whose volume has been adjusted in gain (volume) to a level specified by the node's gainnode.gain a-rate parameter.
... example the following example shows basic usage of an audiocontext to create a gainnode, which is then used to mute and unmute the audio when a mute button is clicked by changing the gain property value.
...And 2 more matches
BaseAudioContext.createPanner() - Web APIs
the createpanner() method of the baseaudiocontext interface is used to create a new pannernode, which is used to spatialize an incoming audio stream in 3d space.
... syntax baseaudioctx.createpanner(); returns a pannernode.
... example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
...And 2 more matches
BaseAudioContext.createStereoPanner() - Web APIs
the createstereopanner() method of the baseaudiocontext interface creates a stereopannernode, which can be used to apply stereo panning to an audio source.
... syntax baseaudiocontext.createstereopanner(); returns a stereopannernode.
...in the javascript we create a mediaelementaudiosourcenode and a stereopannernode, and connect the two together using the connect() method.
...And 2 more matches
CanvasRenderingContext2D.createLinearGradient() - Web APIs
the canvasrenderingcontext2d.createlineargradient() method of the canvas 2d api creates a gradient along the line connecting two given coordinates.
... syntax canvasgradient ctx.createlineargradient(x0, y0, x1, y1); the createlineargradient() method is specified by four parameters defining the start and end points of the gradient line.
... examples filling a rectangle with a linear gradient this example initializes a linear gradient using the createlineargradient() method.
...And 2 more matches
DOMImplementation.createDocumentType() - Web APIs
the domimplementation.createdocumenttype() method returns a documenttype object which can either be used with domimplementation.createdocument upon document creation or can be put into the document via methods like node.insertbefore() or node.replacechild().
... syntax var doctype = document.implementation.createdocumenttype(qualifiednamestr, publicid, systemid); parameters qualifiednamestr is a domstring containing the qualified name, like svg:svg.
... example var dt = document.implementation.createdocumenttype('svg:svg', '-//w3c//dtd svg 1.1//en', 'http://www.w3.org/graphics/svg/1.1/dtd/svg11.dtd'); var d = document.implementation.createdocument('http://www.w3.org/2000/svg', 'svg:svg', dt); alert(d.doctype.publicid); // -//w3c//dtd svg 1.1//en specifications specification status comment domthe definition of 'domimplementation.createdocumenttype' in that specification.
...And 2 more matches
Document.createCDATASection() - Web APIs
createcdatasection() creates a new cdata section node, and returns it.
... syntax var cdatasectionnode = document.createcdatasection(data); cdatasectionnode is a cdata section node.
... example var docu = new domparser().parsefromstring('<xml></xml>', 'application/xml') var cdata = docu.createcdatasection('some <cdata> data & then some'); docu.getelementsbytagname('xml')[0].appendchild(cdata); alert(new xmlserializer().serializetostring(docu)); // displays: <xml><![cdata[some <cdata> data & then some]]></xml> notes this will only work with xml, not html documents (as html documents do not support cdata sections); attempting it on an html document will throw not_supported_err.
...And 2 more matches
Document.createDocumentFragment() - Web APIs
creates a new empty documentfragment into which dom nodes can be added to build an offscreen dom tree.
... syntax var fragment = document.createdocumentfragment(); value a newly created, empty, documentfragment object, which is ready to have nodes inserted into it.
...the usual use case is to create the document fragment, append elements to the document fragment and then append the document fragment to the dom tree.
...And 2 more matches
Document.createNodeIterator() - Web APIs
syntax const nodeiterator = document.createnodeiterator(root[, whattoshow[, filter]]); values root the root node at which to begin the nodeiterator's traversal.
... whattoshow optional is an optional unsigned long representing a bitmask created by combining the constant properties of nodefilter.
...since such nodes were never created in browsers, this paramater had no effect.
...And 2 more matches
Document.createTouch() - Web APIs
the document.createtouch() method creates and returns a new touch object.
... syntax var touch = documenttouch.createtouch(view, target, identifier, pagex, pagey, screenx, screeny); parameters note: all parameters are optional.
... example this example illustrates using the document.createtouch() method to create touch objects.
...And 2 more matches
Document.createTouchList() - Web APIs
the document.createtouchlist() method creates and returns a new touchlist object.
... syntax var list = documenttouch.createtouchlist([touch1 [, touch2 [, ...]]]); parameters touches zero or more touch objects.
... example this example illustrates using the document.createtouchlist() method to create touchlist objects.
...And 2 more matches
HTMLTableElement.createTFoot() - Web APIs
the htmltableelement.createtfoot() method returns the <tfoot> element associated with a given <table>.
... if no footer exists in the table, this methods creates it, and then returns it.
... note: if no footer exists, createtfoot() inserts a new footer directly into the table.
...And 2 more matches
HTMLTableElement.createTHead() - Web APIs
the htmltableelement.createthead() method returns the <thead> element associated with a given <table>.
... if no header exists in the table, this method creates it, and then returns it.
... note: if no header exists, createthead() inserts a new header directly into the table.
...And 2 more matches
WebGLRenderingContext.createProgram() - Web APIs
the webglrenderingcontext.createprogram() method of the webgl api creates and initializes a webglprogram object.
... syntax webglprogram gl.createprogram(); parameters none.
... examples creating a webgl program var program = gl.createprogram(); // attach pre-existing shaders gl.attachshader(program, vertexshader); gl.attachshader(program, fragmentshader); gl.linkprogram(program); if ( !gl.getprogramparameter( program, gl.link_status) ) { var info = gl.getprograminfolog(program); throw 'could not compile webgl program.
...And 2 more matches
createKey - Archive of obsolete content
createkey adds a key to the registry.
... method of winreg object syntax int createkey ( string subkey, string classname); parameters the method has the following parameters: subkey the key path to the appropriate location in the key hierarchy, such as "software\\netscape\\navigator\\mail".
...for information on this parameter, see the description of regcreatekeyex in your windows api documentation.
...description the createkey method adds a key to the registry.
AudioContext.createJavaScriptNode() - Web APIs
the audiocontext.createjavascriptnode() method creates a javascriptnode which is used for directly manipulating audio data with javascript.
... important: this method is obsolete, and has been renamed to audiocontext.createscriptprocessor().
... syntax var jsnode = audioctx.createjavascriptnode(buffersize, numinputchannels, numoutputchannels); parameters buffersize the buffer size must be in units of sample frames, i.e., one of: 256, 512, 1024, 2048, 4096, 8192, or 16384.
... example the following script illustrates the use of createjavascriptnode(): var sinewave = function(context) { var that = this; this.x = 0; // initial sample number this.context = context; this.node = context.createjavascriptnode(1024, 1, 1); this.node.onaudioprocess = function(e) { that.process(e) }; } sinewave.prototype.process = function(e) { var data = e.outputbuffer.getchanneldata(0); for (var i = 0; i < data.length; ++i) { data[i] = math.sin(this.x++); } } sinewave.prototype.play = fu...
BaseAudioContext.createConstantSource() - Web APIs
the createconstantsource() property of the baseaudiocontext interface creates a constantsourcenode object, which is an audio source that continuously outputs a monaural (one-channel) sound signal whose samples all have the same value.
... syntax var constantsourcenode = audiocontext.createconstantsource() parameters none.
... specifications specification status comment web audio apithe definition of 'createconstantsource()' in that specification.
... desktopmobilechromeedgefirefoxinternet exploreroperasafariandroid webviewchrome for androidfirefox for androidopera for androidsafari on iossamsung internetcreateconstantsourcechrome full support 56edge full support ≤79firefox full support 53ie no support noopera full support 43safari no support ...
BaseAudioContext.createOscillator() - Web APIs
the createoscillator() method of the baseaudiocontext interface creates an oscillatornode, a source representing a periodic waveform.
... syntax var oscillatornode = audioctx.createoscillator(); returns an oscillatornode.
... example the following example shows basic usage of an audiocontext to create an oscillator node.
... // create web audio api context var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); // create oscillator node var oscillator = audioctx.createoscillator(); oscillator.type = 'square'; oscillator.frequency.setvalueattime(3000, audioctx.currenttime); // value in hertz oscillator.connect(audioctx.destination); oscillator.start(); specifications specification status comment web audio apithe definition of 'createoscillator' in that specification.
BaseAudioContext.createScriptProcessor() - Web APIs
the createscriptprocessor() method of the baseaudiocontext interface creates a scriptprocessornode used for direct audio processing.
... syntax var scriptprocessor = audioctx.createscriptprocessor(buffersize, numberofinputchannels, numberofoutputchannels); parameters buffersize the buffer size in units of sample-frames.
... note: for a full working example, see our script-processor-node github repo (also view the source code.) var myscript = document.queryselector('script'); var mypre = document.queryselector('pre'); var playbutton = document.queryselector('button'); // create audiocontext and buffer source var audioctx = new audiocontext(); source = audioctx.createbuffersource(); // create a scriptprocessornode with a buffersize of 4096 and a single input and output channel var scriptnode = audioctx.createscriptprocessor(4096, 1, 1); console.log(scriptnode.buffersize); // load in an audio track via xhr and decodeaudiodata function getdata() { request = new xmlhtt...
...click = function() { source.connect(scriptnode); scriptnode.connect(audioctx.destination); source.start(); } // when the buffer source stops playing, disconnect everything source.onended = function() { source.disconnect(scriptnode); scriptnode.disconnect(audioctx.destination); } specifications specification status comment web audio apithe definition of 'createscriptprocessor' in that specification.
Document.createRange() - Web APIs
the document.createrange() method returns a new range object.
... syntax range = document.createrange(); range is the created range object.
... example let range = document.createrange(); range.setstart(startnode, startoffset); range.setend(endnode, endoffset); notes once a range is created, you need to set its boundary points before you can make use of most of its methods.
... specifications specification status comment domthe definition of 'document.createrange' in that specification.
Document.createTextNode() - Web APIs
creates a new text node.
... syntax var text = document.createtextnode(data); text is a text node.
... example <!doctype html> <html lang="en"> <head> <title>createtextnode example</title> <script> function addtextnode(text) { var newtext = document.createtextnode(text), p1 = document.getelementbyid("p1"); p1.appendchild(newtext); } </script> </head> <body> <button onclick="addtextnode('yes!
...');">we can!</button> <hr /> <p id="p1">first line of paragraph.</p> </body> </html> specifications specification status comment domthe definition of 'document: createtextnode' in that specification.
How to create a DOM tree - Web APIs
this page describes how to use the dom core api in javascript to create and modify dom objects.
...n" state="ma" country="usa"/> </person> <person first-name="jed" last-name="brown"> <address street="321 north st" city="atlanta" state="ga" country="usa"/> <address street="123 west st" city="seattle" state="wa" country="usa"/> <address street="321 south avenue" city="denver" state="co" country="usa"/> </person> </people> the w3c dom api, supported by mozilla, can be used to create an in-memory representation of this document like so: var doc = document.implementation.createdocument("", "", null); var peopleelem = doc.createelement("people"); var personelem1 = doc.createelement("person"); personelem1.setattribute("first-name", "eric"); personelem1.setattribute("middle-initial", "h"); personelem1.setattribute("last-name", "jung"); var addresselem1 = doc.createelement("add...
...ress"); addresselem1.setattribute("street", "321 south st"); addresselem1.setattribute("city", "denver"); addresselem1.setattribute("state", "co"); addresselem1.setattribute("country", "usa"); personelem1.appendchild(addresselem1); var addresselem2 = doc.createelement("address"); addresselem2.setattribute("street", "123 main st"); addresselem2.setattribute("city", "arlington"); addresselem2.setattribute("state", "ma"); addresselem2.setattribute("country", "usa"); personelem1.appendchild(addresselem2); var personelem2 = doc.createelement("person"); personelem2.setattribute("first-name", "jed"); personelem2.setattribute("last-name", "brown"); var addresselem3 = doc.createelement("address"); addresselem3.setattribute("street", "321 north st"); addresselem3.setattribute("city", "atlanta"); addres...
...selem3.setattribute("state", "ga"); addresselem3.setattribute("country", "usa"); personelem2.appendchild(addresselem3); var addresselem4 = doc.createelement("address"); addresselem4.setattribute("street", "123 west st"); addresselem4.setattribute("city", "seattle"); addresselem4.setattribute("state", "wa"); addresselem4.setattribute("country", "usa"); personelem2.appendchild(addresselem4); var addresselem5 = doc.createelement("address"); addresselem5.setattribute("street", "321 south avenue"); addresselem5.setattribute("city", "denver"); addresselem5.setattribute("state", "co"); addresselem5.setattribute("country", "usa"); personelem2.appendchild(addresselem5); peopleelem.appendchild(personelem1); peopleelem.appendchild(personelem2); doc.appendchild(peopleelem); see also the dom chapter of...
Element.createShadowRoot() - Web APIs
use element.createshadowroot to create an instance of shadow dom.
... when shadow dom is created, it is always attached to an existing element.
... after the shadow dom is created, the element that it is attached to is called the shadow root.
... syntax var shadowroot = element.createshadowroot(); parameters no parameters.
WebGL2RenderingContext.createVertexArray() - Web APIs
the webgl2renderingcontext.createvertexarray() method of the webgl 2 api creates and initializes a webglvertexarrayobject object that represents a vertex array object (vao) pointing to vertex array data and which provides names for different sets of vertex data.
... syntax webglvertexarrayobject gl.createvertexarray(); parameters none.
... examples var vao = gl.createvertexarray(); gl.bindvertexarray(vao); // ...
... specifications specification status comment webgl 2.0the definition of 'createvertexarray' in that specification.
WebGLRenderingContext.createShader() - Web APIs
the webglrenderingcontext method createshader() of the webgl api creates a webglshader that can then be configured further using webglrenderingcontext.shadersource() and webglrenderingcontext.compileshader().
... syntax webglshader gl.createshader(type); parameters type either gl.vertex_shader or gl.fragment_shader examples see webglshader for usage and examples.
... specifications specification status comment webgl 1.0the definition of 'createshader' in that specification.
... opengl es 2.0the definition of 'glcreateshader' in that specification.
self.createImageBitmap() - Web APIs
the createimagebitmap() method creates a bitmap from a given source, optionally cropped to contain only a portion of that source.
... syntax const imagebitmappromise = createimagebitmap(image[, options]); const imagebitmappromise = createimagebitmap(image, sx, sy, sw, sh[, options]); parameters image an image source, which can be an <img>, svg <image>, <video>, <canvas>, htmlimageelement, svgimageelement, htmlvideoelement, htmlcanvaselement, blob, imagedata, imagebitmap, or offscreencanvas object.
... var canvas = document.getelementbyid('mycanvas'), ctx = canvas.getcontext('2d'), image = new image(); // wait for the sprite sheet to load image.onload = function() { promise.all([ // cut out two sprites from the sprite sheet createimagebitmap(image, 0, 0, 32, 32), createimagebitmap(image, 32, 0, 32, 32) ]).then(function(sprites) { // draw each sprite onto the canvas ctx.drawimage(sprites[0], 0, 0); ctx.drawimage(sprites[1], 32, 32); }); } // load the sprite sheet from an image file image.src = 'sprites.png'; specifications specification status comment html living standardthe d...
...efinition of 'createimagebitmap' in that specification.
NPN_CreateObject - Archive of obsolete content
syntax #include <npruntime.h> npobject *npn_createobject(npp npp, npclass *aclass); parameters the function has the following parameters: <tt>npp</tt> the npp indicating which plugin wants to instantiate the object.
... description if the given npclass provides an allocate function it is used to allocate the storage for the object and the npp argument passed to npn_createobject() is passed along to that function.
...the newly created npobject's reference count is initialized to 1 before it is returned.
PR_CreateFileMap
creates a file mapping object.
... syntax #include <prio.h> prfilemap* pr_createfilemap( prfiledesc *fd, print64 size, prfilemapprotect prot); parameters the function has the following parameters: fd a pointer to a prfiledesc object representing the file that is to be mapped to memory.
... description the prfilemapprotect enumeration used in the prot parameter is defined as follows: typedef enum prfilemapprotect { pr_prot_readonly, pr_prot_readwrite, pr_prot_writecopy } prfilemapprotect; pr_createfilemap only prepares for the mapping a file to memory.
PR_CreateIOLayerStub
creates a new layer.
... syntax #include <prio.h> prfiledesc* pr_createiolayerstub( prdescidentity ident priomethods const *methods); parameters the function has the following parameters: ident the identity to be associated with the new layer.
... description a new layer may be allocated by calling pr_createiolayerstub.
PR_CreateThreadPool
create a new hash table.
... syntax #include <prtpool.h> nspr_api(prthreadpool *) pr_createthreadpool( print32 initial_threads, print32 max_threads, pruint32 stacksize ); parameters the function has the following parameters: initial_threads the number of threads to be created within this thread pool.
... max_threads the limit on the number of threads that will be created to server the thread pool.
BaseAudioContext.createIIRFilter() - Web APIs
the createiirfilter() method of the baseaudiocontext interface creates an iirfilternode, which represents a general infinite impulse response (iir) filter which can be configured to serve as various types of filter.
... syntax var iirfilter = audiocontext.createiirfilter(feedforward, feedback); parameters feedforward an array of floating-point values specifying the feedforward (numerator) coefficients for the transfer function of the iir filter.
... specifications specification status comment web audio apithe definition of 'createiirfilter()' in that specification.
Document.createComment() - Web APIs
createcomment() creates a new comment node, and returns it.
... syntax commentnode = document.createcomment(data); parameters data a string containing the data to be added to the comment.
... example var docu = new domparser().parsefromstring('<xml></xml>', 'application/xml'); var comment = docu.createcomment('this is a not-so-secret comment in your document'); docu.getelementsbytagname('xml')[0].appendchild(comment); alert(new xmlserializer().serializetostring(docu)); // displays: <xml><!--this is a not-so-secret comment in your document--></xml> specifications specification status comment domthe definition of 'document.createcomment' in that specification.
EXT_disjoint_timer_query.createQueryEXT() - Web APIs
the ext_disjoint_timer_query.createqueryext() method of the webgl api creates and initializes webglquery objects, which track the time needed to fully complete a set of gl commands.
... syntax webgltimerqueryext ext.createqueryext(); parameters none.
... examples var ext = gl.getextension('ext_disjoint_timer_query'); var query = ext.createqueryext(); specifications specification status comment ext_disjoint_timer_querythe definition of 'ext_disjoint_timer_query' in that specification.
OES_vertex_array_object.createVertexArrayOES() - Web APIs
the oes_vertex_array_object.createvertexarrayoes() method of the webgl api creates and initializes a webglvertexarrayobject object that represents a vertex array object (vao) pointing to vertex array data and which provides names for different sets of vertex data.
... syntax webglvertexarrayobjectoes ext.createvertexarrayoes(); parameters none.
... examples var ext = gl.getextension('oes_vertex_array_object'); var vao = ext.createvertexarrayoes(); ext.bindvertexarrayoes(vao); // ...
Range.createContextualFragment() - Web APIs
the range.createcontextualfragment() method returns a documentfragment by invoking the html fragment parsing algorithm or the xml fragment parsing algorithm with the start of the range (the parent of the selected node) as the context node.
... syntax documentfragment = range.createcontextualfragment(tagstring) parameters tagstring text that contains text and tags to be converted to a document fragment.
... example var tagstring = "<div>i am a div node</div>"; var range = document.createrange(); // make the parent of the first div in the document becomes the context node range.selectnode(document.getelementsbytagname("div").item(0)); var documentfragment = range.createcontextualfragment(tagstring); document.body.appendchild(documentfragment); specification specification status comment dom parsing and serializationthe definition of 'range.createcontextualfragment()' in that specification.
WebGL2RenderingContext.createQuery() - Web APIs
the webgl2renderingcontext.createquery() method of the webgl 2 api creates and initializes webglquery objects, which provide ways to asynchronously query for information.
... syntax webglquery gl.createquery(); parameters none.
... var query = gl.createquery(); specifications specification status comment webgl 2.0the definition of 'createquery' in that specification.
WebGL2RenderingContext.createSampler() - Web APIs
the webgl2renderingcontext.createsampler() method of the webgl 2 api creates and initializes webglsampler objects.
... syntax webglsampler gl.createsampler(); parameters none.
... var sampler = gl.createsampler(); specifications specification status comment webgl 2.0the definition of 'createsampler' in that specification.
WebGL2RenderingContext.createTransformFeedback() - Web APIs
the webgl2renderingcontext.createtransformfeedback() method of the webgl 2 api creates and initializes webgltransformfeedback objects.
... syntax webgltransformfeedback gl.createtransformfeedback(); parameters none.
... var transformfeedback = gl.createtransformfeedback(); specifications specification status comment webgl 2.0the definition of 'createtransformfeedback' in that specification.
WebGLRenderingContext.createBuffer() - Web APIs
the webglrenderingcontext.createbuffer() method of the webgl api creates and initializes a webglbuffer storing data such as vertices or colors.
... syntax webglbuffer gl.createbuffer(); parameters none.
... examples creating a buffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var buffer = gl.createbuffer(); specifications specification status comment webgl 1.0the definition of 'createbuffer' in that specification.
WebGLRenderingContext.createFramebuffer() - Web APIs
the webglrenderingcontext.createframebuffer() method of the webgl api creates and initializes a webglframebuffer object.
... syntax webglframebuffer gl.createframebuffer(); parameters none.
... examples creating a frame buffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var framebuffer = gl.createframebuffer(); specifications specification status comment webgl 1.0the definition of 'createframebuffer' in that specification.
WebGLRenderingContext.createRenderbuffer() - Web APIs
the webglrenderingcontext.createrenderbuffer() method of the webgl api creates and initializes a webglrenderbuffer object.
... syntax webglrenderbuffer gl.createrenderbuffer(); parameters none.
... examples creating a render buffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var renderbuffer = gl.createrenderbuffer(); specifications specification status comment webgl 1.0the definition of 'createrenderbuffer' in that specification.
WebGLRenderingContext.createTexture() - Web APIs
the webglrenderingcontext.createtexture() method of the webgl api creates and initializes a webgltexture object.
... syntax webgltexture gl.createtexture(); parameters none.
... creating a texture var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var texture = gl.createtexture(); specifications specification status comment webgl 1.0the definition of 'createtexture' in that specification.
201 Created - HTTP
WebHTTPStatus201
the http 201 created success status response code indicates that the request has succeeded and has led to the creation of a resource.
... the new resource is effectively created before this response is sent back and the new resource is returned in the body of the message, its location being either the url of the request, or the content of the location header.
... status 201 created specifications specification title rfc 7231, section 6.3.2: 201 created hypertext transfer protocol (http/1.1): semantics and content ...
Create the Canvas and draw on it - Game development
before we can start writing the game's functionality, we need to create a basic structure to render the game inside.
...using your favourite text editor, create a new html document, save it as index.html, in a sensible location, and add the following code to it: <!doctype html> <html> <head> <meta charset="utf-8" /> <title>gamedev canvas workshop</title> <style> * { padding: 0; margin: 0; } canvas { background: #eee; display: block; margin: 0 auto; } </style> </head> <body> <canvas id="mycanvas" width="480" height="320"></canvas> <script> // javascript code goes here </script> </body> </html> we have a charset defined, <title> and some basic css in the header.
CredentialsContainer.create() - Web APIs
the create() method of the credentialscontainer interface returns a promise that resolves with a new credential instance based on the provided options, or null if no credential object can be created.
... syntax var promise = credentialscontainer.create([options]) parameters options an object of type credentialcreationoptions that contains options for the requested new credentials object.
Document.createEntityReference() - Web APIs
the only workaround is to create a text node, cdata section, attribute node value, etc.
... specifications createentityreference ...
createMediaKeys() - Web APIs
the mediakeysystemaccess.createmediakeys() method returns a promise that resolves to a new mediakeys object.
... syntax var mediakeys = await mediakeysystemaccess.createmediakeys(); specifications specification status comment encrypted media extensionsthe definition of 'createmediakeys()' in that specification.
createSession() - Web APIs
the mediakeys.createsession() method returns a new mediakeysession object, which represents a context for message exchange with a content decryption module (cdm).
... syntax ​var mediakeysessionobject = mediakeys.createsession([mediakeysessiontype]); specifications specification status comment encrypted media extensionsthe definition of 'createsession()' in that specification.
XPathEvaluator.createExpression() - Web APIs
syntax xpathexpression xpathevaluator.createexpression(expression, resolver); parameters expression a domstring representing representing the xpath expression to be created.
... html <div>xpath example</div> <div>number of &lt;div&gt;s: <output></output></div> javascript var xpath = "//div"; var evaluator = new xpathevaluator(); var expression = evaluator.createexpression("//div"); var result = expression.evaluate(document, xpathresult.ordered_node_snapshot_type); document.queryselector("output").textcontent = result.snapshotlength; result specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathevaluator.createexpression()' in that specification.
XPathEvaluator.createNSResolver() - Web APIs
syntax xpathnsresolver xpathevaluator.creatensresolver(noderesolver); parameters noderesolver a node to be used as a context for namespace resolution.
... specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathevaluator.creatensresolver()' in that specification.
Create Your Own Firefox Background Theme - Archive of obsolete content
how to create your own background theme themes are made up of a "header" graphic image file, which skins the default firefox ui background.
createInstanceByContractID
this content is now available at nsicomponentmanager.createinstancebycontractid().
createInstance
this content is now available at nsifactory.createinstance().
create
this content is now available at nsifile.create().
createUnique
this content is now available at nsifile.createunique().
AudioContext.createWaveTable() - Web APIs
the audiocontext method createwavetable() is now obsolete; you should instead use the method createperiodicwave().
Document.createExpression() - Web APIs
syntax xpathexpr = document.createexpression(xpathtext, namespaceurlmapper); parameters xpathtext is a string which is the xpath expression to be compiled.
Index - Web APIs
WebAPIIndex
7 abortcontroller.abortcontroller() api, abortcontroller, constructor, experimental, fetch, reference the abortcontroller() constructor creates a new abortcontroller object instance.
... 15 absoluteorientationsensor api, absoluteorientationsensor, constructor, generic sensor api, orientation sensor api, reference, sensor, sensor apis, sensors the absoluteorientationsensor constructor creates a new absoluteorientationsensor object which describes the device's physical orientation in relation to the earth's reference coordinate system.
... 25 accelerometer.accelerometer() api, accelerometer, accelerometer api, constructor, generic sensor api, reference, sensor, sensor apis, sensors the accelerometer constructor creates a new accelerometer object which returns the acceleration of the device along all three axes at the time it is read.
...And 434 more matches
Index
MozillaTechXPCOMIndex
since binary components are linked against a single gecko sdk, a dependency to a particular version of gecko is created.
...this can create a difficult situation for extension developers trying to support multiple gecko versions (firefox 2 and 3, for example).
... 8 generating guids add-ons, developing mozilla, developing_mozilla:tools, extensions, tools, xpcom guids are used in mozilla programming for identifying several types of entities, including xpcom interfaces (this type of guids is callled iid), components (cid), and legacy add-ons—like extensions and themes—that were created prior to firefox 1.5.
...And 116 more matches
Index - Archive of obsolete content
41 addon-page add-on sdk, add-ons, extensions, obsolete, reference create a page that does not contain navigational elements.
... 50 page-worker add-on sdk create a permanent, invisible page and access its dom.
... 51 panel add-on sdk, add-ons, extensions creates transient dialogs to implement part of an add-on's user interface.
...And 99 more matches
Index
it will detect and open an existing database, or it can create a new one.
...nss will usually create an in-memory (ram) presentation of certificates, once a certificate has been received from the network, read from disk, or looked up from the database, and prepare in-memory data structures that contain the certificate's properties, as well as providing a handle for the programmer to use.
...the usual approach is to create a certificate signing request (csr) as soon as an application is done with the creation step, which will have created a handle to the key pair, and which can be used for the necessary related operations, like producing a proof-of-ownership of the private key, which is usually required when submitting the public key with a csr to a ca.
...And 67 more matches
Index
30 js::clonefunctionobject jsapi reference, reference, référence(2), spidermonkey js::clonefunctionobject creates a new function object from funobj.
...if scopechain is omitted, it creates a new function object in cx's global.
... this can be helpful if funobj is an extant function that you wish to use as if it were enclosed by a newly-created global object.
...And 58 more matches
Chapter 5: Let's build a Firefox extension - Archive of obsolete content
create a development profile if you want to partition your everyday browsing environment from your development environment in firefox, set up a second profile for development.
... to create this dev profile start firefox with firefox.exe -no-remote -p dev on the first start the profile manager will appear, where you can create the dev profile and configure its home-path.
...some of these preferences do not exist—to create them, right-click, select “new>boolean”, and type in the name and set the value accordingly.
...And 49 more matches
Details of the object model - JavaScript
because of this different basis, it can be less apparent how javascript allows you to create hierarchies of objects and to have inheritance of properties and their values.
... this chapter assumes that you are already somewhat familiar with javascript and that you have used javascript functions to create simple objects.
...any object can specify its own properties, either when you create it or at run time.
...And 42 more matches
Index - Archive of obsolete content
ArchiveMozillaXULIndex
to create an output stream, use nsiscriptableio.newoutputstream().
... this method has a number of options to specify text or binary writing, the character set, and whether to append to an existing file or create a new one.
... 435 how to implement a custom xul query processor component xul supports templating to create a block of content from a datasource query.
...And 41 more matches
Using IndexedDB - Web APIs
because it lets you create web applications with rich query abilities regardless of network availability, your applications can work both online and offline.
... create an object store in the database.
...if the database doesn't already exist, it is created by the open operation, then an onupgradeneeded event is triggered and you create the database schema in the handler for this event.
...And 35 more matches
Advanced techniques: Creating and sequencing audio - Web APIs
each voice also has local controls, which allow you to manipulate the effects or parameters particular to each technique we are using to create those voices.
... "sweep" oscillator, periodic wave oscillatornode, periodicwave "pulse" multiple oscillators oscillatornode "noise" random noise buffer, biquad filter audiobuffer, audiobuffersourcenode, biquadfilternode "dial up" loading a sound sample to play audiocontext.decodeaudiodata(), audiobuffersourcenode note: this instrument was not created to sound good, it was created to provide demonstration code and represents a very simplified version of such an instrument.
...context as you should be used to by now, each web audio api app starts with an audio context: // for cross browser compatibility const audiocontext = window.audiocontext || window.webkitaudiocontext; const audioctx = new audiocontext(); the "sweep" — oscillators, periodic waves, and envelopes for what we will call the "sweep" sound, that first noise you hear when you dial up, we're going to create an oscillator to generate the sound.
...And 33 more matches
Bytecode Descriptions
objects creating objects newinit stack: ⇒ obj create and push a new object with no properties.
... format: jof_ic newobject, newobjectwithgroup operands: (uint32_t baseobjindex) stack: ⇒ obj create and push a new object of a predetermined shape.
...the spec requires that an objectliteral or arrayliteral creates a new object every time it's evaluated, so this instruction must not be used anywhere it might be executed more than once.
...And 32 more matches
JSAPI User Guide
it can compile and execute scripts, get and set object properties, call javascript functions, convert javascript data from one type to another, create objects, and so on.
...as the script runs, it can create global functions and variables of its own.
... a minimal example each of the three key elements described in the previous section requires a few jsapi calls: the runtime: use js_newruntime to create it and js_destroyruntime to clean it up when you're done.
...And 31 more matches
Index - Learn web development
36 getting started with the web beginner, css, design, guide, html, index, l10n:priority, publishing, theory it's a lot of work to create a professional website, so if you're new to web development, we encourage you to start small.
...most importantly, you should understand what the document object model is, and how to manipulate it to create useful functionality.
...you can even create your own objects to encapsulate related functions and variables into efficient packages and act as handy data containers.
...And 29 more matches
DirectoryEntrySync - Web APIs
basic concepts if you want to create subdirectories, you have to create each child directory in sequence.
... if you try to create a directory using a full path that includes parent directories that do not exist yet, you get an error.
... so create the hierarchy by recursively adding a new path after creating the parent directory.
...And 26 more matches
Client-side storage - Learn web development
we need to create this and write our javascript code into it.
... create an index.js file in the same directory as your html file.
... we'll start off by creating references to all the html features we need to manipulate in this example — we'll create them all as constants, as these references do not need to change in the lifecycle of the app.
...And 25 more matches
Advanced Svelte: Reactivity, lifecycle, accessibility - Learn web development
let's create a component that will be in charge of displaying the buttons and emitting the corresponding events.
... create a new file — components/moreactions.svelte.
...put the following content into your moreactions.svelte file: <script> import { createeventdispatcher } from 'svelte' const dispatch = createeventdispatcher() let completed = true const checkall = () => { dispatch('checkall', completed) completed = !completed } const removecompleted = () => dispatch('removecompleted') </script> <div class="btn-group"> <button type="button" class="btn btn__primary" on:click={checkall}>{completed ?
...And 25 more matches
CustomizableUI.jsm
there are three main types of widgets: 'legacy' xul widgets, which are the way customizableui represents widgets whose dom representation is present (or overlaid) into a window; api-style widgets, which are the new widgets customizableui can create and manage for you.
... custom which are widgets that are custom-created by some js supplied by the consumer for more details, see api-provided widgets.
... the lifetime of your widget should be identical to the lifetime of the add-on - it's process-global, so if you call createwidget on bootstrap's "startup" and destroywidget on bootstrap's "shutdown", that's enough.
...And 25 more matches
Color picker tool - CSS: Cascading Style Sheets
'hsl' : 'hsv'; this.color.setformat(this.picker_mode); this.createpickingarea(); this.createhuearea(); this.newinputcomponent('h', 'hue', this.inputchangehue.bind(this)); this.newinputcomponent('s', 'saturation', this.inputchangesaturation.bind(this)); this.newinputcomponent('v', 'value', this.inputchangevalue.bind(this)); this.newinputcomponent('l', 'lightness', this.inputchangelightness.bind(this)); this.createalphaarea(); this.newinputcompone...
...nt('r', 'red', this.inputchangered.bind(this)); this.newinputcomponent('g', 'green', this.inputchangegreen.bind(this)); this.newinputcomponent('b', 'blue', this.inputchangeblue.bind(this)); this.createpreviewbox(); this.createchangemodebutton(); this.newinputcomponent('alpha', 'alpha', this.inputchangealpha.bind(this)); this.newinputcomponent('hexa', 'hexa', this.inputchangehexa.bind(this)); this.setcolor(this.color); pickers[topic] = this; } /*************************************************************************/ // function for generating the color-picker /*************************************************************************/ colorpicker.prototype.createpickingarea = function createpickingarea() { var area = document.createelement('div'); var picker = do...
...cument.createelement('div'); area.classname = 'picking-area'; picker.classname = 'picker'; this.picking_area = area; this.color_picker = picker; setmousetracking(area, this.updatecolor.bind(this)); area.appendchild(picker); this.node.appendchild(area); }; colorpicker.prototype.createhuearea = function createhuearea() { var area = document.createelement('div'); var picker = document.createelement('div'); area.classname = 'hue'; picker.classname ='slider-picker'; this.hue_area = area; this.hue_picker = picker; setmousetracking(area, this.updatehueslider.bind(this)); area.appendchild(picker); this.node.appendchild(area); }; colorpicker.prototype.createalphaarea = function createalphaarea() { var area = document.createelement('div'); var mask = documen...
...And 25 more matches
StringView - Archive of obsolete content
the aims of this library are: to create a c-like interface for strings (i.e., an array of character codes — an arraybufferview in javascript) based upon the javascript arraybuffer interface to create a highly extensible library that anyone can extend by adding methods to the object stringview.prototype to create a collection of methods for such string-like objects (since now: stringviews) which work strictly on arrays of numbers rather than on creating new immutable javascript strings to work with unicode encodings other than javascript's default utf-16 domstrings introduction as web applications become more and more powerful, adding features such as audio and video manipulation, access to raw data using websockets, and so forth, it has become clear that there are times when i...
...int16array; break encswitch; case "utf-32": ftaview = uint32array; ntranscrtype &= 14; break encswitch; default: /* case "ascii", or case "binarystring" or unknown cases */ ftaview = uint8array; ntranscrtype &= 14; } typeswitch: switch (typeof vinput) { case "string": /* the input argument is a primitive string: a new buffer will be created.
... */ ntranscrtype &= 7; break typeswitch; case "object": classswitch: switch (vinput.constructor) { case stringview: /* the input argument is a stringview: a new buffer will be created.
...And 24 more matches
Object-oriented JavaScript for beginners - Learn web development
previous overview: objects next with the basics out of the way, we'll now focus on object-oriented javascript (oojs) — this article presents a basic view of object-oriented programming (oop) theory, then explores how javascript emulates object classes via constructor functions, and how to create object instances.
... objective: to understand the basic theory behind object-oriented programming, how this relates to javascript ("everything is an object"), and how to create constructors and object instances.
... creating actual objects from our class, we can create object instances — objects that contain the data and functionality defined in the class.
...And 24 more matches
NSS Tools certutil
using the certificate database tool the certificate database tool is a command-line utility that can create and modify the netscape communicator cert8.db and key3.db database files.
... it can also list, generate, modify, or delete certificates within the cert8.db file and create or change the password, generate new public and private key pairs, display the contents of the key database, or delete key pairs within the key3.db file.
...certificate database tool command options and their arguments are defined as follows: options -n create new certificate and key databases.
...And 24 more matches
Traversing an HTML table with JavaScript and DOM Interfaces - Web APIs
you will learn how to create, access and control, and remove html elements dynamically.
... example: creating an html table dynamically (sample1.html) html <input type="button" value="generate a table." onclick="generate_table()"> javascript function generate_table() { // get the reference for the body var body = document.getelementsbytagname("body")[0]; // creates a <table> element and a <tbody> element var tbl = document.createelement("table"); var tblbody = document.createelement("tbody"); // creating all cells for (var i = 0; i < 2; i++) { // creates a table row var row = document.createelement("tr"); for (var j = 0; j < 2; j++) { // create a <td> element and a text node, make the text // node the contents of the <td>,...
... and put the <td> at // the end of the table row var cell = document.createelement("td"); var celltext = document.createtextnode("cell in row "+i+", column "+j); cell.appendchild(celltext); row.appendchild(cell); } // add the row to the end of the table body tblbody.appendchild(row); } // put the <tbody> in the <table> tbl.appendchild(tblbody); // appends <table> into <body> body.appendchild(tbl); // sets the border attribute of tbl to 2; tbl.setattribute("border", "2"); } note the order in which we created the elements and the text node: first we created the <table> element.
...And 24 more matches
OS.File for the main thread
var img = new image(); img.onload = function() { var canvas = document.createelementns('http://www.w3.org/1999/xhtml', 'canvas'); canvas.width = img.naturalwidth; canvas.height = img.naturalheight; var ctx = canvas.getcontext('2d'); ctx.drawimage(img, 0, 0); (canvas.toblobhd || canvas.toblob).call(canvas, function(b) { var r = cc['@mozilla.org/files/filereader;1'].createinstance(ci.nsidomfilereader); //new filereader(); r.onloadend = fun...
...if the file does not exist, it is created.
...tions); promise<void> setcurrentdirectory(in string path); promise<void> setdates(in string path, in date|number accessdate, in date|number modificationdate); promise<void> setpermissions(in string path, in object options ); promise<file.info> stat(in string path, [optional] in object options); promise<void> unixsymlink(in string targetpath, in string createpath); promise<void> writeatomic(in string path, in arrayview data, in object options); methods os.file.open() use method os.file.open() to open a file.
...And 23 more matches
Migrating from webkitAudioContext - Web APIs
creategainnode() has been renamed to creategain.
... createdelaynode() has been renamed to createdelay.
... createjavascriptnode() has been renamed to createscriptprocessor.
...And 23 more matches
NSS tools : certutil
name certutil — manage keys and certificate in both nss databases and other nss tokens synopsis certutil [options] [[arguments]] description the certificate database tool, certutil, is a command-line utility that can create and modify certificate and key databases.
... it can specifically list, generate, modify, or delete certificates, create or change the password, generate new public and private key pairs, display the contents of the key database, or delete key pairs within the key database.
... certificate issuance, part of the key and certificate management process, requires that keys and certificates be created in the key database.
...And 22 more matches
Linear-gradient Generator - CSS: Cascading Style Sheets
'hsl' : 'hsv'; this.color.setformat(this.picker_mode); this.createpickingarea(); this.createhuearea(); this.newinputcomponent('h', 'hue', this.inputchangehue.bind(this)); this.newinputcomponent('s', 'saturation', this.inputchangesaturation.bind(this)); this.newinputcomponent('v', 'value', this.inputchangevalue.bind(this)); this.newinputcomponent('l', 'lightness', this.inputchangelightness.bind(this)); this.createalphaarea(); this.newinputcompone...
...nt('r', 'red', this.inputchangered.bind(this)); this.newinputcomponent('g', 'green', this.inputchangegreen.bind(this)); this.newinputcomponent('b', 'blue', this.inputchangeblue.bind(this)); this.createpreviewbox(); this.createchangemodebutton(); this.newinputcomponent('alpha', 'alpha', this.inputchangealpha.bind(this)); this.newinputcomponent('hexa', 'hexa', this.inputchangehexa.bind(this)); this.setcolor(this.color); pickers[topic] = this; } /*************************************************************************/ // function for generating the color-picker /*************************************************************************/ colorpicker.prototype.createpickingarea = function createpickingarea() { var area = document.createelement('div'); var picker = do...
...cument.createelement('div'); area.classname = 'picking-area'; picker.classname = 'picker'; this.picking_area = area; this.color_picker = picker; setmousetracking(area, this.updatecolor.bind(this)); area.appendchild(picker); this.node.appendchild(area); }; colorpicker.prototype.createhuearea = function createhuearea() { var area = document.createelement('div'); var picker = document.createelement('div'); area.classname = 'hue'; picker.classname ='slider-picker'; this.hue_area = area; this.hue_picker = picker; setmousetracking(area, this.updatehueslider.bind(this)); area.appendchild(picker); this.node.appendchild(area); }; colorpicker.prototype.createalphaarea = function createalphaarea() { var mask = document.createelement('div'); var picker = docum...
...And 22 more matches
JXON - Archive of obsolete content
</item_number> <discount_until>dec 25, 1995</discount_until> <price>42.50</price> <size description="medium"> <color_swatch image="black_cardigan.jpg">black</color_swatch> </size> </catalog_item> </product> <script type="text/javascript"><![cdata[function matchwo(a,b) { if (a < b && a < 0) { return 1; } else { return 0; } }]]></script> </catalog> first, create a dom tree like the previous example as described in the how to create a dom tree article.
...|*| http://www.gnu.org/licenses/gpl-3.0-standalone.html |*| \*/ function createxml (oobjtree) { function loadobjtree (oparentel, oparentobj) { var vvalue, ochild; if (oparentobj.constructor === string || oparentobj.constructor === number || oparentobj.constructor === boolean) { oparentel.appendchild(onewdoc.createtextnode(oparentobj.tostring())); /* verbosity level is 0 or 1 */ if (oparentobj === oparentobj.valueof()) { return; } } else if (oparento...
...bj.constructor === date) { oparentel.appendchild(onewdoc.createtextnode(oparentobj.togmtstring())); } for (var sname in oparentobj) { if (isfinite(sname)) { continue; } /* verbosity level is 0 */ vvalue = oparentobj[sname]; if (sname === "keyvalue") { if (vvalue !== null && vvalue !== true) { oparentel.appendchild(onewdoc.createtextnode(vvalue.constructor === date ?
...And 21 more matches
certutil
synopsis certutil [options] arguments description the certificate database tool, certutil, is a command-line utility that can create and modify certificate and key database files.
... it can also list, generate, modify, or delete certificates within the database, create or change the password, generate new public and private key pairs, display the contents of the key database, or delete key pairs within the key database.
... -c create a new binary certificate file from a binary certificate request file.
...And 21 more matches
Working with objects - JavaScript
this chapter describes how to use objects, properties, functions, and methods, and how to create your own objects.
...for example, let's create an object named mycar and give it properties named make, model, and year as follows: var mycar = new object(); mycar.make = 'ford'; mycar.model = 'mustang'; mycar.year = 1969; the above example could also be written using an object initializer, which is a comma-delimited list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}): var mycar =...
...examples are as follows: // four variables are created and assigned in a single go, // separated by commas var myobj = new object(), str = 'mystring', rand = math.random(), obj = new object(); myobj.type = 'dot syntax'; myobj['date created'] = 'string with space'; myobj[str] = 'string value'; myobj[rand] = 'random number'; myobj[obj] = 'object'; myobj[''] = 'even an empt...
...And 21 more matches
SVG documentation index - SVG: Scalable Vector Graphics
WebSVGIndex
10 replaced element svg this page was auto-generated because a user created a sub-page to this page.
... 273 clipping and masking advanced, svg, svg:tutorial erasing part of what one has created might at first sight look contradictory.
... but when you try to create a semicircle in svg, you will find out the use of the following properties quickly.
...And 21 more matches
2D maze game with device orientation - Game development
you can create this yourself if you want to follow along: <!doctype html> <html> <head> <meta charset="utf-8" /> <title>cyber orb demo</title> <style> body { margin: 0; background: #333; } </style> <script src="src/phaser-arcade-physics.2.2.2.min.js"></script> <script src="src/boot.js"></script> <script src="src/preloader.js"></script> <script src="src/mainmenu.js"></script> <sc...
... var ball = { _width: 320, _height: 480 }; ball.boot = function(game) {}; ball.boot.prototype = { preload: function() { this.load.image('preloaderbg', 'img/loading-bg.png'); this.load.image('preloaderbar', 'img/loading-bar.png'); }, create: function() { this.game.scale.scalemode = phaser.scalemanager.show_all; this.game.scale.pagealignhorizontally = true; this.game.scale.pagealignvertically = true; this.game.state.start('preloader'); } }; the main ball object is defined and we're adding two variables called _width and _height that are the width and the height of the game canvas — they will hel...
...the create function holds some basic configuration: we're setting up the scaling and alignment of the canvas, and moving on to the preload state when everything's ready.
...And 20 more matches
Mozilla accessibility architecture
even if a child accessible of the document is asked for first, the doc accessible will be created first, because it is needed to cache any accessibles created within it.
... when the doc accessible is asked for, an event is fired which reaches the presshell, which then uses the accessibility service singleton (nsiaccessibilityservice) to create the doc accessible and return it back to the widget code.
... the reason that the doc accessible is not created directly in the widget code where it's needed is that the widget code has no knowledge what nsidomnode is associated with the current window's document object.
...And 20 more matches
Document - Web APIs
WebAPIDocument
it provides functionality globally to the document, like how to obtain the page's url and create new elements in the document.
... constructor document() creates a new document object.
... document.timelineread only returns timeline as a special instance of documenttimeline that is automatically created on page load.
...And 20 more matches
Signaling and video calling - Web APIs
in this article, we will further enhance the websocket chat first created as part of our websocket documentation (this article link is forthcoming; it isn't actually online yet) to support opening a two-way video call between users.
...how do we create this server and how does the signaling process actually work?
... exchanging session descriptions when starting the signaling process, an offer is created by the user initiating the call.
...And 20 more matches
Window.open() - Web APIs
WebAPIWindowopen
windowname optional a domstring specifying the name of the browsing context (window, <iframe> or tab) into which to load the specified resource; if the name doesn't indicate an existing context, a new window is created and is given the name specified by windowname.
... return value a windowproxy object, which is basically a thin wrapper for the window object representing the newly created window, and has all its features available.
... description the open() method creates a new secondary browser window, similar to choosing new window from the file menu.
...And 20 more matches
Drawing graphics - Learn web development
the web still had no way to effectively create animations, games, 3d scenes, and other requirements commonly handled by lower level languages such as c++ or java.
...webgl allows you to create real 3d graphics inside your web browser; the below example shows a simple rotating webgl cube: this article will focus mainly on 2d canvas, as raw webgl code is very complex.
... we will however show how to use a webgl library to create a 3d scene more easily, and you can find a tutorial covering raw webgl elsewhere — see getting started with webgl.
...And 19 more matches
Working with Svelte stores - Learn web development
objective: learn how to use svelte stores using stores we will create an alert component that shows notifications on screen, which can receive messages from any component.
...if you create your own stores honoring the store contract, you get this reactivity syntactic sugar for free.
... creating the alert component to show how to work with stores, we will create an alert component.
...And 19 more matches
Creating the Component Code
use the calculator (after learning long division) you have to write a fair amount of code to create a component library that gets loaded into xpcom.
...using xpcom utilities to make things easier shows some simpler and more elegant ways to create an xpcom component using generic macros, and this chapter is more about learning the basics.
...as you can see in onion peel view of xpcom component creation, the main accessor for the xpcom object is createinstance, which is expected to return the object that matches a given cid and iid pair.
...And 19 more matches
Web Authentication API - Web APIs
similar to the other forms of the credential management api, the web authentication api has two basic methods that correspond to register and login: navigator.credentials.create() - when used with the publickey option, creates new credentials, either for registering a new account or for associating a new asymmetric key pair credentials with an existing account.
... please note: both create() and get() require a secure context (e.g.
... in their most basic forms, both create() and get() receive a very large random number called a challenge from the server and they return the challenge signed by the private key back to the server.
...And 19 more matches
Basic Concepts of grid layout - CSS: Cascading Style Sheets
css grid layout has the following features: fixed and flexible track sizes you can create a grid with fixed track sizes – using pixels for example.
...you can also create a grid using flexible sizes with percentages or with the new fr unit designed for this purpose.
... grid is a powerful specification that, when combined with other parts of css such as flexbox, can help you create layouts that were previously impossible to build in css.
...And 19 more matches
Creating custom Firefox extensions with the Mozilla build system - Archive of obsolete content
for complex extensions, it may be necessary to create components in c++ that provide additional functionality.
...i should also stress that you do not have to build mozilla or use the mozilla build system if you want to create c++ components for mozilla.
... if you are just looking to create an xpcom component or two, this is probably overkill, and you might want to take a look at this guide instead.
...And 18 more matches
Manifest Files - Archive of obsolete content
« previousnext » in this section, we'll see how to put chrome and xul files into a package and create the manifest files for them.
... if you just want to try testing privileged xul code in the firefox browser, you can do this easily by just using a manifest with only one line in it: create a new directory somewhere.
... for example, on a windows machine, you might use c:\testfiles create a new ascii1 file called test.manifest in the chrome directory.
...And 18 more matches
mozIStorageConnection
method overview void asyncclose([optional] in mozistoragecompletioncallback acallback); void begintransaction(); void begintransactionas(in print32 transactiontype); mozistoragestatement clone([optional] in boolean areadonly); void close(); void committransaction(); void createaggregatefunction(in autf8string afunctionname, in long anumarguments, in mozistorageaggregatefunction afunction); mozistorageasyncstatement createasyncstatement(in autf8string asqlstatement); void createfunction(in autf8string afunctionname, in long anumarguments, in mozistoragefunction afunction); mozistoragestatement createstatement(in autf8string asqlstatement); ...
... void createtable(in string atablename, in string atableschema); mozistoragependingstatement executeasync([array, size_is(anumstatements)] in mozistoragebasestatement astatements, in unsigned long anumstatements, [optional] in mozistoragestatementcallback acallback ); void executesimplesql(in autf8string asqlstatement); boolean indexexists(in autf8string aindexname); void preload(); obsolete since gecko 1.9 void removefunction(in autf8string afunctionname); mozistorageprogresshandler removeprogresshandler(); void rollbacktransaction(); void setgrowthincrement(in print32 aincrement, in autf8string adatabasename); mozistorageprogresshandler setprogresshandler(in print32 agranularity, in mozistorageprogressha...
...before closing the connection, you need to finalize all statements created for the connection.
...And 18 more matches
nsITextInputProcessor
/nsitextinputprocessor.idlscriptable this interface is a text input events synthesizer and manages its composition and modifier state 1.0 66 introduced gecko 38 inherits from: nsisupports last changed in gecko 38.0 (firefox 38.0 / thunderbird 38.0 / seamonkey 2.35) the motivation of this interface is to provide better api than nsidomwindowutils to dispatch key events and create, modify, and commit composition in higher level.
... you can create an instance of this interface with the following code: var tip = components.classes["@mozilla.org/text-input-processor;1"].
... createinstance(components.interfaces.nsitextinputprocessor); next, you need to get the rights to create composition or dispatch keyboard events with begininputtransaction() or begininputtransactionfortests(): if (!tip.begininputtransaction(window, callback)) { return; } if begininputtransaction() or begininputtransactionfortests() returns false, it means that another instance of nsitextinputprocessor has composition on the window or is dispatching an event.
...And 18 more matches
WebIDL bindings
for each interface, a namespace whose name is the name of the interface with binding appended is created, and all the things pertaining to that interface's binding go in that namespace.
...note that you may not need to do this if your objects can only be created, never gotten from other objects.
...(this allows the return value to be implicitly converted to a parentobject instance by the compiler via one of that class's non-explicit constructors.) if many instances of myinterface are expected to be created quicky, the return value of getparentobject should itself inherit from nswrappercache for optimal performance.
...And 18 more matches
BaseAudioContext - Web APIs
e-width="2px" /><text x="231" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">baseaudiocontext</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties baseaudiocontext.audioworklet read only secure context returns the audioworklet object, which can be used to create and manage audionodes in which javascript code implementing the audioworkletprocessor interface are run in the background to process audio data.
... baseaudiocontext.createanalyser() creates an analysernode, which can be used to expose audio time and frequency data and for example to create data visualisations.
... baseaudiocontext.createbiquadfilter() creates a biquadfilternode, which represents a second order filter configurable as several different common filter types: high-pass, low-pass, band-pass, etc baseaudiocontext.createbuffer() creates a new, empty audiobuffer object, which can then be populated by data and played via an audiobuffersourcenode.
...And 18 more matches
SVGPathElement - Web APIs
"><rect x="-99" y="65" width="140" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="-29" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgpathelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} note: in svg 2 the getpathsegatlength() and createsvgpathseg* methods were removed and the pathlength property and the gettotallength() and getpointatlength() methods were moved to svggeometryelement.
... svgpathelement.createsvgpathsegclosepath() returns a stand-alone, parentless svgpathsegclosepath object.
... svgpathelement.createsvgpathsegmovetoabs() returns a stand-alone, parentless svgpathsegmovetoabs object.
...And 18 more matches
File I/O - Archive of obsolete content
createinstance(components.interfaces.nsilocalfile); file.initwithpath("/home"); note: the path should be in the "native" form (for example"c:\\windows").
... queryinterface(components.interfaces.nsilocalfile).path); } creating folders fileutils.getdir() can create a folder automatically if it doesn't exist yet: components.utils.import("resource://gre/modules/fileutils.jsm"); var dir = fileutils.getdir("profd", ["dir"], true); the above example creates a folder called "dir" in the user's profile folder.
... you can also create a directory explicitly; for more information refer to nsifile.create().
...And 17 more matches
Templates - Archive of obsolete content
populating elements xul provides a method in which we create elements from data supplied by rdf, either from an rdf file or from an internal datasource.
... to allow the creation of elements based on rdf data, you need to provide a simple template which will be duplicated for each element that is created.
... the template is created using the template element.
...And 17 more matches
Getting started with React - Learn web development
we'll discover a little bit of detail about its background and use cases, set up a basic react toolchain on our local computer, and create and play with a simple starter app — learning a bit about how react works in the process.
... objective: to set up a local react development environment, create a start app, and understand the basics of how it works hello react as its official tagline states, react is a library for building user interfaces.
...these components can be composed together to create a full ui, and react abstracts away much of the rendering work, leaving you to concentrate on the ui design.
...And 17 more matches
Legacy layout methods - Learn web development
layout and grid systems before css grid layout it may seem surprising to anyone coming from a design background that css didn’t have an inbuilt grid system until very recently, and instead we seemed to be using a variety of sub-optimal methods to create grid-like designs.
...this knowledge will be helpful to you if you need to create fallback code for browsers that do not support newer methods, in addition to allowing you to work on existing projects which use these types of systems.
... it is worth bearing in mind, as we explore these systems, that none of them actually create a grid in the way that css grid layout creates a grid.
...And 16 more matches
Enc Dec MAC Using Key Wrap CertReq PKCS10 CSR
ding */ infile = pr_open(infilename, pr_rdonly, 0); if (!infile) { pr_fprintf(pr_stderr, "unable to open \"%s\" for reading.\n", infilename); rv = secfailure; goto cleanup; } /* sign using private key */ sgn = sgn_newcontext(sec_oid_pkcs1_md5_with_rsa_encryption, pk); if (!sgn) { pr_fprintf(pr_stderr, "unable to create context for signing\n"); rv = secfailure; goto cleanup; } rv = sgn_begin(sgn); if (rv != secsuccess) { pr_fprintf(pr_stderr, "problem while sgn_begin\n"); goto cleanup; } while ((nb = pr_read(infile, ibuf, sizeof(ibuf))) > 0) { rv = sgn_update(sgn, ibuf, nb); if (rv != secsuccess) { pr_fprintf(pr_stderr, "...
...6]; secstatus rv = secfailure; vfycontext *vfy = null; prfiledesc *infile = null; /* open the input file for reading */ infile = pr_open(infilename, pr_rdonly, 0); if (!infile) { pr_fprintf(pr_stderr, "unable to open \"%s\" for reading.\n", infilename); rv = secfailure; goto cleanup; } vfy = vfy_createcontext(pk, sigitem, sec_oid_pkcs1_md5_with_rsa_encryption, pwdata); if (!vfy) { pr_fprintf(pr_stderr, "unable to create context for verifying signature\n"); rv = secfailure; goto cleanup; } rv = vfy_begin(vfy); if (rv != secsuccess) { pr_fprintf(pr_stderr, "p...
... pr_gmtparameters, &printabletime); if ( warpmonths ) { printabletime.tm_month += warpmonths; now = pr_implodetime (&printabletime); pr_explodetime (now, pr_gmtparameters, &printabletime); } printabletime.tm_month += validitymonths; after = pr_implodetime (&printabletime); /* note that the time is now in micro-second unit */ validity = cert_createvalidity (now, after); if (validity) { cert = cert_createcertificate(serialnumber, (selfsign ?
...And 16 more matches
sample2
96]; prfiledesc *infile = null; sgncontext *sgn = null; /* open the input file for reading */ infile = pr_open(infilename, pr_rdonly, 0); if (!infile) { pr_fprintf(pr_stderr, "unable to open \"%s\" for reading.\n", infilename); rv = secfailure; goto cleanup; } /* sign using private key */ sgn = sgn_newcontext(sec_oid_pkcs1_md5_with_rsa_encryption, pk); if (!sgn) { pr_fprintf(pr_stderr, "unable to create context for signing\n"); rv = secfailure; goto cleanup; } rv = sgn_begin(sgn); if (rv != secsuccess) { pr_fprintf(pr_stderr, "problem while sgn_begin\n"); goto cleanup; } while ((nb = pr_read(infile, ibuf, sizeof(ibuf))) > 0) { rv = sgn_update(sgn, ibuf, nb); if (rv != secsuccess) { pr_fprintf(pr_stderr, "problem while sgn_update\n"); goto cleanup; } } rv = sgn_end(sgn, res); if (rv != secsuccess...
...e, seckeypublickey *pk, secitem *sigitem, secupwdata *pwdata) { unsigned int nb; unsigned char ibuf[4096]; secstatus rv = secfailure; vfycontext *vfy = null; prfiledesc *infile = null; /* open the input file for reading */ infile = pr_open(infilename, pr_rdonly, 0); if (!infile) { pr_fprintf(pr_stderr, "unable to open \"%s\" for reading.\n", infilename); rv = secfailure; goto cleanup; } vfy = vfy_createcontext(pk, sigitem, sec_oid_pkcs1_md5_with_rsa_encryption, pwdata); if (!vfy) { pr_fprintf(pr_stderr, "unable to create context for verifying signature\n"); rv = secfailure; goto cleanup; } rv = vfy_begin(vfy); if (rv != secsuccess) { pr_fprintf(pr_stderr, "problem while vfy_begin\n"); goto cleanup; } while ((nb = pr_read(infile, ibuf, sizeof(ibuf))) > 0) { rv = vfy_update(vfy, ibuf, nb); if (rv ...
...); goto cleanup; } } now = pr_now(); pr_explodetime (now, pr_gmtparameters, &printabletime); if ( warpmonths ) { printabletime.tm_month += warpmonths; now = pr_implodetime (&printabletime); pr_explodetime (now, pr_gmtparameters, &printabletime); } printabletime.tm_month += validitymonths; after = pr_implodetime (&printabletime); /* note that the time is now in micro-second unit */ validity = cert_createvalidity (now, after); if (validity) { cert = cert_createcertificate(serialnumber, (selfsign ?
...And 16 more matches
Starting WebLock
we have already created a module that implements most of the generic component functionality (e.g.
...when a gecko application starts up, registered components are created and notified via the general-purpose observer interface nsiobserver.
...for example, an object may be created and have its observe method called at startup, or it may register to be notified prior to xpcom shutdown.
...And 16 more matches
Applying styles and colors - Web APIs
we create a canvasgradient object by using one of the following methods.
... createlineargradient(x1, y1, x2, y2) creates a linear gradient object with a starting point of (x1, y1) and an end point of (x2, y2).
... createradialgradient(x1, y1, r1, x2, y2, r2) creates a radial gradient.
...And 16 more matches
Timing element visibility with the Intersection Observer API - Web APIs
articles each article is contained in an <article> element, styled like this: article { background-color: white; padding: 6px; } article:not(:last-child) { margin-bottom: 8px; } article h2 { margin-top: 0; } this creates article boxes with a white background which float atop the blue background, with a small margin around the article.
... the observer, adobserver, is created by calling intersectionobserver's constructor, passing in the callback function, intersectioncallback, and our options.
... if the document has just become visible, we reverse this process: first we go through previouslyvisibleads and set each one's dataset.lastviewstarted to the current document's time (in milliseconds since the document was created) using the performance.now() method.
...And 16 more matches
A re-introduction to JavaScript (JS tutorial) - JavaScript
javascript was created in 1995 by brendan eich while he was an engineer at netscape.
...however, starting with ecmascript 2015, let and const declarations allow you to create block-scoped variables.
... there are two basic ways to create an empty object: var obj = new object(); and: var obj = {}; these are semantically equivalent; the second is called object literal syntax and is more convenient.
...And 16 more matches
context-menu - Archive of obsolete content
for example, if your add-on needs to add a context menu item whenever the user visits a certain page, don't create the item when that page loads, and don't remove it when the page unloads.
... rather, create your item only once and supply a context that matches the target url.
... context menu items are displayed in the order created or in the case of sub menus the order added to the sub menu.
...And 15 more matches
Inheritance in JavaScript - Learn web development
previous overview: objects next with most of the gory details of oojs now explained, this article shows how to create "child" object classes (constructors) that inherit features from their "parent" classes.
...how do we create an object in javascript that inherits from another object?
... say we wanted to create a teacher class, like the one we described in our initial object-oriented definition, which inherits all the members from person, but also includes: a new property, subject — this will contain the subject the teacher teaches.
...And 15 more matches
NSS functions
cert_checkcertusage mxr 3.3 and later cert_comparename mxr 3.2 and later cert_comparevaliditytimes mxr 3.11 and later cert_completecrldecodeentries mxr 3.6 and later cert_convertanddecodecertificate mxr 3.9.3 and later cert_copyname mxr 3.4 and later cert_copyrdn mxr 3.5 and later cert_createava mxr 3.2.1 and later cert_createcertificate mxr 3.5 and later cert_createcertificaterequest mxr 3.2 and later cert_createname mxr 3.2.1 and later cert_createocspcertid mxr 3.6 and later cert_createocsprequest mxr 3.6 and later cert_createrdn mxr 3.2.1 and later cert_createsubjectcertlist ...
...mxr 3.4 and later cert_createvalidity mxr 3.5 and later cert_crlcacherefreshissuer mxr 3.7 and later cert_decodealtnameextension mxr 3.10 and later cert_decodeauthinfoaccessextension mxr 3.10 and later cert_decodeauthkeyid mxr 3.10 and later cert_decodeavavalue mxr 3.4 and later cert_decodebasicconstraintvalue mxr 3.2 and later cert_decodecertfrompackage mxr 3.4 and later cert_decodecertificatepoliciesextension mxr 3.2 and later cert_decodecertpackage mxr 3.2 and later cert_decodecrldistributionpoints mxr 3.10 and later cert_decodedercrl mxr 3.2 and later cert_decodedercrlwithflags mxr 3.6 and later ...
... pk11_clonecontext mxr 3.2 and later pk11_configurepkcs11 mxr 3.2 and later pk11_convertsessionprivkeytotokenprivkey mxr 3.6 and later pk11_convertsessionsymkeytotokensymkey mxr 3.6 and later pk11_copytokenprivkeytosessionprivkey mxr 3.11 and later pk11_createcontextbysymkey mxr 3.2 and later pk11_createdigestcontext mxr 3.2 and later pk11_creategenericobject mxr 3.12 and later pk11_createmergelog mxr 3.12 and later pk11_createpbealgorithmid mxr 3.2 and later pk11_createpbev2algorithmid mxr 3.12 and l...
...And 15 more matches
Storage
create statements to execute on the connection - mozistoragestatement.
... opening a connection javascript example of opening my_db_file_name.sqlite in the profile directory: components.utils.import("resource://gre/modules/services.jsm"); components.utils.import("resource://gre/modules/fileutils.jsm"); let file = fileutils.getfile("profd", ["my_db_file_name.sqlite"]); let dbconn = services.storage.opendatabase(file); // will also create the file if it does not exist likewise, the c++ would look like this: nscomptr<nsifile> dbfile; rv = ns_getspecialdirectory(ns_app_user_profile_50_dir, getter_addrefs(dbfile)); ns_ensure_success(rv, rv); rv = dbfile->append(ns_literal_string("my_db_file_name.sqlite")); ns_ensure_success(rv, rv); nscomptr<mozistorageservice> dbservice = do_getservice(moz_storage_se...
... no results to be returned if you do not need to get any results back, you can use mozistorageconnection.executesimplesql() api like this in javascript: dbconn.executesimplesql("create temp table table_name (column_name integer)"); similarly, the c++ looks like this: rv = mdbconn->executesimplesql(ns_literal_cstring("create temp table table_name (column_name integer)")); ns_ensure_success(rv, rv); results to be returned however, if you need to get results back, you should create the statement with the mozistorageconnection.createstatement() api like this in javascript: va...
...And 15 more matches
HTML documentation index - HTML: Hypertext Markup Language
WebHTMLIndex
3 applying color to html elements using css beginner, css, css colors, guide, html, html colors, html styles, styling html, color with css, there are lots of ways to add color to your html elements to create just the look you want.
...specifying the itemscope attribute for an element creates a new item, which results in a number of name-value pairs that are associated with the element.
... 28 slot global attributes, html, reference the slot global attribute assigns a slot in a shadow dom shadow tree to an element: an element with a slot attribute is assigned to the slot created by the <slot> element whose name attribute's value matches that slot attribute's value.
...And 15 more matches
Index - MDN Web Docs Glossary: Definitions of Web-related terms
52 crud glossary, infrastructure crud (create, read, update, delete) is an acronym for ways one can operate on stored data.
...in javascript, functions create a closure context.
...cryptanalysis creates techniques to break ciphers, in particular by methods more efficient than a brute-force search.
...And 14 more matches
IME handling guide
it handles native key events before or after focused application (depending on the platform) and creates a composition string (a.k.a.
...and the drop down menu is created by ime.
...if there is no proper textcomposition instance, it creates the instance.
...And 14 more matches
Mozilla DOM Hacking Guide
mozilla gives you the opportunity not only to use very powerful and complete dom support, but also to work on a world-class implementation of one of the greatest internet technologies ever created.
... the nsdomclassinfodata objects are created in the sclassinfodata array by explicitly initializing it.
... union { nsdomclassinfoconstructorfnc mconstructorfptr; nsdomclassinfoexternalconstructorfnc mexternalconstructorfptr; } u; this union is a pointer to a function typedef'ed: typedef nsiclassinfo* (*nsdomclassinfoconstructorfnc)(nsdomclassinfoid aid); or typedef nsiclassinfo* (*nsdomclassinfoexternalconstructorfnc) (const char* aname); it is initialized with the docreate member function of the helper class passed as third argument to the macro.
...And 14 more matches
Adding 2D content to a WebGL context - Web APIs
« previousnext » once you've successfully created a webgl context, you can start rendering into it.
...we need to define the shaders that will create the color for our simple scene as well as draw our object.
...the code below creates the two shaders by calling loadshader(), passing the type and source for the shader.
...And 14 more matches
Border-image generator - CSS: Cascading Style Sheets
-weight: bold; text-align: right; float: left; } #output .css-property .value { width: 65%; padding: 0 2.5%; word-break: break-all; float: left; } javascript content 'use strict'; /** * ui-slidersmanager */ var inputslidermanager = (function inputslidermanager() { var subscribers = {}; var sliders = []; var inputcomponent = function inputcomponent(obj) { var input = document.createelement('input'); input.setattribute('type', 'text'); input.style.width = 50 + obj.precision * 10 + 'px'; input.addeventlistener('click', function(e) { this.select(); }); input.addeventlistener('change', function(e) { var value = parsefloat(e.target.value); if (isnan(value) === true) setvalue(obj.topic, obj.value); else setvalue(obj.topic, value); }); return i...
...nput; }; var slidercomponent = function slidercomponent(obj, sign) { var slider = document.createelement('div'); var startx = null; var start_value = 0; slider.addeventlistener("click", function(e) { document.removeeventlistener("mousemove", slidermotion); setvalue(obj.topic, obj.value + obj.step * sign); }); slider.addeventlistener("mousedown", function(e) { startx = e.clientx; start_value = obj.value; document.body.style.cursor = "e-resize"; document.addeventlistener("mouseup", slideend); document.addeventlistener("mousemove", slidermotion); }); var slideend = function slideend(e) { document.removeeventlistener("mousemove", slidermotion); document.body.style.cursor = "auto"; slider.style.cursor = "pointer"; }; var slidermotion = functio...
...this.min : value; var input = new inputcomponent(this); var slider_left = new slidercomponent(this, -1); var slider_right = new slidercomponent(this, 1); slider_left.classname = 'ui-input-slider-left'; slider_right.classname = 'ui-input-slider-right'; if (name) { var info = document.createelement('span'); info.classname = 'ui-input-slider-info'; info.textcontent = name; node.appendchild(info); } node.appendchild(slider_left); node.appendchild(input); node.appendchild(slider_right); this.input = input; sliders[topic] = this; setvalue(topic, value); }; inputslider.prototype.setinputvalue = function setinputvalue() { this.input.value = this.value.tofixed(...
...And 14 more matches
platform/xpcom - Archive of obsolete content
var { class } = require('sdk/core/heritage'); var { unknown, factory } = require('sdk/platform/xpcom'); var { cc, ci } = require('chrome'); var contractid = '@me.org/helloworld'; // define a component var helloworld = class({ extends: unknown, get wrappedjsobject() this, hello: function() {return 'hello world';} }); // create and register the factory var factory = factory({ contract: contractid, component: helloworld }); // xpcom clients can retrieve and use this new // component in the normal way var wrapper = cc[contractid].createinstance(ci.nsisupports); var helloworld = wrapper.wrappedjsobject; console.log(helloworld.hello()); using class id you can specify a class id for the factory by setting the id optio...
...here's the example above, rewritten to use class id instead of contract id for lookup: var { class } = require('sdk/core/heritage'); var { unknown, factory } = require('sdk/platform/xpcom'); var { cc, ci, components } = require('chrome'); // define a component var helloworld = class({ extends: unknown, get wrappedjsobject() this, hello: function() {return 'hello world';} }); // create and register the factory var factory = factory({ component: helloworld }); var id = factory.id; // retrieve the factory by class id var wrapper = components.classesbyid[id].createinstance(ci.nsisupports); var helloworld = wrapper.wrappedjsobject; console.log(helloworld.hello()); replacing factories if the factory you create has the same contract id as an existing registered factory, then yo...
... contractidtocid('@me.org/helloworld'); var wrapper = components.classesbyid[id].createinstance(ci.nsisupports); the xpcom module exports a function factorybycontract to simplify this technique: var wrapper = xpcom.factorybycontract('@me.org/helloworld').createinstance(ci.nsisupports); registration by default, factories are registered and unregistered automatically.
...And 13 more matches
JavaScript Daemons Management - Archive of obsolete content
in the javascript programming language, daemons are all processes created by javascript timers or by a worker instantiation.
...in different objects (daemons) and then to create a constructor for such a class of objects (daemon) in order to standardize and simplify the instantiation of them.
...("daemon - not enough arguments"); } if (oowner) { this.owner = oowner }; this.task = ftask; if (isfinite(nrate) && nrate > 0) { this.rate = math.floor(nrate); } if (nlen > 0) { this.length = math.floor(nlen); } if (fonstart) { this.onstart = fonstart; } if (finit) { this.onstop = finit; finit.call(oowner, this.index, this.length, this.backw); } } /* create the daemon.blank() constructor and the global daemon.context object */ daemon.blank = function () {}; daemon.context = daemon.blank.prototype; /* make love with the gc :-) */ daemon.blank.prototype = /* important!
...And 13 more matches
Chapter 4: Using XPCOM—Implementing advanced processes - Archive of obsolete content
« previousnext » fixme: we should include a link to the mdc list of snippets fixme: we need to add a part about 'why and how to create your own component' c++/js this document was authored by hiroshi shimoda of clear code inc.
...listing 1 shows how you can use xpconnect to acquire references to xpcom services and create new xpcom objects.
...for other components, you can create as many instances as you need.
...And 13 more matches
Getting started with Svelte - Learn web development
then we will learn how to setup our development environment, create a sample app, understand the structure of the project, and see how to run it locally and build it for production.
... objective: to setup a local svelte development environment, create and build a starter app, and understand the basics of how it works.
... also see the following for more information: "what is npm" on nodejs.org "introducing npx" on the npm blog "the easiest way to get started with svelte" on the svelte blog creating your first svelte app the easiest way to create a starter app template is to just download the starter template application.
...And 13 more matches
Getting started with Vue - Learn web development
in this article we'll look at a little bit of vue background, learn how to install it and create a new project, study the high-level structure of the whole project and an individual component, see how to run the project locally, and get it prepared to start building our example.
... objective: to setup a local vue development environment, create a starter app, and understand the basics of how it works.
...this allows you to create markup managed entirely by vue, which can improve developer experience and performance when dealing with complex applications.
...And 13 more matches
Setting up your own test automation environment - Learn web development
create a new file inside your project directory called google_test.js: give it the following contents, then save it: const webdriver = require('selenium-webdriver'), by = webdriver.by, until = webdriver.until; const driver = new webdriver.builder() .forbrowser('firefox') .build(); driver.get('http://www.google.com'); driver.findelement(by.name('q')).sendkeys('webdriver'); driver.s...
... create another new file inside your project directory called google_test_multiple.js.
...iver - google search') { console.log('test passed'); } else { console.log('test failed'); } driver.quit(); }); }); } in terminal, make sure you are inside your project folder, then enter the following command: node google_test_multiple if you are using a mac and do decide to test safari, you might get an error message along the lines of "could not create a session: you must enable the 'allow remote automation' option in safari's develop menu to control safari via webdriver." if you get this, follow the given instruction and try again.
...And 13 more matches
nsIAppShellService
(firefox 8.0 / thunderbird 8.0 / seamonkey 2.5) implemented by: @mozilla.org/appshell/appshellservice;1 as a service: var appshellservice = components.classes["@mozilla.org/appshell/appshellservice;1"] .getservice(components.interfaces.nsiappshellservice); method overview void closetoplevelwindow(in nsixulwindow awindow); obsolete since gecko 1.8 void createhiddenwindow(in nsiappshell aappshell); native code only!
... boolean createstartupstate(in long awindowwidth, in long awindowheight); obsolete since gecko 1.8 nsixulwindow createtoplevelwindow(in nsixulwindow aparent, in nsiuri aurl, in pruint32 achromemask, in long ainitialwidth, in long ainitialheight, in nsiappshell aappshell); nsiwebnav createwindowlessbrowser (in bool aischrome) void destroyhiddenwindow(); void doprofilestartup(in nsicmdlineservice acmdlineservice, in boolean caninteract); obsolete since gecko 1.8 void ensure1window(in nsicmdlineservice acmdlineservice); obsolete since gecko 1.8 void enterlastwindowclosingsurvivalarea(); obsolete since gecko 1.8 void exitlastwindowclosingsurvivalarea(); obsolete since gecko 1.8 void gethiddenwindowandjscontext(out nsid...
... hiddendomwindow nsidomwindow return the (singleton) application hidden window, automatically created and maintained by this appshellservice.
...And 13 more matches
nsIDocShell
do not create an instance directly.
...method overview void addsessionstorage(in nsiprincipal principal, in nsidomstorage storage); void addstate(in nsivariant adata, in domstring atitle, in domstring aurl, in boolean areplace); void beginrestore(in nsicontentviewer viewer, in boolean top); void createaboutblankcontentviewer(in nsiprincipal aprincipal); void createloadinfo(out nsidocshellloadinfo loadinfo); void detacheditorfromwindow(); violates the xpcom interface guidelines void finishrestore(); void firepagehidenotification(in boolean isunload); native code only!
...obsolete since gecko 1.8 nsisimpleenumerator getdocshellenumerator(in long aitemtype, in long adirection); nsidomstorage getsessionstorageforprincipal(in nsiprincipal principal, in domstring documenturi, in boolean create); nsidomstorage getsessionstorageforuri(in nsiuri uri, in domstring documenturi); void historypurged(in long numentries); void internalload(in nsiuri auri, in nsiuri areferrer, in nsisupports aowner, in pruint32 aflags, in wstring awindowtarget, in string atypehint, in nsiinputstream apostdatastream, in nsiinputstream aheadersstream, in unsigned long aloadflags, in nsishentry ashentry, in boolean firstparty, out nsidocshell adocshell, out nsirequest arequest); native code...
...And 13 more matches
nsIXPConnect
void clearallwrappednativesecuritypolicies(); nsixpconnectjsobjectholder createsandbox(in jscontextptr cx, in nsiprincipal principal); native code only!
... nsistackframe createstackframelocation(in pruint32 alanguage, in string afilename, in string afunctionname, in print32 alinenumber, in nsistackframe acaller); void debugdump(in short depth); void debugdumpevalinjsstackframe(in pruint32 aframenumber, in string asourcetext); void debugdumpjsstack(in prbool showargs, in prbool showlocals, in prbool showthisprops); void debugdumpobject(in nsisupports acomobj, in short depth); [noscript,notxpcom] prbool definedomquickstubs(in jscontextptr cx, in jsobjectptr proto, in pruint32 flags, in pruint32 interfacecount, [array, size_is(interfacecount)] in nsiidptr interfacearray); jsval evalinsandboxobject(in astring source, in jscontextptr cx, in nsixpconnectjsobjectholder sandbox, in prbool re...
... exceptions thrown missing exception missing description native code only!createsandbox create a sandbox for evaluating code in isolation using evalinsandboxobject().
...And 13 more matches
Add to iPhoto
this.cfstringcreatewithcharacters = this.lib.declare("cfstringcreatewithcharacters", ctypes.default_abi, this.cfstringref, // returns a new cfstringref ctypes.voidptr_t, // allocator ctypes.jschar.ptr, // pointer to the unicode string c...
...types.int32_t); // length of the string cfstringcreatewithcharacters() is used to create a new cfstring object using a unicode string as the source string, which is copied into the new cfstring object.
... let's take a look at two of the routines declared here: this.cfurlcreatefromfilesystemrepresentation = this.lib.declare("cfurlcreatefromfilesystemrepresentation", ctypes.default_abi, this.cfurlref, // returns ctypes.voidptr_t, // input: allocator ctypes.unsigned_char.ptr, // input: pointer to string ...
...And 13 more matches
Mozilla
there are two ways to create a sidebar for firefox users: the social api and an extension.
... creating a language pack to create a language pack, or a localization repack, you first need to go through the initial setup process.
...some of them are simply the ones i use because i like them, while others are scripts that i've created to speed up the work.
...And 13 more matches
DOMMatrixReadOnly - Web APIs
dommatrixreadonly.flipx() returns a new dommatrix created by flipping the source matrix around its x-axis.
... dommatrixreadonly.flipy() returns a new dommatrix created by flipping the source matrix around its y-axis.
... dommatrixreadonly.inverse() returns a new dommatrix created by inverting the source matrix.
...And 13 more matches
Using files from web applications - Web APIs
function handlefiles(files) { for (let i = 0; i < files.length; i++) { const file = files[i]; if (!file.type.startswith('image/')){ continue } const img = document.createelement("img"); img.classlist.add("obj"); img.file = file; preview.appendchild(img); // assuming that "preview" is the div output where the content will be displayed.
...for each file that is an image, we create a new img element.
... using object urls the dom url.createobjecturl() and url.revokeobjecturl() methods let you create simple url strings that can be used to reference any data that can be referred to using a dom file object, including local files on the user's computer.
...And 13 more matches
Example and tutorial: Simple synth keyboard - Web APIs
the keyboard first, we create space to build the keyboard into.
... the volume control first we create the <div> to contain the settings bar, so it can be styled as needed.
... let notefreq = null; let customwaveform = null; let sineterms = null; let cosineterms = null; finally, global variables that will be used when constructing waveforms are created: notefreq will be an array of arrays; each array represents one octave, each of which contains one entry for each note in that octave.
...And 13 more matches
Using Web Workers - Web APIs
once created, a worker can send messages to the javascript code that created it by posting messages to an event handler specified by that code (and vice versa).
... web workers api a worker is an object created using a constructor (e.g.
... content security policy workers are considered to have their own execution context, distinct from the document that created them.
...And 13 more matches
Implementing a Microsoft Active Accessibility (MSAA) Server - Accessibility
msaa decision-making guide use msaa whenever you have created custom controls where you're handling the drawing, mouse and keyboard accessibility in your own code.
...there's a very good chance they won't ask for more than the events marked [important]: event_system_sound event_system_alert [can be important, to have auto-speaking for newly created role_alerts] event_system_foreground event_system_menustart [important] event_system_menuend [important] event_system_menupopupstart [important] event_system_menupopupend [important] event_system_capturestart event_system_captureend event_system_movesizestart event_system_movesizeend event_system_contexthelpstart event_system_contexthelpend event_s...
...ystem_dragdropstart event_system_dragdropend event_system_dialogstart event_system_dialogend event_system_scrollingstart event_system_scrollingend [possibly important, talk to at vendor] event_system_switchstart event_system_switchend event_system_minimizestart event_system_minimizeend event_object_create [don't implement, watching system generated versions of this event causes assistive technology crashes] event_object_destroy [don't implement, watching system generated versions of this event causes assistive technology crashes] event_object_show [can be important, depending on project] event_object_hide [can be important, depending on project] event_object_reorder [important for mutating docs] event_object_focus [important] event_o...
...And 13 more matches
Layout using named grid lines - CSS: Cascading Style Sheets
in previous guides we’ve looked at placing items by the lines created by defining grid tracks and also how to place items using named template areas.
...to demonstrate i’ll use the simple layout created in the guide on line-based placement.
... this time i’ll create the grid using named lines.
...And 13 more matches
SeaMonkey - making custom toolbar (SM ver. 1.x) - Archive of obsolete content
your operating system normally provides them: a way to create and work with files and directories a text editor for plain text files character encoding some text editors have a setting for character encoding.
...to check your text editor, create a plain text file named test.txt.
... create a new directory named: custombutton perform the following steps in this new directory, creating five files there.
...And 12 more matches
Custom toolbar button - Archive of obsolete content
your operating system normally provides them: a way to create and work with files and directories a text editor for plain text files character encoding some text editors have a setting for character encoding.
... to check your text editor, create a plain text file named test.txt.
...in the extensions directory, create a new directory with the following name.
...And 12 more matches
Simple Menu Bars - Archive of obsolete content
« previousnext » in this section, we'll see how to create a menu bar with menus on it.
...you can also create popup menus.
... the menu features of xul consist of a number of different elements which allow you to create menu bars or popup menus.
...And 12 more matches
LiveConnect Overview - Archive of obsolete content
when a javascript object is sent to java, the runtime engine creates a java wrapper of type jsobject; when a jsobject is sent from java to javascript, the runtime engine unwraps it to its original javascript object type.
...for example, you can create a java string object and assign it to the javascript variable mystring by using the new operator with the java constructor, as follows: var mystring = new java.lang.string("hello world"); in the previous example, the variable mystring is a javaobject because it holds an instance of the java object string.
...to create an instance of the helloworld class in redwood, you access the constructor of the class as follows: var red = new packages.redwood.helloworld(); you can also access classes in the default package (that is, classes that don't explicitly name a package).
...And 12 more matches
The HTML5 input types - Learn web development
objective: to understand the newer input type values available to create native form controls, and how to implement them using html.
... search field search fields are intended to be used to create search boxes on pages and apps.
... phone number field a special field for filling in phone numbers can be created using tel as the value of the type attribute: <input type="tel" id="tel" name="tel"> when accessed via a touch device with a dynamic keyboard, most devices will display a numeric keypad when type="tel" is encountered, meaning this type is useful whenever a numeric keypad is useful, and doesn't just have to be used for telephone numbers.
...And 12 more matches
What is JavaScript? - Learn web development
javascript is a scripting language that enables you to create dynamically updating content, control multimedia, animate images, and pretty much everything else.
...in the above example we take the string "player 1: " and join it to the name variable to create the complete text label, e.g.
... the canvas and webgl apis allow you to create animated 2d and 3d graphics.
...And 12 more matches
Mail composition back end
createandsendmessage the createandsendmessage method will create an rfc822 message and send it all in one operation as well as providing the ability to save disk files for later use.
... ns_imethod createandsendmessage( nsieditorshell *aeditor, - the editor object for the mail compose operation.
...this can be nsnull if you want to do the delivery operation "blind" sendmessagefile the sendmessagefile method will let the caller send a message that has been created by another process (note: createandsendmessage can accomplish this task).
...And 12 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.
...in normal-mode streams, the browser calls the plug-in to tell it when a stream is created and to push more data.
... in contrast, for streams produced by the plug-in, the plug-in calls the plug-in api methods npp_newstream, npp_write, and npp_destroystream to create a stream, push data into it, and delete it.
...And 12 more matches
In depth: Microtasks and the JavaScript runtime environment - Web APIs
there are three types of code that create a new execution context: the global context is the execution context created to run the main body of your code; that is, any code that exists outside of a javascript function.
...this is frequently referred to as a "local context." using the ill-advised eval() function also creates a new execution context.
...tch(language) { case "es": greeting = `¡hola, ${user}!`; break; case "en": default: greeting = `hello, ${user}!`; break; } return greeting; } outputelem.innerhtml += localgreeting(user) + "<br>\r"; } greetuser("mike"); greetuser("teresa"); greetuser("veronica"); this short program contains three execution contexts, some of which are created and destroyed several times over the course of the program's execution.
...And 12 more matches
HTML elements reference - HTML: Hypertext Markup Language
WebHTMLElement
this page lists all the html elements, which are created using tags.
...use the sectioning elements to create a broad outline for your page content, including header and footer navigation, and heading elements to identify sections of content.
... element description <a> the html <a> element (or anchor element), with its href attribute, creates a hyperlink to web pages, files, email addresses, locations in the same page, or anything else a url can address.
...And 12 more matches
Function.prototype.bind() - JavaScript
the bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
...when using bind to create a function (supplied as a callback) inside a settimeout, any primitive value passed as thisarg is converted to object.
... description the bind() function creates a new bound function, which is an exotic function object (a term from ecmascript 2015) that wraps the original function object.
...And 12 more matches
Understanding WebAssembly text format - WebAssembly
declaring globals in webassembly webassembly has the ability to create global variable instances, accessible from both javascript and importable/exportable across one or more webassembly.module instances.
... to create an equivalent value using javascript, you'd use the webassembly.global() constructor: const global = new webassembly.global({value: "i32", mutable: true}, 0); webassembly memory the above example is a pretty terrible logging function: it only prints a single integer!
... the key is that javascript can create webassembly linear memory instances via the webassembly.memory() interface, and access an existing memory instance (currently you can only have one per module instance) using the associated instance methods.
...And 12 more matches
jpm - Archive of obsolete content
on debian and ubuntu, this can be remedied by ensuring you installed the compatibility package, nodejs-legacy: sudo apt-get install nodejs-legacy on other distributions, you may have to create a local symlink to nodejs manually: sudo ln -s "$(which nodejs)" /usr/local/bin/node installing jpm after you have npm installed and node on your path, install jpm just as you would any other npm package.
... command reference jpm supports the following commands: jpm init create a skeleton add-on as a starting point for your add-on.
... create a new directory, change into it, and run jpm init.
...And 11 more matches
Migrate apps from Internet Explorer to Mozilla - Archive of obsolete content
the latest w3c html specification created the title attribute, which is meant to contain a detailed description of the link.
...methods mozilla uses to manipulate content method description appendchild( anode ) creates a new child node.
... createelement( atagname ) creates and returns a new and parentless dom node of the type specified by atagname.
...And 11 more matches
Modularization techniques - Archive of obsolete content
introduction the purpose of this document is provide all the information you need to create a new mozilla module or break existing code into a module.
... /* * the nsifactory interface */ class nsifactory: public nsisupports { public: ns_imethod createinstance(nsisupports *aouter, const nsiid &aiid, void **aresult) = 0; ns_imethod lockfactory(prbool alock) = 0; the reason for using factories is that it provides a mechanism for creating an object without having access to the class declaration for that object.
...we've created something called the nscomponentmanager.
...And 11 more matches
Trees - Archive of obsolete content
ArchiveMozillaXULTutorialTrees
« previousnext » xul provides a way to create tabular or hierarchical lists using a tree.
...both can be used to create tables of data with multiple rows and columns, and both may contain column headers.
... the second part, the tree body, contains the data to appear in the tree and is created with a treechildren tag.
...And 11 more matches
XPCOM Interfaces - Archive of obsolete content
for example, if we wanted to create a mail application, we would need to write scripts which would connect to mail servers to retrieve and send mail.
...an interface would need to be created which describes properties and functions that can be performed on files.
...you can get a component using javascript code like that below: var afile = components.classes["@mozilla.org/file/local;1"].createinstance(); the file component is retrieved and stored in the afile variable.
...And 11 more matches
Building up a basic demo with A-Frame - Game development
environment setup let's start by setting up an environment to create something with a-frame.
... create a new directory to store your project in.
... html structure the first step is to create an html document — inside your project directory, create a new index.html file, and save the follow html inside it: <!doctype html> <html> <head> <meta charset="utf-8"> <title>mdn games: a-frame demo</title> <script src="aframe.min.js"></script> </head> <body> <!-- html goes here --> </body> </html> this contains some basic information like the document charset and <title>.
...And 11 more matches
Building up a basic demo with the PlayCanvas engine - Game development
playcanvas application to begin developing our game we have to create the playcanvas application first (using the given <canvas> element), and then start the update loop.
... var camera = new pc.entity(); camera.addcomponent("camera", { clearcolor: new pc.color(0.8, 0.8, 0.8) }); app.root.addchild(camera); camera.setposition(0, 0, 7); the code above will create a new entity.
...this allows us to make some space to visualize the objects that we will create later on.
...And 11 more matches
Grids - Learn web development
they help us to create designs where elements don’t jump around or change width as we move from page to page, providing greater consistency on our websites.
... creating your grid in css having decided on the grid that your design needs, you can use css grid layout to create that grid in css and place items onto it.
... we will look at the basic features of grid layout first and then explore how to create a simple grid system for your project.
...And 11 more matches
Graceful asynchronous programming with Promises - Learn web development
so instead of waiting for the user, getting the chosen devices enabled, and directly returning the mediastream for the stream created from the selected sources, getusermedia() returns a promise which is resolved with the mediastream once it's available.
...status: ${response.status}`); } else { return response.blob(); } }); each call to .then() creates a new promise.
...add the following lines inside the curly braces: let objecturl = url.createobjecturl(myblob); let image = document.createelement('img'); image.src = objecturl; document.body.appendchild(image); here we are running the url.createobjecturl() method, passing it as a parameter the blob returned when the second promise fulfills.
...And 11 more matches
Adding a new event
the latter is used only for abstruct super event class whose instance will never be created.
... virtual widgetevent* duplicate() const moz_override this method should create a new instance with copying its members except widget.
... create webidl of the event write a dom event definition with webidl.
...And 11 more matches
Localizing with Koala
introduction this tutorial will guide you through making a couple of changes to firefox's user interface using koala, an add-on for komodo edit created to help localizing mozilla.
... before you can use them, you need to create a new koala project.
... creating a new project create a new koala project by going to file > new > new project from template...
...And 11 more matches
sslfnc.html
you must use one of these functions to create a server cache.
... this function creates two caches: theserver session id cache (also called the server session cache, or server cache), and theclient-auth certificate cache (also called the client cert cache, or client auth cache).
... initializing multi-processing with a shared ssl server cache to start a multi-processing application, the initial parent process calls ssl_configmpserversidcache, and then creates child processes, by one of these methods: call fork and then exec (unix) call createprocess (win32) call pr_createprocess (both unix and win32) it is essential that the parent allow the child to inherit the file descriptors.
...And 11 more matches
Accessing the Windows Registry Using XPCOM
a simple example here's a simple example showing how to read your windows productid: var wrk = components.classes["@mozilla.org/windows-registry-key;1"] .createinstance(components.interfaces.nsiwindowsregkey); wrk.open(wrk.root_key_local_machine, "software\\microsoft\\windows\\currentversion", wrk.access_read); var id = wrk.readstringvalue("productid"); wrk.close(); this example, while simple, shows several important things about using the interface.
... first, you must use createinstance() to get an object implementing this interface, not getservice().
...if you want to create a new key, you can use the create() method, which takes the same parameters as open().
...And 11 more matches
Relationship of grid layout to other layout methods - CSS: Cascading Style Sheets
the same layout with css grids in this next example, i create the same layout using grid.
...we do not need to set anything on the items themselves; they will lay themselves out one into each cell of the created grid.
...when you use css grid layout you create a layout and then you place items into it, or you allow the auto-placement rules to place the items into the grid cells according to that strict grid.
...And 11 more matches
Indexed collections - JavaScript
creating an array the following statements create equivalent arrays: let arr = new array(element0, element1, ..., elementn) let arr = array(element0, element1, ..., elementn) let arr = [element0, element1, ..., elementn] element0, element1, ..., elementn is a list of values for the array's elements.
... to create an array with non-zero length, but without any items, either of the following can be used: // this...
...otherwise, an array with a single element (the provided value) will be created.
...And 11 more matches
Using the WebAssembly JavaScript API - WebAssembly
next, let’s create a simple html file called index.html in the same directory as your wasm file (can use our simple template if you haven’t got one easily available).
...create a <script></script> element in your html file, and add the following code to it: var importobject = { imports: { imported_func: arg => console.log(arg) } }; streaming the webassembly module new in firefox 58 is the ability to compile and instantiate webassembly modules directly from underlying sources.
...in addition, newer implementations can also create shared memories, which can be transferred between window and worker contexts using postmessage(), and used in multiple places.
...And 11 more matches
Classes and Inheritance - Archive of obsolete content
a class is a blueprint from which individual objects are created.
...the sdk uses a special constructor internally, known as class, to create constructors that behave properly with respect to inheritance.
...to illustrate this, let's define a simple constructor for a class shape: function shape(x, y) { this.x = x; this.y = y; } we can now use this constructor to create instances of shape: let shape = new shape(2, 3); shape instanceof shape; // => true shape.x; // => 2 shape.y; // => 3 the keyword new tells javascript that we are performing a constructor call.
...And 10 more matches
/loader - Archive of obsolete content
create commonjs module loaders.
... create somewhat standardized js environments that people doing non-browser js are familiar with.
... create task specific loaders with restricted module access.
...And 10 more matches
dev/panel - Archive of obsolete content
with the dev/panel module, you can create your own panels in the toolbox: the panel gets a tab in the toolbox toolbar which enables the user to open it: you specify the panel's content and behavior using html, css, and javascript.
... when the panel's created, the framework passes it a debuggee: this is a messageport object that you can use to exchange json messages with the browser that the developer tools are currently debugging.
... optional setup function a function that will be called when the panel is created.
...And 10 more matches
Layout System Overview - Archive of obsolete content
given a content model, how does the layout system actually create the presentation?
...layout creates frames for content based on either the specific html rules for an element or based on the css display type of the element.
...the layout module looks at the 'display' field of the style context to determine what kind of frame to create (block, inline, table, etc.).
...And 10 more matches
Monitoring downloads - Archive of obsolete content
in particular, it needs to get an instance of the download manager's nsidownloadmanager interface and create the database into which its data will be stored.
... .get("profd", components.interfaces.nsifile); this.dbfile.append("downloadlogger.sqlite"); // get access to the storage service and open the database this.storageservice = components.classes["@mozilla.org/storage/service;1"] .getservice(components.interfaces.mozistorageservice); var dbconn = this.storageservice.opendatabase(this.dbfile); // now create the table; if it already exists, this fails, but we don't care!
... dbconn.executesimplesql("create table items (source text, size integer," + " starttime integer, endtime integer," + " speed real, status integer)"); dbconn.close(); }, this is fairly simple stuff.
...And 10 more matches
Windows Media in Netscape - Archive of obsolete content
client-side detection using javascript objects internet explorer implements the activexobject object to create new instances of activex controls.
... netscape 7.1 introduces geckoactivexobject which can be used in a similar way to create instances of the windows media player.
...activexobject both geckoactivexobject and activexobject work very similarly, with one key difference: both take a programmatic id (progid) and use it to create a reference to the windows media player.
...And 10 more matches
Localizing without a specialized tool
from the create a new localization document, an interested localizer can follow a technical step-by-step process that starts the localization process by focusing on how to localize two of the primary types of localization files (dtd and properties) used in the mozilla source code.
... with that document, users can see immediately two localized files in their user interface by following closely and carefully the steps to create a language pack or a binary file that is ready for installation.
... repeating the process allows a localizer to create a testable package to see his or her work as they progress to a final version.
...And 10 more matches
Enc Dec MAC Output Public Key as CSR
(pk11symkey *key, unsigned char *iv, unsigned int ivlen, ck_mechanism_type type, ck_attribute_type operation) { secitem ivitem = { sibuffer, iv, ivlen }; pk11context *ctx = null; secitem *secparam = pk11_paramfromiv(type, &ivitem); if (secparam == null) { pr_fprintf(pr_stderr, "crypt failed : secparam null\n"); return null; } ctx = pk11_createcontextbysymkey(type, operation, key, secparam); if (ctx == null) { pr_fprintf(pr_stderr, "crypt failed : can't create a context\n"); goto cleanup; } cleanup: if (secparam) { secitem_freeitem(secparam, pr_true); } return ctx; } /* * common encryption and decryption code */ secstatus crypt(pk11context *ctx, unsigned char *out, unsigned int *outl...
... signalgtag; secitem result; secstatus rv = secsuccess; print32 numbytes; void *exthandle; prarenapool *arena = null; prfiledesc *outfile = null; /* open the certificate request file to write */ outfile = pr_open(certreqfilename, pr_create_file | pr_rdwr | pr_truncate, 00660); if (!outfile) { pr_fprintf(pr_stderr, "unable to open \"%s\" for writing (%ld, %ld).\n", certreqfilename, pr_geterror(), pr_getoserror()); goto cleanup; } /* create info about public key */ spki = seckey_createsubjectpublickeyinfo(pubk); if (!spki) { pr_fprintf(pr_stderr, "unabl...
...e to create subject public key\n"); rv = secfailure; goto cleanup; } /* generate certificate request */ cr = cert_createcertificaterequest(subject, spki, null); if (!cr) { pr_fprintf(pr_stderr, "unable to make certificate request\n"); rv = secfailure; goto cleanup; } arena = port_newarena(der_default_chunksize); if (!arena) { fprintf(stderr, "out of memory"); rv = secfailure; goto cleanup; } exthandle = cert_startcertificaterequestattributes(cr); if (exthandle == null) { port_freearena (arena, pr_false); rv = secfailure; goto cleanup; } cert_finishextensions(exthandle); cert_finishcertificaterequestattributes(cr); /* der encode the request */ en...
...And 10 more matches
NSS tools : signtool
e [[-c compression level] ] [[-d cert-dir] ] [[-i installer script] ] [[-m metafile] ] [[-x name] ] [[-f filename] ] [[-t|--token tokenname] ] [[-e extension] ] [[-o] ] [[-z] ] [[-x] ] [[--outfile] ] [[--verbose value] ] [[--norecurse] ] [[--leavearc] ] [[-j directory] ] [[-z jarfile] ] [[-o] ] [[-p password] ] [directory-tree] [archive] description the signing tool, signtool, creates digital signatures and uses a java archive (jar) file to associate the signatures with files in a directory.
... before you can use netscape signing tool to sign files, you must have an object-signing certificate, which is a special certificate whose associated private key is used to create digital signatures.
... for testing purposes only, you can create an object-signing certificate with netscape signing tool 1.3.
...And 10 more matches
Necko Architecture
uris (recall that a url is just one implementation of a uri) can be created as individual components independently of necko, or they can be retrieved via the nsiioservice interface.
...there is a 1-to-1 relationship between uris and channels (if you go so far as to create a channel from a uri, which is not required if all you need is a parsed representation of a uri string).
...a protocol handler's primary responsibility is to create channels for the scheme it has registered to handle.
...And 10 more matches
Building the WebLock UI
specifically, the user interface we create in this chapter will be overlaid into the statusbar of the browser component, where it will provide a small icon the user can click to access the web lock interface.
...in the following chapter we'll describe how you can take these files and create a package, an installable archive that includes the weblock component and the new ui.
...the second section, xul, describes the xml-based user interface language (xul) and how you can use it to create a dialog that provides access to the weblock component and its services.
...And 10 more matches
nsIFile
with an nsifile you can navigate to ancestors or descendants without having to deal with the different path separators used on different platforms, query the state of any file or directory at the position represented by the nsifile and create, move or copy items in the filesystem.
... to create an nsifile from a path you can use fileutils.jsm: var fileutils = cu.import("resource://gre/modules/fileutils.jsm").fileutils var nsifile = new fileutils.file( filename ) note: nsilocalfile was merged with this interface in gecko 14.
... void create(in unsigned long type, in unsigned long permissions); void createunique(in unsigned long type, in unsigned long permissions); boolean equals(in nsifile infile); boolean exists(); acstring getrelativedescriptor(in nsifile fromfile); void initwithfile(in nsifile afile); void initwithnativepath(in acstring filepath); void initwithpath(in...
...And 10 more matches
Using the clipboard
const gclipboardhelper = components.classes["@mozilla.org/widget/clipboardhelper;1"] .getservice(components.interfaces.nsiclipboardhelper); gclipboardhelper.copystring("put me on the clipboard, please."); this example will first create a clipboard helper and then copy a short string to the clipboard.
...the clipboard model in mozilla requires you to perform the following steps to copy data: create an xpcom wrapper for the data which you want to put on the clipboard.
... create a transferring object.
...And 10 more matches
Debugger.Object - Firefox Developer Tools
spidermonkey creates exactly one debugger.object instance for each debuggee object it presents to a given debugger instance: if the debugger encounters the same object through two different routes (perhaps two functions are called on the same object), spidermonkey presents the same debugger.object instance to the debugger each time.
... while most debugger.object instances are created by spidermonkey in the process of exposing debuggee’s behavior and state to the debugger, the debugger can use debugger.object.prototype.makedebuggeevalue to create debugger.object instances for given debuggee objects, or use debugger.object.prototype.copy and debugger.object.prototype.create to create new objects in debuggee compartments, allocated as if by particular debuggee globals.
... environment if the referent is a function that is debuggee code, a debugger.environment instance representing the lexical environment enclosing the function when it was created.
...And 10 more matches
RTCPeerConnection - Web APIs
"50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="236" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">rtcpeerconnection</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructorrtcpeerconnection() the rtcpeerconnection() constructor returns a newly-created rtcpeerconnection, which represents a connection between the local device and a remote peer.propertiesalso inherits properties from: eventtargetcantrickleicecandidatesthe read-only rtcpeerconnection property cantrickleicecandidates returns a boolean which indicates whether or not the remote peer can accept trickled ice candidates.connectionstate the read-only connectionstate property of the rtc...
...this event, of type rtcdatachannelevent, is sent when an rtcdatachannel is added to the connection by the remote peer calling createdatachannel().onicecandidatethe rtcpeerconnection property onicecandidate property is an eventhandler which specifies a function to be called when the icecandidate event occurs on an rtcpeerconnection instance.
...instead of using this obsolete method, you should instead use addtrack() once for each track you wish to send to the remote peer.addtrack()the rtcpeerconnection method addtrack() adds a new media track to the set of tracks which will be transmitted to the other peer.close() the rtcpeerconnection.close() method closes the current peer connection.createanswer() the createanswer() method on the rtcpeerconnection interface creates an sdp answer to an offer received from a remote peer during the offer/answer negotiation of a webrtc connection.
...And 10 more matches
Using readable streams - Web APIs
browser support you can consume fetch body objects as streams and create your own custom readable streams in firefox 65+ and chrome 42+ (and equivalent chromium-based browsers).
...this is done using the readablestream.getreader() method: // fetch the original image fetch('./tortoise.png') // retrieve its body as readablestream .then(response => response.body) .then(body => { const reader = body.getreader(); invoking this method creates a reader and locks it to the stream — no other reader may read this stream until this reader is released, e.g.
...for example, our simple stream pump example goes on to enqueue each chunk in a new, custom readablestream (we will find more about this in the next section), then create a new response out of it, consume it as a blob, create an object url out of that blob using url.createobjecturl(), and then display it on screen in an <img> element, effectively creating a copy of the image we originally fetched.
...And 10 more matches
Auto-placement in CSS Grid Layout - CSS: Cascading Style Sheets
in addition to the ability to place items accurately onto a created grid, the css grid layout specification contains rules that control what happens when you create a grid and do not place some or all of the child items.
...ffa94d; border-radius: 5px; background-color: #ffd8a8; padding: 1em; color: #d9480f; } .wrapper { display: grid; grid-template-columns: repeat(3, 1fr); grid-gap: 10px; } <div class="wrapper"> <div>one</div> <div>two</div> <div>three</div> <div>four</div> <div>five</div> </div> default rules for auto-placement as you can see with the above example, if you create a grid all child items will lay themselves out one into each grid cell.
...if you have created additional rows using the grid-template-rows property then grid will continue placing items in these rows.
...And 10 more matches
Using CSS gradients - CSS: Cascading Style Sheets
you can choose between three types of gradients: linear (created with the linear-gradient() function), radial (created with radial-gradient()), and conic (created with the conic-gradient() function).
... you can also create repeating gradients with the repeating-linear-gradient(), repeating-radial-gradient(), and repeating-conic-gradient() functions.
... we'll start by introducing linear gradients, then introduce features that are supported in all gradient types using linear gradients as the example, then move on to radial, conic and repeating gradients using linear gradients a linear gradient creates a band of colors that progress in a straight line.
...And 10 more matches
Closures - JavaScript
in javascript, closures are created every time a function is created, at function creation time.
... lexical scoping consider the following example code: function init() { var name = 'mozilla'; // name is a local variable created by init function displayname() { // displayname() is the inner function, a closure alert(name); // use variable declared in the parent function } displayname(); } init(); init() creates a local variable called name and a function called displayname().
...this environment consists of any local variables that were in-scope at the time the closure was created.
...And 10 more matches
Functions - JavaScript
(theobject) { theobject.make = 'toyota'; } var mycar = {make: 'honda', model: 'accord', year: 1998}; var x, y; x = mycar.make; // x gets the value "honda" myfunc(mycar); y = mycar.make; // y gets the value "toyota" // (the make property was changed by the function) function expressions while the function declaration above is syntactically a statement, functions can also be created by a function expression.
... function map(f, a) { let result = []; // create a new array let i; // declare variable for (i = 0; i != a.length; i++) result[i] = f(a[i]); return result; } in the following code, the function receives a function defined by a function expression and executes it for every element of the array received as a second argument.
... function map(f, a) { let result = []; // create a new array let i; // declare variable for (i = 0; i != a.length; i++) result[i] = f(a[i]); return result; } const f = function(x) { return x * x * x; } let numbers = [0, 1, 2, 5, 10]; let cube = map(f,numbers); console.log(cube); function returns: [0, 1, 8, 125, 1000].
...And 10 more matches
Inheritance and the prototype chain - JavaScript
it should not be confused with the func.prototype property of functions, which instead specifies the [[prototype]] to be assigned to all instances of objects created by the given function when used as a constructor.
... here is what happens when trying to access a property: // let's create an object o from function f with its own properties a and b: let f = function () { this.a = 1; this.b = 2; } let o = new f(); // {a: 1, b: 2} // add properties in f function's prototype f.prototype.b = 3; f.prototype.c = 4; // do not set the prototype f.prototype = {b:3,c:4}; this will break the prototype chain // o.[[prototype]] has properties b and c.
... code link setting a property to an object creates an own property.
...And 10 more matches
Introduction to using XPath in JavaScript - XPath
the function can be either: created by using the creatensresolver method of a xpathevaluator object.
...specifying null will create a new xpathresult object.
... implementing a default namespace resolver we create a namespace resolver using the creatensresolver method of the document object.
...And 10 more matches
Creating a Firefox sidebar extension - Archive of obsolete content
a newer document is available: creating a firefox sidebar this article describes how to create a registered sidebar for firefox 2 or greater.
...what we will do is create a sidebar and register it so it will be available in the menu.
...first a simple xul page is created.
...And 9 more matches
Drag and Drop Example - Archive of obsolete content
dragging elements around here, we'll create a simple board where items from a palette can be dragged onto the board.
... the user can click on one of several xul elements on the palette and drag it onto a stack element to create an element of a particular type.
...the board will be created using a stack element.
...And 9 more matches
Space Manager Detailed Design - Archive of obsolete content
this frame * created the space manager, and the world coordinate space is * relative to this frame.
...this * creates a new local coordinate space relative to the current * coordinate space.
...((prcliststr*)this);} bandrect* head() const {return (bandrect*)pr_list_head(this);} bandrect* tail() const {return (bandrect*)pr_list_tail(this);} // operations void append(bandrect* abandrect) {pr_append_link(abandrect, this);} // remove and delete all the band rects in the list void clear(); }; frameinfo* getframeinfofor(nsiframe* aframe); frameinfo* createframeinfo(nsiframe* aframe, const nsrect& arect); void destroyframeinfo(frameinfo*); void clearframeinfo(); void clearbandrects(); bandrect* getnextband(const bandrect* abandrect) const; void divideband(bandrect* aband, nscoord abottom); prbool canjoinbands(bandrect* aband, bandrect* aprevband); prbool joinbands(bandrect* aband, bandrect* aprevband)...
...And 9 more matches
Writing to Files - Archive of obsolete content
to create an output stream, use nsiscriptableio.newoutputstream().
... this method has a number of options to specify text or binary writing, the character set, and whether to append to an existing file or create a new one.
... to create an input stream, first get a reference to a nsifile, and then use nsiscriptableio.newoutputstream() to open a stream for writing to it.
...And 9 more matches
Beginner's guide to media queries - Learn web development
media queries are a key part of responsive web design, as they allow you to create different layouts depending on the size of the viewport, but they can also be used to detect other things about the environment your site is running on, for example whether the user is using a touchscreen rather than a mouse.
... prerequisites: html basics (study introduction to html), and an idea of how css works (study css first steps and css building blocks.) objective: to understand how to use media queries, and the most common approach for using them to create responsive designs.
... width and height the feature we tend to detect most often in order to create responsive designs (and that has widespread browser support) is viewport width, and we can apply css if the viewport is above or below a certain width — or an exact width — using the min-width, max-width, and width media features.
...And 9 more matches
Responsive design - Learn web development
historic website layouts at one point in history you had two options when designing a website: you could create a liquid site, which would stretch to fill the browser window or a fixed width site, which would be a fixed size in pixels.
... as the mobile web started to become a reality with the first feature phones, companies who wished to embrace mobile would generally create a special mobile version of their site, with a different url (often something like m.example.com, or example.mobi).
... zoe mickley gillenwater was instrumental in her work to describe and formalize the different ways in which flexible sites could be created, attempting to find a happy medium between filling the screen or being completely fixed in size.
...And 9 more matches
Manipulating documents - Learn web development
you can use this object to return and manipulate information on the html and css that comprises the document, for example get a reference to an element in the dom, change its text content, apply new styles to it, create new elements and add them to the current element as children, or even delete it altogether.
...this is a "tree structure" representation created by the browser that enables the html structure to be easily accessed by programming languages — for example the browser itself uses it to apply styling and other information to the correct elements as it renders a page, and developers like you can manipulate the dom with javascript after the page has been rendered.
... we have created a simple example page at dom-example.html (see it live also).
...And 9 more matches
Introduction to automated testing - Learn web development
for example, let's first create a test directory to allow us to play without fear of breaking anything.
... create a new directory somewhere sensible using your file manager ui, or, on a command line, by navigating to the location you want and running the following command: mkdir node-test to make this directory an npm project, you just need to go inside your test directory and initialize it, with the following: cd node-test npm init this second command will ask you many questions to find out the information required to set up the project; you can just select the defaults for now.
... to begin with, create a test npm project using the procedure detailed at the bottom of the previous section.
...And 9 more matches
Creating Sandboxed HTTP Connections
introduction starting with gecko 1.8.1 (firefox 2), it is possible to create sandboxed http connections which don't affect the user's cookies.
... setting up an http connection the first step in setting up an http connection from an url (stored in a string) is to create an nsiuri out of it.
...to create an nsiuri from an string, we use the newuri method of nsiioservice: // the io service var ioservice = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); // create an nsiuri var uri = ioservice.newuri(myurlstring, null, null); once the nsiuri has been created, a nsichannel can be generated from it using nsiioservice's newchannelfromuri method: // get a channel for that nsiuri var channel = ioservice.newchannelfromuri(uri); to initiate the connection, the asyncopen method is called.
...And 9 more matches
Necko walkthrough
nsdocshell as an example client of the nsihttpchannel api nsdocshell::loaduri(string) create nsiuri from string nsdocshell::loaduri(nsiuri) creates 2 nsiinputstream for read response from; passes them with uri to ...
... nsdocshell::internalload nsdocshell::douriload opens the nsichannel for the uri (ns_newchannel) if "http:", it will be an nsihttpchannel nsdocshell::dochannelload nsuriloader::openuri passes an nsistreamlistener pointer, 'loader' to nsuriloader::openchannel - it creates an nsdocumentopeninfo object, which implements nsistreamlistener, i.e.
...but the interface for clients of necko is important to consider: send request uri helps creates channel setup channel (headers, request data, response callback...) channel->asyncopen.
...And 9 more matches
An Overview of XPCOM
but xpcom also provides several tools and libraries that enable the loading and manipulation of these components, services that help the developer write modular cross-platform code, and versioning support, so that components can be replaced or upgraded without breaking or having to recreate the application.
... using xpcom, developers create components that can be reused in different applications or that can be replaced to change the functionality of existing applications.
...in the haste of early mozilla development, components were created where they were inappropriate, but there's been an ongoing effort to remove xpcom from places like this.
...And 9 more matches
Finishing the Component
« previousnext » at this point you have created most of the infrastructure of the component.
... copying interfaces into your build environment to get and implement interfaces that are not part of gecko in your component, simply create a new directory in the gecko sdk named unfrozen.
...(for weblock, all you need are the headers for nsicontentpolicy and the nsicontentpolicy.idl.) then, using the same steps you used to create the weblock.h, create a header from this idl file using the xpidl compiler.
...And 9 more matches
nsIHTMLEditor
adddefaultproperty(in nsiatom aproperty, in astring aattribute, in astring avalue); void addinsertionlistener(in nsicontentfilter infilter); void align(in astring aalign); boolean breakisvisible(in nsidomnode anode); boolean candrag(in nsidomevent aevent); void checkselectionstateforanonymousbuttons(in nsiselection aselection); nsidomelement createanonymouselement(in astring atag, in nsidomnode aparentnode, in astring aanonclass, in boolean aiscreatedhidden); nsidomelement createelementwithdefaults(in astring atagname); void decreasefontsize(); void dodrag(in nsidomevent aevent); void getalignment(out boolean amixed, out short aalign); astring getbackgroundcolorstate(out boolean amixed); ...
... returninparagraphcreatesnewparagraph boolean a boolean indicating if a return key pressed in a paragraph creates another paragraph or just inserts a <br> at the caret.
... boolean candrag( in nsidomevent aevent ); parameters aevent return value checkselectionstateforanonymousbuttons() checks if the anonymous nodes created by the html editor have to be refreshed or hidden depending on a possible new state of the selection.
...And 9 more matches
nsIWindowsRegKey
method overview void close(); void create(in unsigned long rootkey, in astring relpath, in unsigned long mode); nsiwindowsregkey createchild(in astring relpath, in unsigned long mode); astring getchildname(in unsigned long index); astring getvaluename(in unsigned long index); unsigned long getvaluetype(in astring name); boolean haschanged(); boolean haschild(in astring name); ...
... constant value description root_key_classes_root 0x80000000 root_key_current_user 0x80000001 root_key_local_machine 0x80000002 access constants values for the mode parameter passed to the open() and create() methods.
... constant value description access_basic 0x00020000 access_query_value 0x00000001 access_set_value 0x00000002 access_create_sub_key 0x00000004 access_enumerate_sub_keys 0x00000008 access_notify 0x00000010 access_read access_basic | access_query_value | access_enumerate_sub_keys | access_notify access_write access_basic | access_set_value | access_create_sub_key access_all access_read | access_write wow64_32 0x00000200 ...
...And 9 more matches
Working with data
these are javascript constructors; as such, they're callable functions that you can use to create new cdata objects of that type.
... if type is an array type of unspecified length, the following steps are taken: if the value is a size value, a new array of that length is created, with its cells ready to accept values of the same type as those in the specified array.
... if the type represents a javascript string (that is, an array of jschar characters followed by a null terminator), a copy of that string is created and returned.
...And 9 more matches
Plug-in Basics - Plugins
with the plug-in api, you can create dynamically loaded plug-ins that can: register one or more mime types draw into a part of a browser window receive keyboard and mouse events obtain data from the network using urls post data to urls add hyperlinks or hotspots that link to new urls draw into sections on an html page communicate with javascript/dom from native code you can see which plug-ins are installed on your system...
... when the user opens a page that contains embedded data of a media type that invokes a plug-in, the browser responds with the following sequence of actions: check for a plug-in with a matching mime type load the plug-in code into memory initialize the plug-in create a new instance of the plug-in gecko can load multiple instances of the same plug-in on a single page, or in several open windows at the same time.
... if you are browsing a page that has several embedded realaudio clips, for example, the browser will create as many instances of the realplayer plug-in as are needed (though of course playing several realaudio files at the same time would seldom be a good idea).
...And 9 more matches
FileSystemDirectoryEntry.getDirectory() - Web APIs
options optional an object based on the filesystemflags dictionary, which allows you to specify whether or not to create the entry if it's missing and if it's an error if the file already exists.
... successcallback optional a method to be called once the filesystemdirectoryentry has been created.
...the fileerror.code specifies what type of error occurred, as follows: fileerror.not_found_err the create option was not specified (or was specified as false), and the directory doesn't exist.
...And 9 more matches
FileSystemDirectoryEntry.getFile() - Web APIs
options optional an object based on the filesystemflags dictionary, which allows you to specify whether or not to create the entry if it's missing and if it's an error if the file already exists.
... successcallback optional a method to be called once the filesystemfileentry has been created.
...the {domxref("fileerror.code")}} specifies what type of error occurred, as follows: fileerror.not_found_err the create option was not specified (or was specified as false), and the file doesn't exist.
...And 9 more matches
Using bounded reference spaces - Web APIs
it's difficult (and would probably be fairly confusing) to create a virtual world that's larger than the physical space available to the user if you're mapping their real-world movement into the virtual environment.
...in this section, we'll look at how to safely create a session that will work whether bounded spaces are supported or not.
... safely creating a bounded-preferred space before actually attempting to create a bounded reference space, you need to create a session that supports them.
...And 9 more matches
Starting up and shutting down a WebXR session - Web APIs
before you can begin to render your augmented or virtual reality scenario, you need to create and set up the webxr session, and you should know how to shut it down properly as well.
... webxr api emulator extension the mozilla webxr team has created a webxr api emulator browser extension, compatible with both firefox and chrome, which emulates the webxr api, simulating a variety of compatible devices such as the htc vive, the oculus go and oculus quest, samsung gear, and google cardboard.
... confirming the session type you need is available before trying to create a new webxr session, it's often wise to first check to see if the user's hardware and software support the presentation mode you wish to use.
...And 9 more matches
Using the Web Audio API - Web APIs
because of this modular design, you can create complex audio functions with dynamic effects.
... audio context to be able to do anything with the web audio api, we need to create an instance of the audio context.
...a baseaudiocontext is created for us automatically and extended to an online audio context.
...And 9 more matches
Web Audio API - Web APIs
the web audio api provides a powerful and versatile system for controlling audio on the web, allowing developers to choose audio sources, add effects to audio, create audio visualizations, apply spatial effects (such as panning) and much more.
...this modular design provides the flexibility to create complex audio functions with dynamic effects.
... a simple, typical workflow for web audio would look something like this: create audio context inside the context, create sources — such as <audio>, oscillator, stream create effects nodes, such as reverb, biquad filter, panner, compressor choose final destination of audio, for example your system speakers connect the sources up to the effects, and the effects to the destination.
...And 9 more matches
Error - JavaScript
description runtime errors result in new error objects being created and thrown.
... evalerror creates an instance representing an error that occurs regarding the global function eval().
... internalerror creates an instance representing an error that occurs when an internal error in the javascript engine is thrown.
...And 9 more matches
Object.prototype.constructor - JavaScript
the constructor property returns a reference to the object constructor function that created the instance object.
... description all objects (with the exception of objects created with object.create(null)) will have a constructor property.
... objects created without the explicit use of a constructor function (such as object- and array-literals) will have a constructor property that points to the fundamental object constructor type for that object.
...And 9 more matches
Object - JavaScript
objects can be created using the object() constructor or the object initializer / literal syntax.
...however, an object may be deliberately created for which this is not true (e.g.
... by object.create(null)), or it may be altered so that this is no longer true (e.g.
...And 9 more matches
widget - Archive of obsolete content
create a simple user interface for an add-on in firefox's add-on bar.
...in the add-on's "main.js" file, we create the widget, assign it the html file and the content script, and listen for events from the content script: const widgets = require("sdk/widget"); const data = require("sdk/self").data; var player = widgets.widget({ id: "player", width: 72, label: "player", contenturl: data.url("buttons.html"), contentscriptfile: data.url("button-script.js") }); player.port.on("play", function() { c...
... examples for conciseness, these examples create their content scripts as strings and use the contentscript property.
...And 8 more matches
Custom XUL Elements with XBL - Archive of obsolete content
this somewhat cryptic explanation describes a very simple concept: with xbl you can create your own custom elements.
... xbl basics in order to create an xbl binding you'll need 2 files: the xbl file and a css file that binds an element name to your xbl declaration.
...it holds all the code necessary to control the new element we created.
...And 8 more matches
Appendix E: DOM Building and Insertion (HTML & XUL) - Archive of obsolete content
the following methods will all safely create a dom tree without risk of remote execution.
... if (array.isarray(elemnameorarray)) { var frag = doc.createdocumentfragment(); array.foreach(arguments, function(thiselem) { frag.appendchild(tag.apply(null, thiselem)); }); return frag; } // single element?
... parse element namespace prefix (if none exists, default to defaultnamespace), and create element var elemns = namespace(elemnameorarray); var elem = doc.createelementns(elemns.namespace || jsontodom.defaultnamespace, elemns.shortname); // set element's attributes and/or callback functions (eg.
...And 8 more matches
A XUL Bestiary - Archive of obsolete content
this special option allows you to create and access chromes independent of the mozilla browser and begins to suggest some possibilities for xul-as-platform beyond the simple restyling of the browser.
...when you create different chrome for a package, you can create a subdirectory underneath content whose contents are loaded instead of default.
... for example, if you want to create a different skin for the navigator package, you can create a subdirectory underneath navigator/skin/ whose contents will be loaded instead of default's.
...And 8 more matches
Menus - Archive of obsolete content
menu types a menu is created using the menupopup tag.
...these tags can be used to create menus which sit on a menubar or are attached to buttons.
... submenus may be created by nesting one menu inside of another.
...And 8 more matches
Skinning XUL Files by Hand - Archive of obsolete content
in xul, skins are created with cascading style sheets and images.
...following the instructions here, you are going to create a skin for a xul file and apply it by specifying classes for all of the interested elements.
...the ability to apply styles to elements of a type, to specifically identified elements, and to classes of elements creates the potential for redundancies or conflicts in the style information.
...And 8 more matches
Building a Theme - Archive of obsolete content
an example of the content within a typical xpi file for a theme: example.xpi: /install.rdf /chrome.manifest /preview.png /icon.png /chrome/ browser/ communicator/ global/ mozapps/ we'll want to create a file structure similar to the one above for our tutorial, so let's begin by creating a folder for your theme somewhere on your hard disk (e.g.
...inside your new theme folder, create two new empty text files, one called chrome.manifest and the other called install.rdf.
...first, you'll want to create a directory somewhere.
...And 8 more matches
Building up a basic demo with Babylon.js - Game development
we will try to create a simple demo first — a cube rendered on the screen.
... initialising the babylon.js engine we have to create a babylon.js engine instance first (passing it the <canvas> element to render on) before we start developing our game.
...let's create a scene by adding the following lines just below our previous code: var scene = new babylon.scene(engine); scene.clearcolor = new babylon.color3(0.8, 0.8, 0.8); thus, the scene is created and the second line sets the background color to light gray.
...And 8 more matches
Building up a basic demo with PlayCanvas editor - Game development
here's what the page looks like — you can create projects and manage them, change their settings etc.
... click create to have it created.
...by clicking the editor button we'll launch the online playcanvas editor where we'll create our scene with the shapes.
...And 8 more matches
Cooperative asynchronous JavaScript: Timeouts and intervals - Learn web development
universe'); clearing timeouts finally, if a timeout has been created, you can cancel it before the specified time has elapsed by calling cleartimeout(), passing it the identifier of the settimeout() call as a parameter.
...the following function creates a new date() object, extracts a time string out of it using tolocaletimestring(), and then displays it in the ui.
... it then runs the function once per second using setinterval(), creating the effect of a digital clock that updates once per second (see this live, and also see the source): function displaytime() { let date = new date(); let time = date.tolocaletimestring(); document.getelementbyid('demo').textcontent = time; } const createclock = setinterval(displaytime, 1000); just like settimeout(), setinterval() returns an identifying value you can use later when you need to clear the interval.
...And 8 more matches
Working with JSON - Learn web development
objective: to understand how to work with data stored in json, and create your own json objects.
...add the following at the bottom of your javascript code: let requesturl = 'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json'; to create a request, we need to create a new request object instance from the xmlhttprequest constructor, using the new keyword.
...we are then passing that object to two function calls — the first one fills the <header> with the correct data, while the second one creates an information card for each hero on the team, and inserts it into the <section>.
...And 8 more matches
Object prototypes - Learn web development
in this example, we have defined a constructor function, like so: function person(first, last, age, gender, interests) { // property and method definitions this.name = { 'first': first, 'last' : last }; this.age = age; this.gender = gender; //...see link in summary above for full definition } we have then created an object instance like this: let person1 = new person('bob', 'smith', 32, 'male', ['music', 'skiing']); if you type "person1." into your javascript console, you should see the browser try to auto-complete this with the member names available on this object: in this list, you will see the members defined on person1's constructor — person() — name, age, gender, interests, bio, and greeti...
... so object.prototype.tostring(), object.prototype.valueof(), etc., are available to any object types that inherit from object.prototype, including new object instances created from the person() constructor.
...these all have a number of members defined on their prototype, which is why for example when you create a string, like this: let mystring = 'this is my string.'; mystring immediately has a number of useful methods available on it, like split(), indexof(), replace(), etc.
...And 8 more matches
Introduction to client-side frameworks - Learn web development
that could look something like this: function buildtodoitemel(id, name) { const item = document.createelement('li'); const span = document.createelement('span'); const textcontent = document.createtextnode(name); span.appendchild(textcontent) item.id = id; item.appendchild(span); item.appendchild(builddeletebuttonel(id)); return item; } here, we use the document.createelement() method to make our <li>, and several more lines of code to create the properties and children it needs.
...it follows a similar pattern to the one we used to build a list item element: function builddeletebuttonel(id) { const button = document.createelement('button'); const textcontent = document.createtextnode('delete'); button.setattribute('type', 'button'); button.appendchild(textcontent); return button; } this button doesn't do anything yet, but it will later once we decide to implement our delete feature.
... the code that will render our items on the page might read something like this: function rendertodolist() { const frag = document.createdocumentfragment(); state.tasks.foreach(task => { const item = buildtodoitemel(task.id, task.name); frag.appendchild(item); }); while (todolistel.firstchild) { todolistel.removechild(todolistel.firstchild); } todolistel.appendchild(frag); } we've now got well over thirty lines of code dedicated just to the ui – just to the step of rendering something in the dom – and at no point do we add classes that we could use later to style our list-items!
...And 8 more matches
Eclipse CDT
then, to create the eclipse project and open it, run: ./mach ide eclipse or to create the eclipse project without opening it yet, run: ./mach build-backend -b cppeclipse building the eclipse project should only take a few seconds.
...be aware that when eclipse gives results for any of the actions that follow, it will not include results for sections of the code that are ifdef'ed out by the configuration used to create your object directory.
...it also used to be necessary to add the following two lines to your mozconfig to make the compiler output errors all on a single line, but that may not be needed anymore: export cflags="-fmessage-length=0" export cppflags="-fmessage-length=0" debugging to create a debug configuration, open the project properties window, and select "run/debug settings" on the left.
...And 8 more matches
Creating localizable web applications
so in order to display a localized label of a category or a tab, you should create a mapping between the non-localizable english names used in the urls and the localizable english strings used in the interface.
...good: <h3> <?printf( /* l10n: %s is the author's username */ _("created by <a href=\"%s\">%s</a>"), $locale_conf->url('/gallery/designer/' .
..."</a> : how to create personas"), $locale_conf->url('/'));?> snippet 2.
...And 8 more matches
AsyncTestUtils extended framework
if you need to wrap an existing url listener or need a callback or fancy promise, create an instance of asyncurllistener.
... synthetic message sets the code that creates synthetic message sets returns instances of the syntheticmessageset class.
... create a single folder with messages in it let [folder, set1, set2, ...] = make_folder_with_sets([asynsetdef1, asynsetdef2, ...]); yield wait_for_message_injection(); this creates a folder with an automatically generated name and adds one or more sets of messages to it.
...And 8 more matches
Places Developer Guide
fuel - a collection of wrapper apis for easing access to a number of firefox utilities and services nsiplacestransactionsservice - a firefox service for modifying bookmarks in a transactional manner, providing facilities for undo/redo places utilities for javascript - accessors and helper functions for firefox and extensions creating bookmarks, folders and other items creating a bookmark // create an nsiuri for the url to be bookmarked.
... creating a folder var folderid = bookmarks.createfolder( bookmarks.toolbarfolder, // the id of the folder the new folder will be placed in.
... creating a livemark var ioservice = cc["@mozilla.org/network/io-service;1"] .getservice(ci.nsiioservice); var siteuri = ioservice.newuri("http://www.mozilla.com", null, null); var feeduri = ioservice.newuri("http://www.mozilla.org/news.rdf", null, null); var livemarks = cc["@mozilla.org/browser/livemark-service;2"] .getservice(ci.nsilivemarkservice); livemarks.createlivemark(bookmarks.toolbarfolder, // the id of the folder the livemark will be placed in "my livemark title", // the title of the livemark siteuri, // the uri of the site.
...And 8 more matches
Using the Places livemark service
the livemark service, offered by the nsilivemarkservice interface, is used to create, edit, and reload livemarks.
... initiating the livemark service before using the livemark service, you need to obtain an instance: var livemarkservice = components.classes["@mozilla.org/browser/livemark-service;2"] .getservice(components.interfaces.nsilivemarkservice); creating a new livemark the nsilivemarkservice.createlivemark() method creates a new livemark.
... var newlvmkid = livemarkservice.createlivemark(parentfolderid, "livemark name", uri("http://example.com/"), uri("http://example.com/rss.xml"), -1); the first parameter is the id of the folder in which to create the livemark.
...And 8 more matches
Avoiding leaks in JavaScript XPCOM components
this tends to be solved in one of two ways: either break the cycle at some point or ensure that the cycle is never created in the first place by making one of the pointers not own a reference (which carries the potential for crashes just like malloc and free).
...however, in a fully garbage-collected system the programmer can still create leaks by leaving objects reachable that are no longer needed.
...if you implement nsiobserver in javascript and register that observer (without using weak references) with a service (for example, with the observer service bug 239833 or with the pref service bug 256822), the service will do exactly what you tell it to do: notify the observer you just created until you unregister the observer.
...And 8 more matches
Mozilla internal string guide
there are also a number of concrete classes that are created as a side-effect of helper routines, etc.
...let the string library create the class for you.
... nssubstringtuple - created via string concatenation nsdependentsubstring - created through substring nspromiseflatstring - created through promiseflatstring() nsliteral[c]string - created through the ""_ns and u""_ns user-defined literals of course, there are times when it is necessary to reference these string classes in your code, but as a general rule they should be avoided.
...And 8 more matches
mozIStorageFunction
objects implementing this interface can be registered with mozistorageconnection.createfunction().
...this is called by the database engine when the function registered with mozistorageconnection.createfunction() is used in an executing sql statement or trigger.
... javascript starting in gecko 1.9.1.4 (firefox 3.0.15), you can directly pass your function into the mozistorageconnection method mozistorageconnection, like this: dbconn.createfunction("square", 1, function(aarguments) { let value = aarguments.getint32(0); return value * value; }); // run some query that uses the function.
...And 8 more matches
nsIMsgDatabase
last changed in gecko 1.9 (firefox 3) inherits from: nsidbchangeannouncer method overview void open(in nsilocalfile afoldername, in boolean acreate, in boolean aleaveinvaliddb); void forcefolderdbclosed(in nsimsgfolder afolder); void close(in boolean aforcecommit); void commit(in nsmsgdbcommit committype); void forceclosed(); void clearcachedhdrs; void resethdrcachesize(in unsigned long size); nsimsgdbhdr getmsghdrforkey(in nsmsgkey key); nsimsgdbhdr getmsghdrformessageid(in string messageid); boolean containskey(in nsmsgkey key); nsimsgdbhdr createnewhdr(in nsmsgkey key)...
...smsgkey key, in boolean deleted, in nsidbchangelistener instigator); void applyretentionsettings(in nsimsgretentionsettings amsgretentionsettings, in boolean adeleteviafolder); boolean hasnew(); void clearnewlist(in boolean notify); void addtonewlist(in nsmsgkey key); void startbatch(); void endbatch(); nsimsgofflineimapoperation getofflineopforkey(in nsmsgkey messagekey, in boolean create); void removeofflineop(in nsimsgofflineimapoperation op); nsisimpleenumerator enumerateofflineops(); void listallofflineopids(in nsmsgkeyarrayptr offlineopids); native code only!
... void setattributesonpendinghdr(in nsimsgdbhdr pendinghdr, in string property, in string propertyval, in long flags); void createcollationkey(in astring sourcestring, out octetptr key, out unsigned long len); native code only!
...And 8 more matches
Initialization and Destruction - Plugins
instance creation: the browser calls the plug-in api function npp_new when the instance is created.
... initialization the browser calls np_initialize when a plug-in is loaded and before the first instance is created.
... during initialization, when the browser encounters data of a mime type registered for a plug-in (either embedded in an html page or in a separate file), it loads the plug-in code into memory (if it hasn't been loaded already) and creates a new instance of the plug-in.
...And 8 more matches
Background Tasks API - Web APIs
window.requestidlecallback = window.requestidlecallback || function(handler) { let starttime = date.now(); return settimeout(function() { handler({ didtimeout: false, timeremaining: function() { return math.max(0, 50.0 - (date.now() - starttime)); } }); }, 1); } if window.requestidlecallback is undefined, we create it here.
... the implementation of our shim for cancelidlecallback() is much simpler: window.cancelidlecallback = window.cancelidlecallback || function(id) { cleartimeout(id); } if cancelidlecallback() isn't defined, this creates one which simply passes the specified callback id through to cleartimeout().
...these elements are: totaltaskcountelem is the <span> we use to insert the total number of tasks created into the status display in the progress box.
...And 8 more matches
Using the CSS Painting API - Web APIs
to programmatically create an image used by a css stylesheet we need to work through a few steps: define a paint worklet using the registerpaint() function register the worklet include the paint() css function to elaborate over these steps, we're going to start by creating a half-highlight background, like on this header: css paint worklet in an external script file, we employ the registerpaint() function to name our css paint worklet.
... we define the fillstyle as being hsla(55, 90%, 60%, 1.0), which is a shade of yellow, and then call fillrect() to create a rectangle of that color.
... we can use the css background-size and background-position properties to re-size or relocate this background image, but this is the default size and placement of the yellow box we created in our paint worklet.
...And 8 more matches
Drawing shapes with canvas - Web APIs
all other shapes must be created by combining one or more paths.
...the clearrect() function then erases a 60x60 pixel square from the center, and then strokerect() is called to create a rectangular outline 50x50 pixels within the cleared square.
...to make shapes using paths, we take some extra steps: first, you create the path.
...And 8 more matches
Introduction to the DOM - Web APIs
we'll look at how the dom represents an html or xml document in memory and how you use apis to create web content and applications.
... when you create a script–whether it's inline in a <script> element or included in the web page by means of a script loading instruction–you can immediately begin using the api for the document or window elements to manipulate the document itself or to get at the children of that document, which are the various elements in the web page.
... your dom programming may be something as simple as the following, which displays an alert message by using the alert() function from the window object, or it may use more sophisticated dom methods to actually create new content, as in the longer example below.
...And 8 more matches
WebGL model view projection - Web APIs
the code below will create 2 triangles that will draw a square on the screen.
... webglbox example this example will create a custom webglbox object that will draw a 2d box on the screen.
... webglbox constructor the constructor looks like this: function webglbox() { // setup the canvas and webgl context this.canvas = document.getelementbyid('canvas'); this.canvas.width = window.innerwidth; this.canvas.height = window.innerheight; this.gl = mdn.createcontext(canvas); var gl = this.gl; // setup a webgl program, anything part of the mdn object is defined outside of this article this.webglprogram = mdn.createwebglprogramfromids(gl, 'vertex-shader', 'fragment-shader'); gl.useprogram(this.webglprogram); // save the attribute and uniform locations this.positionlocation = gl.getattriblocation(this.webglprogram, 'position'); this.colo...
...And 8 more matches
WebRTC connectivity - Web APIs
this article describes how the various webrtc-related protocols interact with one another in order to create a connection and transfer data and/or media among peers.
... signaling unfortunately, webrtc can’t create connections without some sort of server in the middle.
... peer a who will be the initiator of the connection, will create an offer.
...And 8 more matches
Grid template areas - CSS: Cascading Style Sheets
for example, if i wish to create the layout shown below i can identify four main areas.
...this will not yet create any layout, but we now have named areas to use in a layout.
... .header { grid-area: hd; } .footer { grid-area: ft; } .content { grid-area: main; } .sidebar { grid-area: sd; } having defined these names i then create my layout.
...And 8 more matches
Realizing common layouts using CSS Grid Layout - CSS: Cascading Style Sheets
i am going to create this layout using the named template areas that we learned about in the guide grid template areas.
...we go to a two column layout, and then to a three column layout by redefining the grid, and the placement of items on the grid.</p> </article> <aside class="side">sidebar</aside> <div class="ad">advertising</div> <footer class="main-footer">the footer</footer> </div> as we are using grid-template-areas to create the layout.
... .main-head { grid-area: header; } .content { grid-area: content; } .main-nav { grid-area: nav; } .side { grid-area: sidebar; } .ad { grid-area: ad; } .main-footer { grid-area: footer; } this will not create any layout, however our items now have names we can use to do so.
...And 8 more matches
Adapting to the new two-value syntax of display - CSS: Cascading Style Sheets
as an example, when we use display: flex we create a block-level container, with flex children.
... we can create inline flex containers.
... if you create a flex container using the single value of inline-flex you will have an inline-level box with flex children.
...And 8 more matches
position - CSS: Cascading Style Sheets
WebCSSposition
this value creates a new stacking context when the value of z-index is not auto.
... absolute the element is removed from the normal document flow, and no space is created for the element in the page layout.
... this value creates a new stacking context when the value of z-index is not auto.
...And 8 more matches
Audio and Video Delivery - Developer guides
a <video> element, or document.createelement('video') perhaps?) deliver the media file to the player.
... html audio <audio controls preload="auto"> <source src="audiofile.mp3" type="audio/mpeg"> <!-- fallback for browsers that don't support mp3 --> <source src="audiofile.ogg" type="audio/ogg"> <!-- fallback for browsers that don't support audio tag --> <a href="audiofile.mp3">download audio</a> </audio> the code above will create an audio player that attempts to preload as much audio as possible for smooth playback.
...'t support mp4 --> <source src="videofile.webm" type="video/webm"> <!-- specifying subtitle files --> <track src="subtitles_en.vtt" kind="subtitles" srclang="en" label="english"> <track src="subtitles_no.vtt" kind="subtitles" srclang="no" label="norwegian"> <!-- fallback for browsers that don't support video tag --> <a href="videofile.mp4">download video</a> </video> the code above creates a video player of dimensions 640x480 pixels, displaying a poster image until the video is played.
...And 8 more matches
new operator - JavaScript
the new operator lets developers create an instance of a user-defined object type or of one of the built-in object types that has a constructor function.
... description the new keyword does the following things: creates a blank, plain javascript object; links (sets the constructor of) this object to another object; passes the newly created object from step 1 as the this context; returns this if the function doesn't return an object.
... create an instance of the object with new.
...And 8 more matches
Paths - SVG: Scalable Vector Graphics
WebSVGTutorialPaths
it can be used to create lines, curves, arcs, and more.
... paths create complex shapes by combining multiple straight lines or curved lines.
... complex shapes composed only of straight lines can be created as <polyline>s.
...And 8 more matches
Using custom elements - Web Components
one of the key features of the web components standard is the ability to create custom elements that encapsulate your functionality on an html page, rather than having to make do with a long, nested batch of elements that together provide a custom page feature.
...for example <popup-info>, or document.createelement("popup-info").
...to create one of these, you have to specify which element they extend (as implied in the examples above), and they are used by writing out the basic element but specifying the name of the custom element in the is attribute (or property).
...And 8 more matches
panel - Archive of obsolete content
creates transient dialogs to implement part of an add-on's user interface.
... a panel's content is loaded as soon as it is created, before the panel is shown, and the content remains loaded when a panel is hidden, so it is possible to keep a panel around in the background, updating its content as appropriate in preparation for the next time it is shown.
... opening a panel will close any panel created by the panel() constructor that is already open, even if that panel was opened by a different add-on sdk based extension.
...And 7 more matches
How to convert an overlay extension to restartless - Archive of obsolete content
mport("resource://gre/modules/addonmanager.jsm"); addonmanager.getaddonbyid(myaddonid,function(addon) { var file = services.io.newuri("resource://myaddon/filename.ext",null,null) .queryinterface(components.interfaces.nsifileurl) .file; var stream = components.classes["@mozilla.org/network/file-input-stream;1"] .createinstance(components.interfaces.nsifileinputstream) .queryinterface(components.interfaces.nsiseekablestream); stream.init(file, 0x01, 0444, 0); // read-only, read by owner/group/others, normal behavior /* do stuff */ }); this bit of code is paraphrased and probably not to be recommended as-is, but it should work.
... step 3a: option 1: use nsizipreader let zipreader = components.classes["@mozilla.org/libjar/zip-reader;1"] .createinstance(components.interfaces.nsizipreader); zipreader.open(addondata.installpath); ...
...xmlhttprequest is an api created by microsoft, adopted by mozilla and other vendors, and hacked into a swiss army knife of file loading.
...And 7 more matches
Creating a Help Content Pack - Archive of obsolete content
original doc: http://www.mozilla.org/projects/help.../content_packs i hesitate to call it "original", tho, because i've basically rewritten the entire thing so that it's easier and faster to use to create help content.
...you can create a content packs which inherit from existing mozilla help content packs.
... open up your favorite text editor and create the file content-pack.rdf.
...And 7 more matches
Menu - Archive of obsolete content
ArchiveMozillaJetpackUIMenu
features can also create new menus and attach them almost anywhere, chrome or content, as popup menus or context menus.
...because it is still under development, the api currently lives in the future and must be imported before it is used: jetpack.future.import("menu"); menus all menus in jetpack are jetpack.menu objects, including both built-in firefox menus and menus that features create.
... to create a new menu, use one of the jetpack.menu constructors below.
...And 7 more matches
jspage - Archive of obsolete content
flash=(function(){var a=($try(function(){return navigator.plugins["shockwave flash"].description; },function(){return new activexobject("shockwaveflash.shockwaveflash").getvariable("$version");})||"0 r0").match(/\d+/g);return{version:parseint(a[0]||0+"."+a[1],10)||0,build:parseint(a[2],10)||0}; })();function $exec(b){if(!b){return b;}if(window.execscript){window.execscript(b);}else{var a=document.createelement("script");a.setattribute("type","text/javascript"); a[(browser.engine.webkit&&browser.engine.version<420)?"innertext":"text"]=b;document.head.appendchild(a);document.head.removechild(a);}return b;}native.uid=1; var $uid=(browser.engine.trident)?function(a){return(a.uid||(a.uid=[native.uid++]))[0];}:function(a){return a.uid||(a.uid=native.uid++);};var window=new native({name:"window",legacy...
...:(browser.engine.trident)?null:window.window,initialize:function(a){$uid(a); if(!a.element){a.element=$empty;if(browser.engine.webkit){a.document.createelement("iframe");}a.element.prototype=(browser.engine.webkit)?window["[[domelement.prototype]]"]:{}; }a.document.window=a;return $extend(a,window.prototype);},afterimplement:function(b,a){window[b]=window.prototype[b]=a;}});window.prototype={$family:{name:"window"}}; new window(window);var document=new native({name:"document",legacy:(browser.engine.trident)?null:window.document,initialize:function(a){$uid(a);a.head=a.getelementsbytagname("head")[0]; a.html=a.getelementsbytagname("html")[0];if(browser.engine.trident&&browser.engine.version<=4){$try(function(){a.execcommand("backgroundimagecache",false,true); });}if(browser.engine.trident){a.windo...
...(function(c){if(c.length==1){c+=c;}return c.toint(16);});return(b)?a:"rgb("+a+")"; },rgbtohex:function(d){if(this.length<3){return null;}if(this.length==4&&this[3]==0&&!d){return"transparent";}var b=[];for(var a=0;a<3;a++){var c=(this[a]-0).tostring(16); b.push((c.length==1)?"0"+c:c);}return(d)?b:"#"+b.join("");}});function.implement({extend:function(a){for(var b in a){this[b]=a[b];}return this;},create:function(b){var a=this; b=b||{};return function(d){var c=b.arguments;c=(c!=undefined)?$splat(c):array.slice(arguments,(b.event)?1:0);if(b.event){c=[d||window.event].extend(c); }var e=function(){return a.apply(b.bind||null,c);};if(b.delay){return settimeout(e,b.delay);}if(b.periodical){return setinterval(e,b.periodical);}if(b.attempt){return $try(e); }return e();};},run:function(a,b){return this.a...
...And 7 more matches
The life of an HTML HTTP request - Archive of obsolete content
this factory is then told to create a nsicontentviewer.
... the factory creates a contentviewer.
... in most cases (including this) it also creates a nsidocument (nshtmldocument) and binds it to the contentviewer.
...And 7 more matches
Creating XPI Installer Modules - Archive of obsolete content
in the package you create in this tutorial, for example, all of the resources are located under the content/ subdirectory, but they could just as easily have been archived directly at the top--along with skin and locale resources, if you wanted.
...once you have created a package like the one described here, mozilla users can download and install it in a single step.
...developing the resources needless to say, one of the first things you will have to create is the actual software you wish to make redistributable.
...And 7 more matches
Install script template - Archive of obsolete content
nsfolder, null); if (errblock1!=0) { logcomment("could not add " + component_file + " to " + pluginsfolder + ":" + errblock1); cancelinstall(errblock1); } } else { logcomment("cancelling current browser install due to lack of space..."); cancellinstall(); } // secondary install block, which sets up plugins and xpt in another location in addition to the current browser errblock2 = createsecondaryinstall(); // performinstall block, in which error conditions from previous blocks are checked.
... * * @param empty param list **/ function createsecondaryinstall() { // use getfolder in such a way that it creates c:\winnt\system32\myplugin secondaryfolder = getfolder("win system", company_name); // if secondaryfolder is null, then there has been an error if(!secondaryfolder) return nosecondaryinstall; else { // we have admin privileges to write to the win system directory // so we will set up dll and xpt in their new home ...
...) { logcomment("moz registerplid: rootkey=="+hkey_current_user); winreg.setrootkey(winreg.hkey_current_user); } else { logcomment("moz registerplid: invalid rootkey, "+rootkey); return invalidrootkeyerror; } if (!winreg.iskeywritable(plidpath)) { logcomment("moz registerplid: registry key not writable"); return registrykeynotwritableerror; } // if we can't find the plidpath create the key if (!winreg.keyexists(plidpath)) { logcomment("moz registerplid: creating missing key "+plidpath+"."); myregstatus = winreg.createkey(plidpath, ""); if (myregstatus != 0) { logcomment("moz registerplid: could not create the key, "+plidpath+"as expected.
...And 7 more matches
Content Panels - Archive of obsolete content
you could create a wizard interface by opening a different window for each screen.
...note that xul does have a wizard element which may be used to create wizard interfaces.
...it creates a separate document within the window.
...And 7 more matches
Back to the Server: Server-Side JavaScript On The Rise - Archive of obsolete content
listing 1 - querying a mysql database from rhino // import the java sql packages importpackage( java.sql ); // load the mysql driver java.lang.class.forname( "com.mysql.jdbc.driver" ); // create connection to the database var conn = drivermanager.getconnection( "jdbc:mysql://localhost/rhino", "urhino", "prhino" ); // create a statement handle var stmt = conn.createstatement(); // get a resultset var rs = stmt.executequery( "select * from employee" ); // get the metadata from the resultset var meta = rs.getmetadata(); // loop over the records, dump out column names and values while( r...
...this creates a strict separation of the two environments.
...heet"/> <script src="/jaxer_examples/js/ext-2.1/adapter/ext/ext-base.js"/> <script src="/jaxer_examples/js/ext-2.1/ext-all.js"/> <link href="/jaxer_examples/css/main.css" type="text/css" rel="stylesheet"/> <script runat="both" src="/jaxer_examples/js/validatecomments.js"/> <script> var txt_name; var txt_email; var txt_message; var btn_comments; var form_comments; ext.onready( function() { // create the name text field txt_name = new ext.form.textfield({ name: "name", fieldlabel: "name", width: 200 }); // create the e-mail text field txt_email = new ext.form.textfield({ name: "email", fieldlabel: "e-mail", width: 200 }); // create the message text field txt_message = new ext.form.textarea({ name: "message", fieldlabel: "message", width: 200 }); // create a butto...
...And 7 more matches
Index - Game development
streamlining cross device differences creates multiple challenges, not least when providing appropriate controls for different contexts.
... 42 2d breakout game using phaser 2d, beginner, canvas, games, javascript, phaser, tutorial in this step-by-step tutorial, we create a simple mobile mdn breakout game written in javascript, using the phaser framework.
...let's explore how to create a group of bricks and print them on screen using a loop.
...And 7 more matches
Basic native form controls - Learn web development
all rich text editors you'll encounter are custom widgets created with html, css, and javascript.
... single line text fields a single line text field is created using an <input> element whose type attribute value is set to text, or by omitting the type attribute altogether (text is the default value).
...this is used to create a form control that is invisible to the user, but is still sent to the server along with the rest of the form data once submitted — for example you might want to submit a timestamp to the server stating when an order was placed.
...And 7 more matches
Introduction to web APIs - Learn web development
application programming interfaces (apis) are constructs made available in programming languages to allow developers to create complex functionality more easily.
... apis for drawing and manipulating graphics are now widely supported in browsers — the most popular ones are canvas and webgl, which allow you to programmatically update the pixel data contained in an html <canvas> element to create 2d and 3d scenes.
... for example, you might draw shapes such as rectangles or circles, import an image onto the canvas, and apply a filter to it such as sepia or grayscale using the canvas api, or create a complex 3d scene with lighting and textures using webgl.
...And 7 more matches
Third-party APIs - Learn web development
const audiosource = audioctx.createmediaelementsource(audioelement); // etc.
...in this case we specify the coordinates of the center of the map, a map layer of type map to show (created using the mapquest.tilelayer() method), and the default zoom level.
... next, you need to go to the mapquest developer site, create an account, and then create a developer key to use with your example.
...And 7 more matches
Arrays - Learn web development
here we look at why this is useful, then explore how to create an array, retrieve, add, and remove items stored in an array, and more besides.
...for example: let sequence = [1, 1, 2, 3, 5, 8, 13]; let random = ['tree', 795, [0, 1, 2]]; before proceeding, create a few example arrays.
...first, create a string in your console: let mydata = 'manchester,london,liverpool,birmingham,leeds,carlisle'; now let's split it at each comma: let myarray = mydata.split(','); myarray; finally, try finding the length of your new array, and retrieving some items from it: myarray.length; myarray[0]; // the first item in the array myarray[1]; // the second item in the array myarray[myarray.length-1];...
...And 7 more matches
Starting our Svelte Todo list app - Learn web development
in this article we will first have a look at the desired functionality of our app, then we'll create a todos.svelte component and put static markup and styles in place, leaving everything ready to start developing our to-do list app features, which we'll go on to in subsequent articles.
... objective: to learn how to create a svelte component, render it inside another component, pass data into it using props, and save its state.
... building our first component let's create a todos.svelte component — this will contain our list of todos.
...And 7 more matches
TypeScript support in Svelte - Learn web development
all you have to do is run the following terminal commands (run them somewhere where you are storing your svelte test projects — it creates a new directory): npx degit sveltejs/template svelte-typescript-app cd svelte-typescript-app node scripts/setuptypescript.js this creates a starter project that includes typescript support, which you can then modify as you wish.
... inside the src folder create a types folder.
... create a filter.enum.ts file in the types folder.
...And 7 more matches
Introducing a complete toolchain - Learn web development
you will need to create accounts with each of github and netlify if you wish to complete the tutorial.
... once you've signed up for github (click the sign up link on the homepage if you don't already have an account, and follow the instructions), you can use your github account for authentication on netlify (click sign up, then choose github from the "sign up with one of the following" list), so technically you only need to create one new account.
... using the command line, we can create the project, install the initial tooling, and create rudimentary configuration files.
...And 7 more matches
Theme concepts
these theme options can be implemented as static themes (although the theme images themselves may be animated) or as dynamic themes created in a browser extension.
... you can also use the theme generator on amo to create a static theme.
... defining a theme to create a theme (in this example a simple, single image theme): create a folder in a suitable location on your computer.
...And 7 more matches
Creating reftest-based unit tests
so, if the effect of complex markup is being tested, put that complex markup into a page and create another page that uses simple markup to achieve the same visual effect.
...create a directory (inside firefox's source code tree) and make that your current directory (i.e.
... step 3 create a file named foo.html with the following: <html><head><title>reftest0001</title> <body><strong>hello!</strong></body> </html> step 4 create a file named bar.html with the following: <html><head><title>reftest0001</title> <body><b>hello!</b></body> </html> step 5 create a file named reftest.list with the following: == foo.html bar.html you are now ready to run the test (but first you must go back to the root of firefox's source code tree): $ ./mach reftest path/to/reftest.list 2>&1 | grep reftest reftest pass: file:///users/ray/mozilla-central/path/to/foo.html $ congratulations!
...And 7 more matches
Debugging on Mac OS X
creating an xcode project if you try to create a new xcode project in an existing directory then xcode will delete its existing contents (xcode will warn you beforehand).
... these steps were last updated for xcode 10.3: open xcode, and create a new project with file > new project.
...create/select a temporary directory to contain the project and then click create.
...And 7 more matches
Displaying Places information using views
tree view create a built-in tree view by setting the type attribute to "places" on a tree element.
... in firefox 3.6 and earlier requires gecko 1.9.2(firefox 3.6 / thunderbird 3.1 / fennec 1.0) create a built-in menu view by setting the type attribute to "places" on an empty menupopup element (which would be a child of some parent menu element): <menu> <menupopup type="places" /> </menu> the place attribute or property should be set on the menupopup as well.
... toolbar view create a built-in toolbar view by setting the type attribute to "places" on an empty hbox element (which would be a child of some parent toolbaritem element, itself the child of a toolbar element): <toolbar> <toolbaritem> <hbox type="places" /> </toolbaritem> </toolbar> the place attribute or property should be set on the hbox as well.
...And 7 more matches
Error codes returned by Mozilla APIs
ns_error_file_unknown_type (0x80520004) an call was made to nsifile.create() with an invalid type.
... ns_error_file_already_exists (0x80520008) an attempt was made to create a file that already exists.
... ns_error_file_too_big (0x8052000f) this error occurs when nsifile.createunique() cannot create a file with a unique filename.
...And 7 more matches
Bootstrapping a new locale
(see also https://developer.mozilla.org/en/create_a_new_localization) the documentation here is no longer being maintained and is inaccurate.
... create a bare-bones localization next, create a base localization.
...you will need to create an account so you can access the service.
...And 7 more matches
NSS API Guidelines
the certdb library manipulates the certificate database (add, create, delete certificates and crls).
... it also provides general certificate-handling routines (create a certificate, verify, add/check certificate extensions).
...option 1, currently the most common used for enums, actually creates namespace pollution.
...And 7 more matches
Rhino scopes and contexts
it's important to understand that a scope is independent of the context that created it.
... you can create a scope using one context and then evaluate a script using that scope and another context (either by exiting the current context and entering another, or by executing on a different thread).
... a top-level scope is created by calling context.initstandardobjects to create all the standard objects: scriptableobject scope = cx.initstandardobjects(); the easiest way to embed rhino is just to create a new scope this way whenever you need one.
...And 7 more matches
Getting Started Guide
a rule of xpcom is that any function that creates or returns an interface pointer will have already addrefed it.
... you use an owning reference when you created the object; you got the object from a function that might have created it, e.g., any `getter' function, such as queryinterface, or createinstance.
... nscomptr<nsifoo> foo(dont_addref(createfoo())); // |createfoo| |addref|s its result, as all good getters do something nscomptr doesn't do an nscomptr does all that is necessary to behave as an owning reference.
...And 7 more matches
Index
13 autoconfig: how to create a configuration file autoconfiguration, thunderbird authoritative definition 14 autoconfiguration in thunderbird moved to autoconfiguration 15 buddy icons in mail seth spitzer mozilla is now able to show icons in the message header area and the addressbook card pane.
... instead of destroying the mail compose window on send (or close) just to create a new one the next time, mozilla mail will "cache" the compose window on send (or close), and use that instead.
... any new window performance problems that mozilla has are especially painful in mail compose, as we need to create a new compose window on every new mail message or reply.
...And 7 more matches
Recording a media element - Web APIs
utility functions next, we create some utility functions that will get used later.
... line 2 creates the mediarecorder that will handle recording the input stream.
... line 3 creates an empty array, data, which will be used to hold the blobs of media data provided to our ondataavailable event handler.
...And 7 more matches
Using the User Timing API - Web APIs
the user timing interface allows the developer to create application specific timestamps that are part of the browser's performance timeline.
... this document shows how to create mark and measure performance entry types and how to use user timing methods (which are extensions of the performance interface) to retrieve and remove entries from the browser's performance timeline.
... performance marks a performance mark is a named performance entry that is created by the application at some location in an application.
...And 7 more matches
Establishing a connection: The WebRTC perfect negotiation pattern - Web APIs
create the signaling and peer connections first, the signaling channel needs to be opened and the rtcpeerconnection needs to be created.
... let makingoffer = false; pc.onnegotiationneeded = async () => { try { makingoffer = true; await pc.setlocaldescription(); signaler.send({ description: pc.localdescription }); } catch(err) { console.error(err); } finally { makingoffer = false; } }; note that setlocaldescription() without arguments automatically creates and sets the appropriate description based on the current signalingstate.
... the set description is either an answer to the most recent offer from the remote peer or a freshly-created offer if there's no negotiation underway.
...And 7 more matches
A simple RTCDataChannel sample - Web APIs
set up the local peer localconnection = new rtcpeerconnection(); sendchannel = localconnection.createdatachannel("sendchannel"); sendchannel.onopen = handlesendchannelstatuschange; sendchannel.onclose = handlesendchannelstatuschange; the first step is to create the "local" end of the connection.
... the next step is to create the rtcdatachannel by calling rtcpeerconnection.createdatachannel() and set up event listeners to monitor the channel so that we know when it's opened and closed (that is, when the channel is connected or disconnected within that peer connection).
... set up the remote peer remoteconnection = new rtcpeerconnection(); remoteconnection.ondatachannel = receivechannelcallback; the remote end is set up similarly, except that we don't need to explicitly create an rtcdatachannel ourselves, since we're going to be connected through the channel established above.
...And 7 more matches
Using DTMF with WebRTC - Web APIs
offeroptions an rtcofferoptions object providing options to specify when calling rtcpeerconnection.createoffer().
... then a second rtcpeerconnection, this one representing the receiving end of the call, is created and stored in receiverpc; its onicecandidate event handler is set up too.
...falling " + "back to the <strong>deprecated</strong> addstream() method..."); callerpc.addstream(stream); } if (callerpc.getsenders) { dtmfsender = callerpc.getsenders()[0].dtmf; } else { log("your browser doesn't support rtcpeerconnection.getsenders(), so " + "falling back to use <strong>deprecated</strong> createdtmfsender() " + "instead."); dtmfsender = callerpc.createdtmfsender(audiotracks[0]); } dtmfsender.ontonechange = handletonechangeevent; } after setting audiotracks to be a list of the audio tracks on the stream from the user's microphone, it's time to add the media to the caller's rtcpeerconnection.
...And 7 more matches
Viewpoints and viewers: Simulating cameras in WebXR - Web APIs
simulating classic cinematography cinematography is the art of designing, planning, and executing camera movements to create the desired look and emotion for a scene in animation or film.
...a slow move can bring a sense of movement, ease, or focus to a scene, while a rapid zoom can create a sense of anxiety, surprise, or tension.
... there are two techniques in 3d graphics that can create similar though not identical results, and whose methods apply more easily in different situations.
...And 7 more matches
Geometry and reference spaces in WebXR - Web APIs
like an architect or a set designer, you have the power to create moods and experiences through a physical environment.
...the right balance can create a unique presence and guide your user.
... once created, an xrreferencespace guarantees a certain level of support for motion and orientation tracking, and provides a mechanism for obtaining an xrviewerpose from which you can get a matrix which represents the position and facing direction of the space relative to the world space, if the space represents a viewer such as the user's headset, an observer's headset, or a virtual camera.
...And 7 more matches
Movement, orientation, and motion: A WebXR example - Web APIs
session_type the type of xr session to create: inline for an inline session presented in the context of the document and immersive-vr to present the scene to an immersive vr headset.
... const viewerstartposition = vec3.fromvalues(0, 0, -10); const viewerstartorientation = vec3.fromvalues(0, 0, 1.0); const cubeorientation = vec3.create(); const cubematrix = mat4.create(); const mousematrix = mat4.create(); const inverseorientation = quat.create(); const radians_per_degree = math.pi / 180.0; the first two—viewerstartposition and viewerstartorientation—indicate where the viewer will be placed relative to the center of the space, and the direction in which they'll initially be looking.
...startposition); vec3.copy(cubeorientation, viewerstartorientation); xrsession.requestreferencespace(refspacetype) .then((refspace) => { xrreferencespace = refspace.getoffsetreferencespace( new xrrigidtransform(viewerstartposition, cubeorientation)); animationframerequestid = xrsession.requestanimationframe(drawframe); }); return xrsession; } after storing the newly-created xrsession object into xrsession, the label of the button is set to "exit webxr" to indicate its new function after starting the scene, and a handler is installed for the end event, so we get notified when the xrsession ends.
...And 7 more matches
WebXR Device API - Web APIs
the webxr device api implements the core of the webxr feature set, managing the selection of output devices, render the 3d scene to the chosen device at the appropriate frame rate, and manage motion vectors created using input controllers.
... to accomplish these things, the webxr device api provides the following key capabilities: find compatible vr or ar output devices render a 3d scene to the device at an appropriate frame rate (optionally) mirror the output to a 2d display create vectors representing the movements of input controls at the most basic level, a scene is presented in 3d by computing the perspective to apply to the scene in order to render it from the viewpoint of each of the user's eyes by computing the position of each eye and rendering the scene from that position, looking in the direction the user is currently facing.
...using the xrsystem interface, you can create xrsessions to represent actual ar and/or vr sessions.
...And 7 more matches
Background audio processing using AudioWorklet - Web APIs
when the web audio api was first introduced to browsers, it included the ability to use javascript code to create custom audio processors that would be invoked to perform real-time audio manipulations.
...with the processor registered, you can create a new audioworkletnode which passes the audio through the processor's code when the node is linked into the chain of audio nodes along with any other audio nodes.
... create module that defines a audio worklet processor class, based on audioworkletprocessor which takes audio from one or more incoming sources, performs its operation on the data, and outputs the resulting audio data.
...And 7 more matches
Overview of CSS Shapes - CSS: Cascading Style Sheets
there are a number of ways to create these shapes and in these guides we will find out how css shapes work, and consider some ways you might like to use them.
...the result is that the content now curves around the circular shape rather than following the rectangle created by the box of the image.
... we have already seen how circle() creates a circular shape.
...And 7 more matches
Block formatting context - Developer guides
a block formatting context is created by at least one of the following: the root element of the document (<html>).
... anonymous table cells implicitly created by the elements with display: table, table-row, table-row-group, table-header-group, table-footer-group (which is the default for html tables, table rows, table bodies, table headers, and table footers, respectively), or inline-table.
... column-span: all should always create a new formatting context, even when the column-span: all element isn't contained by a multicol container (spec change, chrome bug).
...And 7 more matches
HTML attribute: rel - HTML: Hypertext Markup Language
WebHTMLAttributesrel
not allowed annotation annotation noopener creates a top-level browsing context that is not an auxiliary browsing context if the hyperlink would create either of those to begin with (i.e., has an appropriate target attribute value).
... not allowed annotation annotation opener creates an auxiliary browsing context if the hyperlink would otherwise create a top-level browsing context that is not anauxiliary browsing context (i.e., has "_blank" as target attribute value).
...in this case, on <link> and <form>, if the rel attribute is absent, has no keywords, or if not one or more of the space-separated keywords above, then the element does not create any links.
...And 7 more matches
<input type="datetime-local"> - HTML: Hypertext Markup Language
<input> elements of type datetime-local create input controls that let the user easily enter both a date and a time, including the year, month, and day as well as the time in hours and minutes.
...this is somewhat like having date and time widgets both created for you and merged into one.
...as an example, the datetime-local picker on firefox for android looks like this: non-supporting browsers gracefully degrade to a text input, but this creates problems both in terms of consistency of user interface (the presented control will be different), and data handling.
...And 7 more matches
TypedArray - JavaScript
int8array), an array buffer is created internally in memory or, if an arraybuffer object is given as constructor argument, then this is used instead.
...instead, you create an instance of an array of a particular type, such as a int8array or a bigint64array.
... parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros.
...And 7 more matches
Communicating With Other Scripts - Archive of obsolete content
for example: if an add-on creates a single panel object and loads several content scripts into the panel at the same time, then they can interact with each other.
... if an add-on creates two panel objects and loads a script into each one, they can't interact with each other.
... if an add-on creates a single page-mod object and loads several content scripts into the page mod, then only content scripts associated with the same page can interact with each other: if two different matching pages are loaded, content scripts attached to page a cannot interact with those attached to page b.
...And 6 more matches
Interacting with page scripts - Archive of obsolete content
by default, content scripts loaded by add-ons and scripts loaded by web pages are insulated from each other: content scripts can't interact directly with page scripts or access javascript objects they create page scripts can't interact directly with content scripts or access objects they create.
...you don't want arbitrary web pages to be able to access objects in content scripts, and you don't want objects created by content scripts to clash with objects created by page scripts.
...cloneinto() creates a structured clone of the object in the target context, and returns a reference to the clone.
...And 6 more matches
Creating Reusable Modules - Archive of obsolete content
it's a useful way to create a "fingerprint" that can be used to identify a file.
...the documentation for that interface includes an example which we can adapt like this: var {cc, ci} = require("chrome"); function promptforfile() { const nsifilepicker = ci.nsifilepicker; var fp = cc["@mozilla.org/filepicker;1"] .createinstance(nsifilepicker); var window = require("sdk/window/utils").getmostrecentbrowserwindow(); fp.init(window, "select a file", nsifilepicker.modeopen); fp.appendfilters(nsifilepicker.filterall | nsifilepicker.filtertext); var rv = fp.show(); if (rv == nsifilepicker.returnok || rv == nsifilepicker.returnreplace) { var file = fp.file; // get the path as string.
...we can adapt it like this: var {cc, ci} = require("chrome"); // return the two-digit hexadecimal code for a byte function tohexstring(charcode) { return ("0" + charcode.tostring(16)).slice(-2); } function md5file(path) { var f = cc["@mozilla.org/file/local;1"] .createinstance(ci.nsilocalfile); f.initwithpath(path); var istream = cc["@mozilla.org/network/file-input-stream;1"] .createinstance(ci.nsifileinputstream); // open for reading istream.init(f, 0x01, 0444, 0); var ch = cc["@mozilla.org/security/hash;1"] .createinstance(ci.nsicryptohash); // we want to use the md5 algorithm ch.init(ch.md5); // this tells updatefro...
...And 6 more matches
Interaction between privileged and non-privileged pages - Archive of obsolete content
to trigger the alert() in the listener and pass the data from the web page, write code such as this in the web page: var element = document.createelement("myextensiondataelement"); element.setattribute("attribute1", "foobar"); element.setattribute("attribute2", "hello world"); document.documentelement.appendchild(element); var evt = document.createevent("events"); evt.initevent("myextensionevent", true, false); element.dispatchevent(evt); this code creates an arbitrary element -- <myextensiondataelement/> -- and inserts it into the web p...
...finally, the code creates and dispatches a custom event named myextensionevent -- similar to the standard dom click event you catch with onclick handlers.
... you can optionally clean up the created element, or create it once when the web page loads then re-use it each time.
...And 6 more matches
JavaScript Client API - Archive of obsolete content
to create a custom sync engine to synchronize a new data you, you'll need to define an engine object that extends the base syncengine object.
... in this case, it is highly recommended to use the utils.makeguid() helper to generate new guids: let newguid = utils.makeguid(); your store object must implement the following methods: itemexists(id) createrecord(id, collection) changeitemid(oldid, newid) getallids() wipe() create(record) update(record) remove(record) you may also find it useful to override other methods of the base implementation, for example applyincomingbatch if the underlying storage for your data supports batch operations.
... createrecord the createrecord( id, collection ) method gets called by the engine to request a new record for an item with a given guid.
...And 6 more matches
Mozilla Application Framework in Detail - Archive of obsolete content
editor's note: this article should be rewritten to describe why use xulrunner to create your own application.
...you can create applications using our framework that either have a native look and feel for each os, or one which is identical on macs, pc's or unix operating systems.
...in addition to the technologies already mentioned, we go even further by allowing you to even create your own custom interface widgets.
...And 6 more matches
Creating a Skin - Archive of obsolete content
this section describes how to create a simple skin.
...let's create a skin that we can apply to it.
... you need to create a file 'findfile.css' in a custom skin.
...And 6 more matches
Modifying a XUL Interface - Archive of obsolete content
creating new elements you can create new elements using the createelement() function of the document.
... it takes one argument, the tag name of the element to create.
...for example, the following will add a button to a xul window: example 1 : source view <script> function addbutton(){ var abox = document.getelementbyid("abox"); var button = document.createelement("button"); button.setattribute("label","a new button"); abox.appendchild(button); } </script> <box id="abox" width="200"> <button label="add" oncommand="addbutton();"/> </box> this example has two parts a box container element in xul.
...And 6 more matches
Test your skills: Basic controls - Learn web development
basic controls 1 this task starts you off nice and gently by asking you to create two <input> elements, for a user's id and password, along with a submit button.
... create appropriate inputs for user id and password.
... create a submit button inside the remaining list item, with button text of "log in".
...And 6 more matches
Making asynchronous programming easier with async and await - Learn web development
you can also create an async function expression, like so: let hello = async function() { return "hello" }; hello(); and you can use arrow functions: let hello = async () => { return "hello" }; these all do basically the same thing.
...status: ${response.status}`); } else { return response.blob(); } }) .then(myblob => { let objecturl = url.createobjecturl(myblob); let image = document.createelement('img'); image.src = objecturl; document.body.appendchild(image); }) .catch(e => { console.log('there has been a problem with your fetch operation: ' + e.message); }); by now, you should have a reasonable understanding of promises and how they work, but let's convert this to use async/await to see how much simpler it makes things: asyn...
...status: ${response.status}`); } else { let myblob = await response.blob(); let objecturl = url.createobjecturl(myblob); let image = document.createelement('img'); image.src = objecturl; document.body.appendchild(image); } } myfetch() .catch(e => { console.log('there has been a problem with your fetch operation: ' + e.message); }); it makes code much simpler and easier to understand — no more .then() blocks everywhere!
...And 6 more matches
A first splash into JavaScript - Learn web development
ntent = 'last guess was too low!' ; } else if(userguess > randomnumber) { loworhi.textcontent = 'last guess was too high!'; } } guesscount++; guessfield.value = ''; } guesssubmit.addeventlistener('click', checkguess); function setgameover() { guessfield.disabled = true; guesssubmit.disabled = true; resetbutton = document.createelement('button'); resetbutton.textcontent = 'start new game'; document.body.append(resetbutton); resetbutton.addeventlistener('click', resetgame); } function resetgame() { guesscount = 1; const resetparas = document.queryselectorall('.resultparas p'); for(let i = 0 ; i < resetparas.length ; i++) { resetparas[i].textcontent = ''; } ...
... let's imagine your boss has given you the following brief for creating this game: i want you to create a simple guess the number type game.
...you create a variable with the keyword let (or var) followed by a name for your variable (you'll read more about the difference between the keywords in a future article).
...And 6 more matches
Test your skills: Object-oriented JavaScript - Learn web development
create a new instance of the shape class called square.
... create a new instance of shape called triangle, with a name of triangle and a sidelength of 3.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
...And 6 more matches
Componentizing our Svelte app - Learn web development
other people apply the same techniques used for deciding if you should create a new function or object.
... first of all, create a new file — components/filterbutton.svelte.
... creating our todo component now we will create a todo component to encapsulate each individual todo — including the checkbox and some editing logic so you can change an existing todo.
...And 6 more matches
Package management basics - Learn web development
you could manage your own package registry — products like microsoft azure allow you to create proxies to the npm registry (so you can override or lock certain packages), github also offers a package registry service, and there will be likely more options appearing as time goes on.
... setting up the app as an npm package first of all, create a new directory to store our experimental app in, somewhere sensible that you’ll find again.
... we’ll call it parcel-experiment, but you can call it whatever you like: mkdir parcel-experiment cd parcel-experiment next, let's initialise our app as an npm package, which creates a config file — package.json — that allows us to save our configuration details in case we want to recreate this environment later on, or even publish the package to the npm registry (although this is somewhat beyond the scope of this article).
...And 6 more matches
How Mozilla's build system works
the file is generated from a file called configure.in, which is written in m4 and processed using autoconf 2.13 to create the final configure script.
...0 created; 1 updated; 2187 unchanged total wall time: 5.03s; cpu time: 3.79s; efficiency: 75% what this is saying is that a total of 1,096 moz.build files were read.
...if you wanted to create a consumer that performed a line count of all c++ files or generated a clang compilation database, for example, this would be an acceptable use of a buildbackend.
...And 6 more matches
Overview of Mozilla embedding APIs
do_createinstance this function simplifies creating new component instances.
... ns_getweakreference this function creates a weak reference to a component which implements the nsiweakreference interface.
...conceptually, for each document being rendered, gecko creates a container called a domwindow.
...And 6 more matches
NSS_3.12_release_notes.html
ocspenabledsoftfailurepolicy (see cert.h) cert_getpkixverifynistrevocationpolicy (see cert.h) cert_getusepkixforvalidation (see cert.h) cert_getvaliddnspatternsfromcert (see cert.h) cert_newtempcertificate (see cert.h) cert_setocsptimeout (see certhigh/ocsp.h) cert_setusepkixforvalidation (see cert.h) cert_pkixverifycert (see cert.h) hash_gettype (see sechash.h) nss_initwithmerge (see nss.h) pk11_createmergelog (see pk11pub.h) pk11_creategenericobject (see pk11pub.h) pk11_createpbev2algorithmid (see pk11pub.h) pk11_destroymergelog (see pk11pub.h) pk11_generatekeypairwithopflags (see pk11pub.h) pk11_getpbecryptomechanism (see pk11pub.h) pk11_isremovable (see pk11pub.h) pk11_mergetokens (see pk11pub.h) pk11_writerawattribute (see pk11pub.h) seckey_ecparamstobasepointorderlen (see keyhi.h) seckey_e...
...cparamstokeysize (see keyhi.h) secmod_deletemoduleex (see secmod.h) sec_getregisteredhttpclient (see ocsp.h) sec_pkcs5isalgorithmpbealgtag (see secpkcs5.h) vfy_createcontextdirect (see cryptohi.h) vfy_createcontextwithalgorithmid (see cryptohi.h) vfy_verifydatadirect (see cryptohi.h) vfy_verifydatawithalgorithmid (see cryptohi.h) vfy_verifydigestdirect (see cryptohi.h) vfy_verifydigestwithalgorithmid (see cryptohi.h) new macros for camellia support (see blapit.h): nss_camellia nss_camellia_cbc camellia_block_size new macros for rsa (see blapit.h): rsa_max_modulus_bits rsa_max_exponent_bits new macros in certt.h: x.509 v3 ku_encipher_only cert_max_serial_number_bytes cert_max_dn_bytes pkix cert_rev_m_do_not_test_using_this_method cert_rev_m_test_using_this_method cert_rev_m_allow_netwo...
... bug 354403: nsslist_createiterator returns pointer to a freed memory if the function fails to allocate a lock bug 399236: pkix wrapper must print debug output into stderr bug 399300: pkix error results not freed after use.
...And 6 more matches
PKCS11 Implement
c_closesession the nss calls c_closesession to close sessions created for bulk encryption.
... c_logout the nss calls c_logout on a token's initial session when the password is timed out when performing any kind of private key operation if "ask always" is turned on when changing a password when the user logs out object management c_createobject the nss calls c_createobject when loading new private keys and new certificates into a token.
... typically, nss uses c_createobject for creating a new private key if pkcs #12 is operating or if your writable token doesn't support c_generatekeypair.
...And 6 more matches
NSS tools : modutil
this tool can also create certificate, key, and module security database files.
... -create create new certificate, key, and module databases.
... -dbdir [sql:]directory specify the database directory in which to access or create security module database files.
...And 6 more matches
gtstd.html
if you are creating a server application, you must use the certificate database tool, which comes with nss, to create the certx.db and keyx.db files and populate them with the appropriate certificates and keys.
... if you are creating a client application, you can use either the certificate database tool or the communicator security interface to create the database files and populate them with the appropriate certificates and keys.
... create a new certificate database in the ca_db directory.
...And 6 more matches
NSS tools : modutil
MozillaProjectsNSStoolsmodutil
this tool can also create certificate, key, and module security database files.
... -create create new certificate, key, and module databases.
... -dbdir [sql:]directory specify the database directory in which to access or create security module database files.
...And 6 more matches
Hacking Tips
this unwinder is able to read the frames created by the jit, and to display the frames which are after these jit frames.
... do next in gdb until you reach the definition of the funcptr: // call the per-exported-function trampoline created by generateentry.
... using the tracelogger (js shell / browser) create graphs showing time spent in which engine and which function like this.
...And 6 more matches
JS_DefineConstDoubles
create multiple constant double or integer valued properties on an object.
... obj jsobject * object for which to create new properties.
... cds jsconstdoublespec * pointer to an array of jsconstdoublespec records containing property names and values to create.
...And 6 more matches
Places utilities for JavaScript
placesutils method overview nsiuri createfixeduri(string aspec); string getformattedstring(string key, string params); string getstring(string key); boolean nodeisfolder(nsinavhistoryresultnode anode); boolean nodeisbookmark(nsinavhistoryresultnode anode); boolean nodeisseparator(nsinavhistoryresultnode anode); boolean nodeisvisit(nsinavhistoryresultnode anode); boolean nodei...
...ostrecentbookmarkforuri(nsiuri auri); nsinavhistoryresultnode getmostrecentfolderforfeeduri(nsiuri auri); nsinavhistoryresultnode geturlsforcontainernode(nsinavhistoryresultnode anode); void opencontainernodeintabs(nsinavhistoryresultnode anode, nsidomevent aevent); void openurinodesintabs(array nsinavhistoryresultnode anodes, nsidomevent aevent); void createmenuitemfornode(nsinavhistoryresultnode anode, acontainersmap); constants mimetypes type_x_moz_place_container type_x_moz_place_separator: "text/x-moz-place-separator", type_x_moz_place: "text/x-moz-place", type_x_moz_url: "text/x-moz-url", type_html: "text/html", type_unicode: "text/unicode", services there's easy access to some of the common services used in bookmarks or histo...
... placesflavors generic_view_drop_types methods createfixeduri nsiuri createfixeduri(string aspec) takes in a spec and returns a valid uri based on it using the nsiurifixup service.
...And 6 more matches
Generic factory
in xpcom, a generic factory is a factory created using the facilities in xpcom/glue/nsigenericfactory.h.
...rick potts wrote a templated-based generic factory (nsfactory<t>) that simplifies the factory creation process that just requires writing a createinstance() method.
... */ class nsigenericfactory : public nsifactory { public: static const nsiid& iid() { static nsiid iid = ns_igenericfactory_iid; return iid; } typedef ns_callback(constructorprocptr) (nsisupports *aouter, refnsiid aiid, void **aresult); /** * establishes the generic factory's constructor function, which will be called * by createinstance.
...And 6 more matches
XPCOM array guide
MozillaTechXPCOMGuideArrays
an nsiarray implementation can be created from c++ or javascript using nsicomponentmanager.createinstance() and the contract id "@mozilla.org/array;1".
... the created array implements nsimutablearray and nsiarray.
... c++ example void getlist(nsiarray** aresult) { nscomptr<nsimutablearray> array = do_createinstance(ns_array_contractid); // append some elements ...
...And 6 more matches
XPCOM Stream Guide
MozillaTechXPCOMGuideStreams
this implementation actually writes the contents of the file you're trying to create to a temporary file.
...if you have an input stream called nativestream, you can use code like this: var stream = components.classes["@mozilla.org/scriptableinputstream;1"] .createinstance(components.interfaces.nsiscriptableinputstream); stream.init(nativestream); the stream provides .read(count), .available(), and .close() methods.
...however, it is usually better to create an input stream that you then feed to the output stream: var outstream = components.classes["@mozilla.org/storagestream;1"] .createinstance(components.interfaces.nsistoragestream) .getoutputstream(); var instream = components.classes["@mozilla.org/io/string-input-stream;1"] .createinstance(components.interfaces.nsistringinputstream); var data = "hello world"; instream.setdata(data, data.length); while (instream.available()) { outstream.writefrom(instream, instream.available()); } note this is an inefficient example: the only important part is how to feed the outp...
...And 6 more matches
Components.Constructor
summary creates a javascript function which can be used to create or construct new instances of xpcom components.
... syntax var func = [ new ] components.constructor(contractid [, interfacename [, initializer ] ]); parameters contractid a string containing the contract id of the component interfacename if given, nsisupports.queryinterface() will be called on each newly-created instance with the interface named by this string initializer if given, a string containing the name of a function which will be called on the newly-created instance, using the arguments provided to the created function when called description components.constructor() is a handy shortcut for creating instances of xpcom components.
... it eliminates the clutter of typing components.classes, components.interfaces, createinstance, and so on every time you wish to create an instance.
...And 6 more matches
imgIContainer
to create an instance, use: implemented by: ?????????????????????????????????????
... as a service: var imgicontainer = components.classes["@mozilla.org/????????????????????????????"] .createinstance(components.interfaces.imgicontainer); method overview void addrestoredata([array, size_is(acount), const] in char data, in unsigned long acount); native code only!
...create and return a new copy of the current frame that you can write to and otherwise inspect the pixels of.
...And 6 more matches
nsIAccessibleRetrieval
create a new accessible of the appropriate type if necessary, or use one from the accessibility cache if it already exists.
...create a new accessible of the appropriate type if necessary, or use one from the accessibility cache if it already exists.
...create a new accessible of the appropriate type if necessary, or use one from the accessibility cache if it already exists.
...And 6 more matches
nsICache
access granted - you must write to this descriptor because the cache entry was just created for you.
... access_read_write 3 access requested - i want to read, but i'm willing to update an existing entry if necessary, or create a new one if none exists.
...this constant specify that cache session is not a stream based entry when calling nsicacheservice.createsession() method.
...And 6 more matches
nsICacheService
method overview nsicachesession createsession(in string clientid, in nscachestoragepolicy storagepolicy, in boolean streambased); acstring createtemporaryclientid(in nscachestoragepolicy storagepolicy); obsolete since gecko 1.9.2 void evictentries(in nscachestoragepolicy storagepolicy); void init(); obsolete since gecko 1.8 void shutdown(); obsolete since gecko 1.8 void visitentries(in n...
... methods createsession() this method creates a cache session.
...hence, it is possible to create duplicate cache sessions.
...And 6 more matches
nsIDOMParser
creating a domparser to create a domparser object from a web page or a chrome script running in a window, simply use new domparser().
... when you create a domparser from a privileged script, you can pass parameters to the constructor, more on that below.
... to create a domparser when the constructor is not available (e.g., from a js xpcom component, a js module, or an xpcshell test), use: var parser = components.classes["@mozilla.org/xmlextras/domparser;1"] .createinstance(components.interfaces.nsidomparser); // optionally, call parser.init(principal, documenturi, baseuri); principals, document and base uri note: this section covers changes introduced to domparser in gecko 1.9.
...And 6 more matches
nsINavBookmarksService
nts.classes["@mozilla.org/browser/nav-bookmarks-service;1"] .getservice(components.interfaces.nsinavbookmarksservice); method overview void addobserver(in nsinavbookmarkobserver observer, in boolean ownsweak); void beginupdatebatch(); obsolete since gecko 1.9 void changebookmarkuri(in long long aitemid, in nsiuri anewuri); long long createdynamiccontainer(in long long aparentfolder, in autf8string aname, in astring acontractid, in long aindex); note: renamed from createcontainer in gecko 1.9 obsolete since gecko 13.0 long long createfolder(in long long aparentfolder, in autf8string name, in long index); void endupdatebatch(); obsolete since gecko 1.9 void exportbookmarkshtml(in nsifile file); obsolete sin...
... this method creates a dynamic container under the given parent folder.
... long long createdynamiccontainer( in long long aparentfolder, in autf8string aname, in astring acontractid, in long aindex ); parameters aparentfolder the id of the parent folder.
...And 6 more matches
nsISupports proxies
the only difference is that the first accepts a created object object, and the latter will create an object for you.
...for instance, if you need to not only use an object remotely, but also have it created remotely, use the second api.
...these means that you should have had to create and idl for it and have generated a typelib.
...And 6 more matches
nsIZipWriter
to create an instance, use: var zipwriter = components.classes["@mozilla.org/zipwriter;1"] .createinstance(components.interfaces.nsizipwriter); method overview void addentrychannel(in autf8string azipentry, in prtime amodtime, in print32 acompression, in nsichannel achannel, in boolean aqueue); void addentrydirectory(in autf8string azipentry, in prtime amodtime, in boo...
...(a forward slash is '/') detail: this azipentry is very important, this example demonstrates its usage: var zw = cc['@mozilla.org/zipwriter;1'].createinstance(ci.nsizipwriter); var myzipfile = fu.file('c:\\myzipfile.zip'); //this file will be creatd in c drive var pr = {pr_rdonly: 0x01, pr_wronly: 0x02, pr_rdwr: 0x04, pr_create_file: 0x08, pr_append: 0x10, pr_truncate: 0x20, pr_sync: 0x40, pr_excl: 0x80}; zw.open(xpi, pr.pr_wronly | pr.pr_create_file | pr.pr_truncate); //xpi file is created if not there, if it is there it is truncated/deleted ...
...zw.addentryfile(saveinzipas, ci.nsizipwriter.compression_none, filetoaddtozip, false); this example creates a folder in the zip called "sub folder" and then adds "c:\add this file.txt" to it, but it will be called "blah.txt".
...And 6 more matches
Thunderbird Configuration Files
all these files are plain text files you need to create in your profile folder and can be edited using a standard text editor, such as notepad on windows and gedit or kate on linux.
...the path examples above refers to the default profile that is automatically created when you start thunderbird for the first time.
...this folder does not exist by default, so you need to create it before you can start adding your preferences.
...And 6 more matches
Using the Multiple Accounts API
creating new accounts it is possible to create and modify accounts through the account manager api.
...you should not use createinstance() to create any of the relevant objects because the account manager needs to keep track of all of these objects as they are created.
... to create accounts using the api, you should do the following: create a fresh identity with createidentity(); assign values to the various identity properties as necessary.
...And 6 more matches
Drawing and Event Handling - Plugins
you can also use npn_getvalue to help create a menu or dialog box for a windowless plug-in.
... on ms windows and unix, the browser creates a child window for each plug-in instance and passes it a window through npp_setwindow.
...however, the browser can create invisible instances for which npp_setwindow is never called and a window is never created.
...And 6 more matches
Blob - Web APIs
WebAPIBlob
to create a blob that contains a subset of another blob's data, use the slice() method.
... constructor blob() returns a newly created blob object which contains a concatenation of all of the data in the array passed into the constructor.
... examples creating a blob the blob() constructor can create blobs from other objects.
...And 6 more matches
EventTarget.addEventListener() - Web APIs
passivesupported = true; return false; } }; window.addeventlistener("test", null, options); window.removeeventlistener("test", null, options); } catch(err) { passivesupported = false; } this creates an options object with a getter function for the passive property; the getter sets a flag, passivesupported, to true if it gets called.
... then, when you want to create an actual event listener that uses the options in question, you can do something like this: someelement.addeventlistener("mouseup", handlemouseup, passivesupported ?
...while anonymous (and all traditional javascript functions) create their own this bindings, arrow functions inherit the this binding of the containing function.
...And 6 more matches
FileSystemFileEntry - Web APIs
it offers properties describing the file's attributes, as well as the file() method, which creates a file object that can be used to read the file.
... methods file() creates a new file object which can be used to read the file.
... obsolete methods createwriter() creates a new filewriter object which allows writing to the file represented by the file system entry.
...And 6 more matches
FileSystemFlags - Web APIs
methods which accept an options parameter of this type may specify zero or more of these flags as fields in an object, like this: datadirectoryentry.getdirectory("workspace", { create: true }, function(entry) { }); here, we see that the create property is provided, with a value of true, indicating that the directory should be created if it's not already there.
... properties create optional if this property is true, and the requested file or directory doesn't exist, the user agent should create it.
... exclusive optional if true, and the create option is also true, the file must not exist prior to issuing the call.
...And 6 more matches
HTMLMediaElement.srcObject - Web APIs
until other browsers catch up, for mediasource, blob and file, consider falling back to creating a url with url.createobjecturl() and assign it to htmlmediaelement.src.
... usage notes older versions of the media source specification required using createobjecturl() to create an object url then setting src to that url.
... examples basic example in this example, a mediastream from a camera is assigned to a newly-created <video> element.
...And 6 more matches
IDBObjectStore - Web APIs
methods idbobjectstore.add() returns an idbrequest object, and, in a separate thread, creates a structured clone of the value, and stores the cloned value in the object store.
... idbobjectstore.clear() creates and immediately returns an idbrequest object, and clears this object store in a separate thread.
... idbobjectstore.createindex() creates a new index during a version upgrade, returning a new idbindex object in the connected database.
...And 6 more matches
Checking when a deadline is due - Web APIs
recording the date information to provide a reasonable user experience on mobile devices, and to cut down on ambiguities, i decided to create an html form with: a text input for entering a title for your to-do list.
...duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // add our newitem object to the object store var request = objectstore.add(newitem[0]); in this section we create an object called newitem that stores the data in the format required to insert it into the database.
... the next few lines open the database transaction and provide messages to notify the user if this was successful or failed.then an objectstore is created into which the new item is added.
...And 6 more matches
Intersection Observer API - Web APIs
creating an intersection observer create the intersection observer by calling its constructor and passing it a callback function to be run whenever a threshold is crossed in one direction or the other: let options = { root: document.queryselector('#scrollarea'), rootmargin: '0px', threshold: 1.0 } let observer = new intersectionobserver(callback, options); a threshold of 1.0 means that when 100% of the target is visible within...
... targeting an element to be observed once you have created the observer, you need to give it a target element to watch: let target = document.queryselector('#listitem'); observer.observe(target); // the callback we setup for the observer will be executed now for the first time // it waits until we assign a target to our observer (even if the target is currently not visible) whenever the target meets a threshold specified for the intersectionobserver...
...the values in rootmargin define offsets added to each side of the intersection root's bounding box to create the final intersection root bounds (which are disclosed in intersectionobserverentry.rootbounds when the callback is executed).
...And 6 more matches
Spaces and reference spaces: Spatial tracking in WebXR - Web APIs
note: this article presumes that you are familiar with the concepts introduced in geometry and reference spaces in webxr: that is, the basics of 3d coordinate systems, as well as webxr spaces, reference spaces, and how reference spaces are used to create local coordinate systems for individual objects or movable components within a scene.
...a pose, simply put, describes a position and orientation relative to the origin of the reference space from which it was created.
... there is only one way to create an xrpose, and that's using the getpose() method on an animation frame as given using an xrframe object.
...And 6 more matches
Controlling multiple parameters with ConstantSourceNode - Web APIs
you simply need to create a constantsourcenode and connect it to all of the audioparams whose values should be linked to always match each other.
...in this simple example, we create three oscillatornodes.
... function setup() { context = new (window.audiocontext || window.webkitaudiocontext)(); playbutton = document.queryselector("#playbutton"); volumecontrol = document.queryselector("#volumecontrol"); playbutton.addeventlistener("click", toggleplay, false); volumecontrol.addeventlistener("input", changevolume, false); gainnode1 = context.creategain(); gainnode1.gain.value = 0.5; gainnode2 = context.creategain(); gainnode3 = context.creategain(); gainnode2.gain.value = gainnode1.gain.value; gainnode3.gain.value = gainnode1.gain.value; volumecontrol.value = gainnode1.gain.value; constantnode = context.createconstantsource(); constantnode.connect(gainnode2.gain); constantnode.connect(gainnode3.gain); constantnode.star...
...And 6 more matches
Basic Shapes - CSS: Cascading Style Sheets
you have already met the reference box in the guide on creating shapes from box values, which directly uses the reference box to create the shape.
...in the screenshot below i have created a circle, using shape-outside: circle(50%).
... .shape { shape-outside: circle(50%) border-box; } what is worth noting is that the margin-box will clip the shape, therefore shapes created in reference to other shapes which extend past the margin box will have the shape clipped to the margin box.
...And 6 more matches
Shapes From Images - CSS: Cascading Style Sheets
in this guide we will take a look at how we can create a shape from an image file with an alpha channel or even from a css gradient.
... this is a very flexible way to create shapes.
... rather than drawing a path with a complex polygon in css, you can create the shape in a graphics program and then use the path created by the pixels less opaque than a threshold value.
...And 6 more matches
Visual formatting model - CSS: Cascading Style Sheets
box generation box generation is the part of the css visual formatting model that creates boxes from the document's elements.
... anonymous boxes an anonymous box is created when there is not an html element to use for the box.
...in order to fix the box tree, an anonymous box is created around that run of text.
...And 6 more matches
Audio and video manipulation - Developer guides
the beauty of the web is that you can combine technologies to create new forms.
...you can combine webgl and the <video> element to create video textures, which means you can put video inside 3d scenes.
... html <video id="my-video" controls src="myvideo.mp4" type="video/mp4"> </video> javascript var context = new audiocontext(), audiosource = context.createmediaelementsource(document.getelementbyid("my-video")), filter = context.createbiquadfilter(); audiosource.connect(filter); filter.connect(context.destination); // configure filter filter.type = "lowshelf"; filter.frequency.value = 1000; filter.gain.value = 25; playable code <video id="my-video" controls="true" width="480" height="270" crossorigin="anonymous"> <source src="https://udn.r...
...And 6 more matches
this - JavaScript
calling super() creates a this binding within the constructor and essentially has the effect of evaluating the following line of code, where base is the inherited class: this = new base(); warning: referring to this before calling super() will throw an error.
...calling f.bind(someobject) creates a new function with the same body and scope as f, but where this occurs in the original function, in the new function it is permanently bound to the first argument of bind, regardless of how the function is being used.
... // call as a method of an object var obj = {func: foo}; console.log(obj.func() === globalobject); // true // attempt to set this using call console.log(foo.call(obj) === globalobject); // true // attempt to set this using bind foo = foo.bind(obj); console.log(foo() === globalobject); // true no matter what, foo's this is set to what it was when it was created (in the example above, the global object).
...And 6 more matches
The building blocks of responsive design - Progressive web apps (PWAs)
for web developers, it is now fairly common to be called upon to create a web site or app that changes its user interface depending on the browser or device accessing the site to provide an optimized experience.
... one approach to this is to create different versions of your site/app for different platforms or browsers and serve them appropriately after detecting which browser or platform is looking at your site.
... it is usually much better to create a single version of your code which doesn't care about what browser or platform is accessing the site, but instead uses feature tests to find out what code features the browser supports or what the values of certain browser features are, and then adjusts the code appropriately.
...And 6 more matches
page-worker - Archive of obsolete content
create a permanent, invisible page and access its dom.
...a page worker may be destroyed, after which its memory is freed, and you must create a new instance to load another page.
...to do this, save the file in your add-on's data directory and create the url using the data.url() method of the self module: pageworker = require("sdk/page-worker").page({ contentscript: "console.log(document.body.innerhtml);", contenturl: require("sdk/self").data.url("myfile.html") }); from firefox 34, you can use "./myfile.html" as an alias for self.data.url("myfile.html").
...And 5 more matches
places/bookmarks - Archive of obsolete content
create, modify, and retrieve bookmarks.
... usage this module exports: three constructors: bookmark, group, and separator, corresponding to the types of objects, referred to as bookmark items, in the bookmarks database in firefox two additional functions, save() to create, update, and remove bookmark items, and search() to retrieve the bookmark items that match a particular set of criteria.
... examples creating a new bookmark let { bookmark, save } = require("sdk/places/bookmarks"); // create a new bookmark instance, unsaved let bookmark = bookmark({ title: "mozilla", url: "http://mozilla.org" }); // attempt to save the bookmark instance to the bookmarks database // and store the emitter let emitter = save(bookmark); // listen for events emitter.on("data", function (saved, inputitem) { // on a "data" event, an item has been updated, passing in the // latest snapshot from the ser...
...And 5 more matches
ui/frame - Archive of obsolete content
experimental create html iframes, using bundled html, css and javascript, that can be added to a designated area of the firefox user interface.
... usage this module exports the frame constructor, which can be used to create frame components.
... right now it can be used in conjunction with a toolbar: you create a frame, then supply it to the toolbar's constructor, and the content is then displayed inside the toolbar.
...And 5 more matches
Low-Level APIs - Archive of obsolete content
/loader create commonjs module loaders.
... event/target create objects that broadcast events.
... frame/hidden-frame creates firefox frames (i.e.
...And 5 more matches
Examples and demos from articles - Archive of obsolete content
in different objects and then to create a constructor for such class of objects in order to standardize and simplify the instantiation of them.
...[article] css pure-css dropdown menu [html] with the :hover pseudo-class you can create complex cascade algorithms.
... this is a common technique used, for example, in order to create pure-css dropdown menus (that is only css, without using javascript).
...And 5 more matches
Localizing an extension - Archive of obsolete content
if you haven't already created an extension, or would like to refresh your memory, take a look at the previous articles in this series: creating a status bar extension creating a dynamic status bar extension adding preferences to an extension download the sample you can download this article's sample code so you can look at it side-by-side with the article, or to use it as a basis for your own extension.
... download the sample localizing strings in xul files create the needed locale files each xul file that comprises the user interface for your extension should have a locale file in its locale directory.
...string bundles are created by establishing a property file that maps keys to string values.
...And 5 more matches
MCD, Mission Control Desktop, AKA AutoConfig - Archive of obsolete content
autoconfig directives here we want to set users central mail preferences: create one account from their login name, get their email address from an ldap request and set the enterprise imap and smtp servers.
... thunderbird.cfg (version 1) here's the complete file, first we get the user login name from environment variables, then configure the ldap address book, create an email account, and configure imap and smtp: [root@calaz /usr/lib/thunderbird] $ cat thunderbird.cfg //put everything in a try/catch try { // 1) env variables if(getenv("user") != "") { // *nix settings var env_user = getenv("user"); var env_home = getenv("home"); } else { // windows settings var env_user = getenv("username"); var env_home = getenv("homepath"); } var env_mozdebug= getenv("mozilla_debug"); // var env_user = prompt("indiquez votre login", toto); // 2) lock general preferences //ldap address...
...ts ) { // build the userinfo object for later use for( var attr in ldapattrs ) { userinfo[ ldapattrs[attr] ] = getldapvalue( queryresults, ldapattrs[attr] ); } } else { throw( "no ldap results" ); } } // call upon ldap for the values in ldapattrs array, // uses the previous processldapvalues() getldapattributes( ldaphost, ldapbase, ldapfilter, ldapattrs.join(",") ); // create account // see also http://blog.deanandadie.net/2010/06/easy-thunderbird-account-management-using-mcd/ // identity defaultpref("mail.identity.id1.fullname", userinfo.cn ); defaultpref("mail.identity.id1.smtpserver", "smtp1" ); defaultpref("mail.identity.id1.useremail", userinfo.mail ); // imap server settings defaultpref("mail.server.server1.hostname", "myimap.server.com" ); defaultpref("mail.se...
...And 5 more matches
File object - Archive of obsolete content
summary non-standard server-side object this object lets you work files and directories on the local filesystem, and create os pipelines.
... here is the original proposal for this object, and a status update from december 1998: http://www.mozilla.org/js/js-file-object.html created by the file constructor: new file(); new file(filename); parameters filename name of the file we want to work with.
... when a file is constructed, leading and trailing spaces are removed from the filename, so new file(" abc.txt ") just creates a file called abc.txt.
...And 5 more matches
Tamarin build documentation - Archive of obsolete content
use the following command to create a copy of the tamarin repository: $ hg clone http://hg.mozilla.org/tamarin-central tamarin-central tips for working with mercurial can be found here.
... building tamarin building tamarin will create all the libraries for the avmplus and garbage collector (mmgc), and create a standalone executable (shell) for executing files in the abc file format.
...the setup procedure below creates an android sdk/ndk entirely from publicly available sources.
...And 5 more matches
Using XPInstall to Install Plugins - Archive of obsolete content
myplugininstaller.xpi), and can be created on windows by utilities such as winzip.
... you can create an xpinstall file by first zipping all the items you want installed with winzip (create a zip archive) and then renaming it with the xpi file extension instead of the zip file extension.
...to actually create and write keys to the windows system registry, you'll use the functions of the winreg object.
...And 5 more matches
Working With Directories - Archive of obsolete content
a reference to a directory may be created in the same way as with a file by using nsiscriptableio.getfile().
...these directories do not need to exist yet, but they can be created using nsifile.create().
...var dir = io.getfile("desktop", "myfiles"); dir.append("pictures"); if (dir.exists() && dir.isdirectory()) alert("this is a directory"); creating directories you can create a new directory by using nsifile.create().
...And 5 more matches
Building Menus With Templates - Archive of obsolete content
this means that a menu created with a template will not have any of the generated items until the user opens the menu, or a script opens the menu.
...this allows for better performance as the entire content of a complex menu does not need to be created until the user needs to use the menu.
... it is very simple to create a menu using a template.
...And 5 more matches
Introduction - Archive of obsolete content
note that only the user interface will be created, with only limited functionality.
... what is xul and why was it created?
... xul (pronounced "zool" and rhyming with "cool") was created to make development of the mozilla browser easier and faster.
...And 5 more matches
More Menu Features - Archive of obsolete content
« previousnext » in this section, we'll look at creating submenus and checked menus creating submenus you can create submenus inside other menus (nested menus) using the existing elements.
...however, you can create submenus by simply placing the menu element inside the menupopup element.
...the example below creates a simple submenu inside the file menu example 1 : source view <toolbox flex="1"> <menubar id="sample-menubar"> <menu id="file-menu" label="file"> <menupopup id="file-popup"> <menu id="new-menu" label="new"> <menupopup id="new-popup"> <menuitem label="window"/> <menuitem label="message"/> </menupopup> </menu> <menuitem label="open"/> <menuitem label="save"/> <menuseparator/> <menuitem label="exit"/> </menupopup> </menu> </menubar> </toolbox> adding a menu to our find files example let's add a menu to the find files dialog.
...And 5 more matches
XUL Structure - Archive of obsolete content
these packaged files can be created by using a zip utility.
...to gain the extra privileges, you will need to create a manifest file and put that in the chrome directory.
... this file is easy to create, as it is typically only a couple of lines long.
...And 5 more matches
XML - Archive of obsolete content
lots of people have created new languages out of xml.
...information developers create languages particular to their applications, any time they need a very specific way to represent the structure of some data.
... when we say language, we mean that developers create a set of terms, orlexicon, and a relationship between these terms, or what some people call agrammar.
...And 5 more matches
toolbarbutton - Archive of obsolete content
checkstate type: integer, values 0, 1, or 2 this attribute may be used to create three state buttons, numbered 0, 1 and 2.
...if this attribute is not present, a normal button is created.
... you can set this attribute to the value menu to create a button with a menu popup.
...And 5 more matches
Sunbird Theme Tutorial - Archive of obsolete content
you also need knowledge of: using your operating system to create files and directories using the tools listed above css graphic design knowledge of xul, xbl and javascript is useful for advanced themes.
... creating a unique identifier create an identifier that is likely to be unique, in the form: <tt>something@domain-name</tt> it must contain an at-sign (<tt>@</tt>), making it look something like an e-mail address, but it does not need to be a real e-mail address.
...create a new directory in the <tt>extensions</tt> directory.
...And 5 more matches
Browser Feature Detection - Archive of obsolete content
m css 2 100% 98% 67% 71% / 83% 38% / 42% test results cross reference dom core level 1 support for properties/methods in document name firefox 1.5 ie 6 & 7 opera 8.54 - 9.01 document.doctype true true true document.implementation true true true document.documentelement true true true document.createelement() true true true document.createdocumentfragment() true true true document.createtextnode() true true true document.createcomment() true true true document.createcdatasection() true false true document.createprocessinginstruction() true false true document.createattribute() true ...
... true true document.createentityreference()obsolete since gecko 7 (method present but only returns null: bug 9850) false false document.getelementsbytagname() true true true dom core level 2 support for properties/methods in document name firefox 1.5 ie 6 & 7 opera 8.54 - 9.01 document.doctype true true true document.implementation true true true document.documentelement true true true document.createelement() true true true document.createdocumentfragment() true true true document.createtextnode() true true true document.createcomment() true true true document.createcdatasection() true fals...
...e true document.createprocessinginstruction() true false true document.createattribute() true true true document.createentityreference()obsolete since gecko 7 true false false document.getelementsbytagname() true true true document.importnode() true false true document.createelementns() true false true document.createattributens() true false true document.getelementsbytagnamens() true false true document.getelementbyid() true true true dom level 1 html support for properties/methods in document name firefox 1.5 ie 6 & 7 opera 8.54 - 9.01 document.documentelement true true true d...
...And 5 more matches
RDF in Mozilla FAQ - Archive of obsolete content
if the uri argument refers to an rdf/xml file's url, then the rdf service will create an rdf/xml datasource and asynchronously parse it.
... how do i create a datasource from an rdf/xml file?
... you can either create an rdf/xml datasource using the rdf service's getdatasource() method: // get the rdf service var rdf = components .classes["@mozilla.org/rdf/rdf-service;1"] .getservice(components.interfaces.nsirdfservice); // ...and from it, get the datasource.
...And 5 more matches
Organizing your CSS - Learn web development
create logical sections in your stylesheet it is a good idea to have all of the common styling first in the stylesheet.
... avoid overly-specific selectors if you create very specific selectors you will often find that you need to duplicate chunks of your css to apply the same rules to another element.
... article.main p.box { border: 1px solid #ccc; } if you then wanted to apply the same rules to something outside of main, or to something other than a <p>, you would have to add another selector to these rules or create a whole new ruleset.
...And 5 more matches
Dealing with files - Learn web development
inside your chosen place, create a new folder called web-projects (or similar).
... inside this first folder, create another folder to store your first website in.
...the most common things we'll have on any website project we create are an index html file and folders to contain images, style files, and script files.
...And 5 more matches
Choosing the right approach - Learn web development
nested callbacks) no code example an example that loads a resource via the xmlhttprequest api (run it live, and see the source): function loadasset(url, type, callback) { let xhr = new xmlhttprequest(); xhr.open('get', url); xhr.responsetype = type; xhr.onload = function() { callback(xhr.response); }; xhr.send(); } function displayimage(blob) { let objecturl = url.createobjecturl(blob); let image = document.createelement('img'); image.src = objecturl; document.body.appendchild(image); } loadasset('coffee.jpg', 'blob', displayimage); pitfalls nested callbacks can be cumbersome and hard to read (i.e.
... single delayed operation repeating operation multiple sequential operations multiple simultaneous operations no yes no (unless it is the same one) no code example the following function creates a new date() object, extracts a time string out of it using tolocaletimestring(), and then displays it in the ui.
... we then run it once per second using setinterval(), creating the effect of a digital clock that updates once per second (see this live, and also see the source): function displaytime() { let date = new date(); let time = date.tolocaletimestring(); document.getelementbyid('demo').textcontent = time; } const createclock = setinterval(displaytime, 1000); pitfalls the frame rate isn't optimized for the system the animation is running on, and can be somewhat inefficient.
...And 5 more matches
JavaScript object basics - Learn web development
you should get a result similar to one of the below lines: [object object] object { } { } congratulations, you've just created your first object.
... an object like this is referred to as an object literal — we've literally written out the object contents as we've come to create it.
... it is very common to create an object using an object literal when you want to transfer a series of structured, related data items in some manner, for example sending a request to the server to be put into a database.
...And 5 more matches
Creating our first Vue component - Learn web development
previous overview: client-side javascript frameworks next now it's time to dive deeper into vue, and create our own custom component — we'll start by creating a component to represent each item in the todo list.
... objective: to learn how to create a vue component, render it inside another component, pass data into it using props, and save its state.
... creating a todoitem component let's create our first component, which will display a single todo item.
...And 5 more matches
Command line crash course - Learn web development
out of the box, here are just a few of the things the command line can do, along with names of relevant tools in each case: navigate your computer’s file system along with base level tasks such as create, copy, rename and delete: move around your directory structure: cd create directories: mkdir create files (and modify their metadata): touch copy files: cp move files: mv delete files or directories: rm download files found at specific urls: curl search for fragments of text inside larger bodies of text: grep view a file's contents page by page: less, cat manipulate ...
... have a play with them in a test directory you’ve created somewhere so that you don’t accidentally delete anything important, using the example commands below for guidance: mkdir — this creates a new directory inside the current directory you are in, with the name you provide after the command name.
...for example rmdir my-awesome-website will remove the directory we created above.
...And 5 more matches
Deploying our app - Learn web development
as such, it's important to create a toolchain that handles these problems in a way that requires as little manual intervention as possible.
... the newly-created production code is placed in a new directory called dist, which contains all the files required to run the website, ready for you to upload to a server.
... you should now be able to run the following command in the root of your project directory to run the production build step (first quit the running process with ctrl + c if you need to): npm run build this should give you an output like the following, showing you the production files that were created, how big they are, and how long they took to build: dist/src.99d8a31a.js.map 446.15 kb 63ms dist/src.99d8a31a.js 172.51 kb 5.55s dist/stars.7f1dd035.svg 6.31 kb 145ms dist/asteriod2.3ead4904.svg 3.51 kb 155ms dist/asteriod1.698d75e9.svg 2.9 kb 153ms dist/src.84f2edd1.css.map 2.57 kb 3ms dist/src.84f2edd1.css 1.25 kb ...
...And 5 more matches
Creating Custom Events That Can Pass Data
mozilla/content/events/src/nseventdispatcher.cpp note: in the mozilla 1.8.x branch this code is actually in mozilla/content/events/src/nseventlistenermanager.cpp this is quite an important file since this holds the createevent method which acts as a factory method dom events.
... the change you want to make is in nseventdispatcher::createevent().
... you will find that there is a bunch of code like: if (aeventtype.lowercaseequalsliteral("{somethingsomething}event")) return ns_{somethingsomething}event(adomevent, aprescontext, nsnull); you can either have a function like this or write the code straight in nseventlistenermanager::createevent() like this: if (aeventtype.lowercaseequalsliteral("nsmyevent")){ //note: the lowercase is important!
...And 5 more matches
Localizing with Mercurial
your mercurial configuration is contained within a config file which you must create yourself.
... your config file should have the following settings: [ui] username = your real name <user@example.com> merge = internal:merge [defaults] commit = -v [diff] git = 1 showfunc = 1 unified = 8 to configure hg, follow these steps: create a new file in your favorite text editor.
... here's how to get (or clone) your en-us source files for the first time: run the following command in the command line to get the source en-us files for firefox: hg clone https://hg.mozilla.org/mozilla-central/ this will create a clone of the mozilla-central repository in the directory mozilla-central.
...And 5 more matches
QA phase
manual & automated builds with the click of a button, some l10n tools (like narro and koala) automatically create language pack builds for you.
... to copy this file to the appropriate directory, do the following: navigate to your working directory from your command-line terminal (i.e., where you created the folder structure described above).
... to create and configure this file, follow these instructions: until the fix for bug 1063880 lands on mozilla-aurora and mozilla-beta when building language packs against those two trees you should: remove ac_add_options --disable-compile-environment from .mozconfig in step 3 use ./mach build config after step 4 update the mozilla source code: $ cd mozilla-aurora $ hg pull -u enter the following command to create the .mozconfig file: $ nano -w .mozconfig en...
...And 5 more matches
An overview of NSS Internals
it will detect and open an existing database, or it can create a new one.
...nss will usually create an in-memory (ram) presentation of certificates, once a certificate has been received from the network, read from disk, or looked up from the database, and prepare in-memory data structures that contain the certificate's properties, as well as providing a handle for the programmer to use.
...the usual approach is to create a certificate signing request (csr) as soon as an application is done with the creation step, which will have created a handle to the key pair, and which can be used for the necessary related operations, like producing a proof-of-ownership of the private key, which is usually required when submitting the public key with a csr to a ca.
...And 5 more matches
Encrypt Decrypt MAC Keys As Session Objects
mkey *key, unsigned char *iv, unsigned int ivlen, ck_mechanism_type type, ck_attribute_type operation) { secitem ivitem = { sibuffer, iv, ivlen }; pk11context *ctx = null; secitem *secparam = pk11_paramfromiv(ckm_aes_cbc, &ivitem); if (secparam == null) { pr_fprintf(pr_stderr, "crypt failed : secparam null\n"); return null; } ctx = pk11_createcontextbysymkey(ckm_aes_cbc, operation, key, secparam); if (ctx == null) { pr_fprintf(pr_stderr, "crypt failed : can't create a context\n"); goto cleanup; } cleanup: if (secparam) { secitem_freeitem(secparam, pr_true); } return ctx; } /* * common encryption and decryption code */ secstatus crypt(pk11context *ctx, unsigned char *out, unsigned in...
...unsigned int maclen; unsigned int nwritten; unsigned char encbuf[blocksize]; unsigned int encbuflen; secitem noparams = { sibuffer, null, 0 }; pk11context *ctxmac = null; pk11context *ctxenc = null; unsigned int pad[1]; secitem paditem; unsigned int paddinglength; static unsigned int firsttime = 1; int j; ctxmac = pk11_createcontextbysymkey(ckm_md5_hmac, cka_sign, mk, &noparams); if (ctxmac == null) { pr_fprintf(pr_stderr, "can't create mac context\n"); rv = secfailure; goto cleanup; } rv = macinit(ctxmac); if (rv != secsuccess) { goto cleanup; } ctxenc = encryptinit(ek, iv, ivlen, ckm_aes_cbc); /* read a buffer of plaintext from input file */ while ((p...
...textlen = pr_read(infile, ptext, sizeof(ptext))) > 0) { /* encrypt using it using cbc, using previously created iv */ if (ptextlen != blocksize) { paddinglength = blocksize - ptextlen; for ( j=0; j < paddinglength; j++) { ptext[ptextlen+j] = (unsigned char)paddinglength; } ptextlen = blocksize; } rv = encrypt(ctxenc, encbuf, &encbuflen, sizeof(encbuf), ptext, ptextlen); if (rv != secsuccess) { pr_fprintf(pr_stderr, "encrypt failure\n"); goto cleanup; } /* save the last block of ciphertext as the next iv */ iv = encbuf; ivlen = encbuflen; /* write the cipher text to intermediate file */ n...
...And 5 more matches
Encrypt and decrypt MAC using token
mkey *key, unsigned char *iv, unsigned int ivlen, ck_mechanism_type type, ck_attribute_type operation) { secitem ivitem = { sibuffer, iv, ivlen }; pk11context *ctx = null; secitem *secparam = pk11_paramfromiv(ckm_aes_cbc, &ivitem); if (secparam == null) { pr_fprintf(pr_stderr, "crypt failed : secparam null\n"); return null; } ctx = pk11_createcontextbysymkey(ckm_aes_cbc, operation, key, secparam); if (ctx == null) { pr_fprintf(pr_stderr, "crypt failed : can't create a context\n"); goto cleanup; } cleanup: if (secparam) { secitem_freeitem(secparam, pr_true); } return ctx; } /* * common encryption and decryption code */ secstatus crypt(pk11context *ctx, unsigned char *out, unsigned in...
...unsigned int maclen; unsigned int nwritten; unsigned char encbuf[blocksize]; unsigned int encbuflen; secitem noparams = { sibuffer, null, 0 }; pk11context *ctxmac = null; pk11context *ctxenc = null; unsigned int pad[1]; secitem paditem; unsigned int paddinglength; static unsigned int firsttime = 1; int j; ctxmac = pk11_createcontextbysymkey(ckm_md5_hmac, cka_sign, mk, &noparams); if (ctxmac == null) { pr_fprintf(pr_stderr, "can't create mac context\n"); rv = secfailure; goto cleanup; } rv = macinit(ctxmac); if (rv != secsuccess) { goto cleanup; } ctxenc = encryptinit(ek, iv, ivlen, ckm_aes_cbc); /* read a buffer of plaintext from input file */ while ((p...
...textlen = pr_read(infile, ptext, sizeof(ptext))) > 0) { /* encrypt using it using cbc, using previously created iv */ if (ptextlen != blocksize) { paddinglength = blocksize - ptextlen; for ( j=0; j < paddinglength; j++) { ptext[ptextlen+j] = (unsigned char)paddinglength; } ptextlen = blocksize; } rv = encrypt(ctxenc, encbuf, &encbuflen, sizeof(encbuf), ptext, ptextlen); if (rv != secsuccess) { pr_fprintf(pr_stderr, "encrypt failure\n"); goto cleanup; } /* save the last block of ciphertext as the next iv */ iv = encbuf; ivlen = encbuflen; /* write the cipher text to intermediate file */ n...
...And 5 more matches
Encrypt Decrypt_MAC_Using Token
mkey *key, unsigned char *iv, unsigned int ivlen, ck_mechanism_type type, ck_attribute_type operation) { secitem ivitem = { sibuffer, iv, ivlen }; pk11context *ctx = null; secitem *secparam = pk11_paramfromiv(ckm_aes_cbc, &ivitem); if (secparam == null) { pr_fprintf(pr_stderr, "crypt failed : secparam null\n"); return null; } ctx = pk11_createcontextbysymkey(ckm_aes_cbc, operation, key, secparam); if (ctx == null) { pr_fprintf(pr_stderr, "crypt failed : can't create a context\n"); goto cleanup; } cleanup: if (secparam) { secitem_freeitem(secparam, pr_true); } return ctx; } /* * common encryption and decryption code.
...unsigned int maclen; unsigned int nwritten; unsigned char encbuf[blocksize]; unsigned int encbuflen; secitem noparams = { sibuffer, null, 0 }; pk11context *ctxmac = null; pk11context *ctxenc = null; unsigned int pad[1]; secitem paditem; unsigned int paddinglength; static unsigned int firsttime = 1; int j; ctxmac = pk11_createcontextbysymkey(ckm_md5_hmac, cka_sign, mk, &noparams); if (ctxmac == null) { pr_fprintf(pr_stderr, "can't create mac context\n"); rv = secfailure; goto cleanup; } rv = macinit(ctxmac); if (rv != secsuccess) { goto cleanup; } ctxenc = encryptinit(ek, iv, ivlen, ckm_aes_cbc); /* read a buffer of plaintext from input file.
... */ while ((ptextlen = pr_read(infile, ptext, sizeof(ptext))) > 0) { /* encrypt using it using cbc, using previously created iv.
...And 5 more matches
NSS Sample Code Sample_3_Basic Encryption and MACing
mkey *key, unsigned char *iv, unsigned int ivlen, ck_mechanism_type type, ck_attribute_type operation) { secitem ivitem = { sibuffer, iv, ivlen }; pk11context *ctx = null; secitem *secparam = pk11_paramfromiv(ckm_aes_cbc, &ivitem); if (secparam == null) { pr_fprintf(pr_stderr, "crypt failed : secparam null\n"); return null; } ctx = pk11_createcontextbysymkey(ckm_aes_cbc, operation, key, secparam); if (ctx == null) { pr_fprintf(pr_stderr, "crypt failed : can't create a context\n"); goto cleanup; } cleanup: if (secparam) { secitem_freeitem(secparam, pr_true); } return ctx; } /* * common encryption and decryption code */ secstatus crypt(pk11context *ctx, unsigned char *out, unsigned in...
...unsigned int maclen; unsigned int nwritten; unsigned char encbuf[blocksize]; unsigned int encbuflen; secitem noparams = { sibuffer, null, 0 }; pk11context *ctxmac = null; pk11context *ctxenc = null; unsigned int pad[1]; secitem paditem; unsigned int paddinglength; static unsigned int firsttime = 1; int j; ctxmac = pk11_createcontextbysymkey(ckm_md5_hmac, cka_sign, mk, &noparams); if (ctxmac == null) { pr_fprintf(pr_stderr, "can't create mac context\n"); rv = secfailure; goto cleanup; } rv = macinit(ctxmac); if (rv != secsuccess) { goto cleanup; } ctxenc = encryptinit(ek, iv, ivlen, ckm_aes_cbc); /* read a buffer of plaintext from input file */ while ((p...
...textlen = pr_read(infile, ptext, sizeof(ptext))) > 0) { /* encrypt using it using cbc, using previously created iv */ if (ptextlen != blocksize) { paddinglength = blocksize - ptextlen; for ( j=0; j < paddinglength; j++) { ptext[ptextlen+j] = (unsigned char)paddinglength; } ptextlen = blocksize; } rv = encrypt(ctxenc, encbuf, &encbuflen, sizeof(encbuf), ptext, ptextlen); if (rv != secsuccess) { pr_fprintf(pr_stderr, "encrypt failure\n"); goto cleanup; } /* save the last block of ciphertext as the next iv */ iv = encbuf; ivlen = encbuflen; /* write the cipher text to intermediate file */ n...
...And 5 more matches
EncDecMAC using token object - sample 3
or decryption - common code */ pk11context * cryptinit(pk11symkey *key, unsigned char *iv, unsigned int ivlen, ck_mechanism_type type, ck_attribute_type operation) { secitem ivitem = { sibuffer, iv, ivlen }; pk11context *ctx = null; secitem *secparam = pk11_paramfromiv(ckm_aes_cbc, &ivitem); if (secparam == null) { pr_fprintf(pr_stderr, "crypt failed : secparam null\n"); return null; } ctx = pk11_createcontextbysymkey(ckm_aes_cbc, operation, key, secparam); if (ctx == null) { pr_fprintf(pr_stderr, "crypt failed : can't create a context\n"); goto cleanup; } cleanup: if (secparam) { secitem_freeitem(secparam, pr_true); } return ctx; } /* * common encryption and decryption code */ secstatus crypt(pk11context *ctx, unsigned char *out, unsigned int *outlen, unsigned int maxout, unsigned char *in, uns...
...d char ptext[blocksize]; unsigned int ptextlen; unsigned char mac[digestsize]; unsigned int maclen; unsigned int nwritten; unsigned char encbuf[blocksize]; unsigned int encbuflen; secitem noparams = { sibuffer, null, 0 }; pk11context *ctxmac = null; pk11context *ctxenc = null; unsigned int pad[1]; secitem paditem; unsigned int paddinglength; static unsigned int firsttime = 1; int j; ctxmac = pk11_createcontextbysymkey(ckm_md5_hmac, cka_sign, mk, &noparams); if (ctxmac == null) { pr_fprintf(pr_stderr, "can't create mac context\n"); rv = secfailure; goto cleanup; } rv = macinit(ctxmac); if (rv != secsuccess) { goto cleanup; } ctxenc = encryptinit(ek, iv, ivlen, ckm_aes_cbc); /* read a buffer of plaintext from input file */ while ((ptextlen = pr_read(infile, ptext, sizeof(ptext))) > 0) { /* encrypt...
... using it using cbc, using previously created iv */ if (ptextlen != blocksize) { paddinglength = blocksize - ptextlen; for ( j=0; j < paddinglength; j++) { ptext[ptextlen+j] = (unsigned char)paddinglength; } ptextlen = blocksize; } rv = encrypt(ctxenc, encbuf, &encbuflen, sizeof(encbuf), ptext, ptextlen); if (rv != secsuccess) { pr_fprintf(pr_stderr, "encrypt failure\n"); goto cleanup; } /* save the last block of ciphertext as the next iv */ iv = encbuf; ivlen = encbuflen; /* write the cipher text to intermediate file */ nwritten = pr_write(encfile, encbuf, encbuflen); /*pr_assert(nwritten == encbuflen);*/ rv = macupdate(ctxmac, ptext, ptextlen); } rv = macfinal(ctxmac, mac, &maclen, digestsize); if (rv != secsuccess) { pr_fprintf(pr_stderr, "macfinal failure\n"); goto cleanup; } if (maclen == 0...
...And 5 more matches
NSS Tools modutil
this tool can also create key3.db, cert8.db, and secmod.db security database files.
...the options and arguments for the modutil command are defined as follows: options -create create new secmod.db, key3.db, and cert8.db files.
... arguments -dbdir directory specify the database directory in which to access or create security module database files.
...And 5 more matches
Scripting Java
the above examples could be expressed as follows: $ java org.mozilla.javascript.tools.shell.main js> importclass(packages.org.mozilla.javascript.context); js> context.currentcontext; org.mozilla.javascript.context@bb6ab6 working with java now that we can access java classes, the next logical step is to create an object.
... implementing java interfaces now that we can access java classes, create java objects, and access fields, methods, and properties of those objects, we have a great deal of power at our fingertips.
... to address this need, rhino provides the ability to create new java objects that implement interfaces.
...And 5 more matches
JS_InitClass
once js_initclass creates the new class's constructor, it stores the constructor as a property in this object.
...js_initclass always creates a new prototype object that serves as the __proto__ for class instances; parent_proto becomes the __proto__ of that prototype object.
...instead it must create a new object and return it.
...And 5 more matches
JS_NewObject
creates a new javascript object.
...ject(jscontext *cx, const jsclass *clasp, js::handle<jsobject*> proto, js::handle<jsobject*> parent); jsobject * js_newobjectwithgivenproto(jscontext *cx, const jsclass *clasp, js::handle<jsobject*> proto, js::handle<jsobject*> parent); // added in spidermonkey 1.8 name type description cx jscontext * the context in which to create the new object.
...if this is null, an ordinary javascript object is created.
...And 5 more matches
History Service Design
for example, is possible to create a query folder containing the 10 pages most visited by the user, allowing to fast find good candidates for bookmarking.
...history service provides the basics to create such adaptive search paths, allowing for a better browsing experience through a common interface.
... database maintenance at startup the service creates an exclusive storage connection to places.sqlite, the exclusive locking is needed for both a perf gain and data-safety.
...And 5 more matches
Setting up the Gecko SDK
the following four sections tell the developer how to download and organize the gecko sdk and create a new project in which components like weblock can be created.
...including this header file in your project ensures that the component you create uses the same defines as the gecko libraries themselves.
... building a microsoft visual cpp project once you set up the gecko sdk, you can create a microsoft visual c++ project to handle component development with the sdk.
...And 5 more matches
Components.utils.Sandbox
components.utils.sandbox is used to create a sandbox object for use with evalinsandbox().
... creating a sandbox to create a new sandbox, call components.utils.sandbox: var sandbox = components.utils.sandbox(principal[, options]); using new components.utils.sandbox(...) to create a sandbox has the same effect as calling sandbox(...) without new.
... the created sandbox is simply an empty javascript object marked as having been created by the restricted privilege principal.
...And 5 more matches
nsIDOMXPathEvaluator
to create an instance, use: var domxpathevaluator = components.classes["@mozilla.org/dom/xpath-evaluator;1"] .createinstance(components.interfaces.nsidomxpathevaluator); method overview nsidomxpathexpression createexpression(in domstring expression, in nsidomxpathnsresolver resolver) nsidomxpathnsresolver creatensresolver(in nsidomnode noderesolver); nsisupports evaluate(in domstring expression, in nsidomnode contextnode, in nsidomxpathnsresolver resolver, in unsigned short type, in nsisupports resu...
...lt) methods createexpression() creates an nsidomxpathexpression which can then be used for (repeated) evaluations.
... nsidomxpathexpression createexpression( in domstring expression, in nsidomxpathnsresolver resolver ); parameters expression a string representing the xpath to be created.
...And 5 more matches
nsILivemarkService
toolkit/components/places/public/nsilivemarkservice.idlscriptable this interface is used to create and reload livemarks.
...to use this service, use: var livemarkservice = components.classes["@mozilla.org/browser/livemark-service;2"] .getservice(components.interfaces.nsilivemarkservice); method overview long long createlivemark(in long long folder, in astring name, in nsiuri siteuri, in nsiuri feeduri, in long index); long long createlivemarkfolderonly(in long long folder, in astring name, in nsiuri siteuri, in nsiuri feeduri, in long index); nsiuri getfeeduri(in long long container); long long getlivemarkidforfeeduri(in nsiuri afeeduri); nsiuri getsiteuri(in long long conta...
...iner); boolean islivemark(in long long folder); void reloadalllivemarks(); void reloadlivemarkfolder(in long long folderid); void setfeeduri(in long long container, in nsiuri feeduri); void setsiteuri(in long long container, in nsiuri siteuri); void start(); void stopupdatelivemarks(); methods createlivemark() creates a new livemark.
...And 5 more matches
nsIPluginHost
inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview nsifile createtempfiletopost(in string apostdataurl); native code only!
... void createtmpfiletopost(in string apostdataurl, out string atmpfilename); native code only!
... methods native code only!createtempfiletopost to create temp file with content len header in, it will use by http post.
...And 5 more matches
Using COM from js-ctypes
basis and reference for this article bugzilla :: bug 738501 - implement ability to create windows shortcuts from javascript - comment 4 relavent topic bugzilla :: bug 505907 - support c++ calling from jsctypes converting com code to c code to convert com code to js-ctypes, we need to write c++ vtable pointers in c.
... #include <sapi.h> int main(void) { if (succeeded(coinitialize(null))) { ispvoice* pvoice = null; hresult hr = cocreateinstance(clsid_spvoice, null, clsctx_all, iid_ispvoice, (void**)&pvoice); if (succeeded(hr)) { pvoice->speak(l"hello, firefox!", spf_default, null); pvoice->release(); } } // msdn documentation says that even if coinitalize fails, counitialize // must be called couninitialize(); return 0; } to run the code, save it as test.
... #include <sapi.h> int main(void) { if (succeeded(coinitialize(null))) { struct ispvoice* pvoice = null; hresult hr = cocreateinstance(&clsid_spvoice, null, clsctx_all, &iid_ispvoice, (void**)&pvoice); if (succeeded(hr)) { pvoice->lpvtbl->speak(pvoice, l"hello, firefox!", 0, null); pvoice->lpvtbl->release(pvoice); } } // msdn documentation says that even if coinitalize fails, counitialize // must be called couninitiali...
...And 5 more matches
Index - Firefox Developer Tools
18 debugger when called as a constructor, the debugger object creates a new debugger instance.
...they can just create and use objects, and when the objects are no longer needed, the runtime takes care of cleaning up, and frees the memory the objects occupied.
... 58 edit css filters css, devtools, filters, page inspector, tools css filter properties in the rules view have a circular gray and white swatch next to them: 59 edit shape paths in css css, devtools, page inspector, rules view, tools, highlighter, shapes the shape path editor is a tool that helps you see and edit shapes created using clip-path and also the css shape-outside property and <basic-shape> values.
...And 5 more matches
AbstractRange - Web APIs
staticrange a staticrange is a basic range which cannot be changed once it's been created.
...in order to set a range endpoint within the text of an element, be sure to find the text node inside the element: let startelem = document.queryselector("p"); let endelem = startelem.queryselector("span"); let range = document.createrange(); range.setstart(startelem, 0); range.setend(endelem, endelem.childnodes[0].length/2); let contents = range.clonecontents(); document.body.appendchild(contents); this example creates a new range, rng, and sets its starting point to the third child node of the first element whose class is elementclass.
... if you want to create a range that incorporates the contents of the <p> element whose contents are "a <em>very</em> interesting thing happened on the way to the forum...", you can do so like this: let prange = document.createrange(); prange.selectnodecontents(document.queryselector("#entry1 p")); since we wish to select the entire contents of the <p> element, including its descendants, this works perfectly.
...And 5 more matches
AudioBufferSourceNode - Web APIs
an audiobuffersourcenode can only be played once; after each call to start(), you have to create a new node if you want to play the same sound again.
... fortunately, these nodes are very inexpensive to create, and the actual audiobuffers can be reused for multiple plays of the sound.
... indeed, you can use these nodes in a "fire and forget" manner: create the node, call start() to begin playing the sound, and don't even bother to hold a reference to it.
...And 5 more matches
AudioContext - Web APIs
you need to create an audiocontext before you do anything else, as everything happens inside a context.
... it's recommended to create one audiocontext and reuse it instead of initializing a new one each time, and it's ok to use a single audiocontext for several different audio source and pipeline concurrently.
...ext" target="_top"><rect x="151" y="1" width="120" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="211" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">audiocontext</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor audiocontext() creates and returns a new audiocontext object.
...And 5 more matches
Pixel manipulation with canvas - Web APIs
y * (width * 4) + x * 4; return [red, red + 1, red + 2, red + 3]; }; const colorindices = getcolorindicesforcoord(xcoord, ycoord, canvaswidth); const [redindex, greenindex, blueindex, alphaindex] = colorindices; you may also access the size of the pixel array in bytes by reading the uint8clampedarray.length attribute: var numbytes = imagedata.data.length; creating an imagedata object to create a new, blank imagedata object, you should use the createimagedata() method.
... there are two versions of the createimagedata() method: var myimagedata = ctx.createimagedata(width, height); this creates a new imagedata object with the specified dimensions.
... you can also create a new imagedata object with the same dimensions as the object specified by anotherimagedata.
...And 5 more matches
Using Fetch - Web APIs
the code would look something like this: fetch('flowers.jpg') .then(response => { if (!response.ok) { throw new error('network response was not ok'); } return response.blob(); }) .then(myblob => { myimage.src = url.createobjecturl(myblob); }) .catch(error => { console.error('there has been a problem with your fetch operation:', error); }); supplying your own request object instead of passing a path to the resource you want to request into the fetch() call, you can create a request object using the request() constructor, and pass that in as a fetch() method argument: const myheaders = new headers(); ...
...const myrequest = new request('flowers.jpg', { method: 'get', headers: myheaders, mode: 'cors', cache: 'default', }); fetch(myrequest) .then(response => response.blob()) .then(myblob => { myimage.src = url.createobjecturl(myblob); }); request() accepts exactly the same parameters as the fetch() method.
... you can even pass in an existing request object to create a copy of it: const anotherrequest = new request(myrequest, myinit); this is pretty useful, as request and response bodies are one use only.
...And 5 more matches
HTMLTableElement - Web APIs
htmltableelement.createthead() returns an htmlelement representing the first <thead> that is a child of the element.
... if none is found, a new one is created and inserted in the tree immediately before the first element that is neither a <caption>, nor a <colgroup>, or as the last child if there is no such element.
... htmltableelement.createtfoot() returns an htmlelement representing the first <tfoot> that is a child of the element.
...And 5 more matches
IDBDatabase - Web APIs
the idbdatabase interface of the indexeddb api provides a connection to a database; you can use an idbdatabase object to open a transaction on your database then create, manipulate, and delete objects (data) in that database.
...when a database is first created, this attribute is an empty string.
... idbdatabase.createmutablefile() creates a file handle, allowing files to be stored inside an indexeddb database.
...And 5 more matches
Basic concepts - Web APIs
because it lets you create web applications with rich query abilities regardless of network availability, these applications can work both online and offline.
...you can create indexes that use any property of the objects for quick searching, as well as sorted enumeration.
...indexeddb, on the other hand, requires you to create an object store for a type of data and simply persist javascript objects to that store.
...And 5 more matches
SVGSVGElement - Web APIs
svgsvgelement.createsvgnumber() creates an svgnumber object outside of any document trees.
... svgsvgelement.createsvglength() creates an svglength object outside of any document trees.
... svgsvgelement.createsvgangle() creates an svgangle object outside of any document trees.
...And 5 more matches
A basic 2D WebGL animation example - Web APIs
in this webgl example, we create a canvas and within it render a rotating square using webgl.
...tex-shader" }, { type: gl.fragment_shader, id: "fragment-shader" } ]; shaderprogram = buildshaderprogram(shaderset); aspectratio = glcanvas.width/glcanvas.height; currentrotation = [0, 1]; currentscale = [1.0, aspectratio]; vertexarray = new float32array([ -0.5, 0.5, 0.5, 0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, -0.5, -0.5 ]); vertexbuffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, vertexbuffer); gl.bufferdata(gl.array_buffer, vertexarray, gl.static_draw); vertexnumcomponents = 2; vertexcount = vertexarray.length/vertexnumcomponents; currentangle = 0.0; rotationrate = 6; animatescene(); } after getting the webgl context, gl, we need to begin by building the shader program.
... the array of vertices is created next, as a float32array with six coordinates (three 2d vertices) per triangle to be drawn, for a total of 12 values.
...And 5 more matches
Using WebRTC data channels - Web APIs
creating a data channel the underlying data transport used by the rtcdatachannel can be created in one of two ways: let webrtc create the transport and announce it to the remote peer for you (by causing it to receive a datachannel event).
...to do this, simply call createdatachannel() without specifying a value for the negotiated property, or specifying the property with a value of false.
... this will automatically trigger the rtcpeerconnection to handle the negotiations for you, causing the remote peer to create a data channel and linking the two together across the network.
...And 5 more matches
Fundamentals of WebXR - Web APIs
mixed reality is a large and complex subject, with much to learn and many other apis to bring together in order to create an engaging experience for users.
... thus, webxr was created.
...which type of session you want to create is specified when creating the session.
...And 5 more matches
Using IIR filters - Web APIs
so you can create a highpass filter, or a lowpass filter, or a more bespoke one.
... and this is where the iir filter node is useful — you can create your own if none of the alaready available settings is right for what you want.
... with that all in mind, let's take a look at the code to create an iir filter with the web audio api.
...And 5 more matches
Web audio spatialization basics - Web APIs
basics of spatialization in web audio, complex 3d spatializations are created using the pannernode, which in layman's terms is basically a whole lotta cool maths to make audio appear in 3d space.
... 3d boombox demo to demonstrate 3d spatialization we've created a modified version of the boombox demo we created in our basic using the web audio api guide.
... let's create our context and listener and set the listener's position to emulate a person looking into our room: const audiocontext = window.audiocontext || window.webkitaudiocontext; const audioctx = new audiocontext(); const listener = audioctx.listener; const posx = window.innerwidth/2; const posy = window.innerheight/2; const posz = 300; listener.positionx.value = posx; listener.positiony.value = posy;...
...And 5 more matches
Box-shadow generator - CSS: Cascading Style Sheets
true : false; this.topic = topic; this.node = node; var pointer = document.createelement('div'); pointer.classname = 'ui-slider-pointer'; node.appendchild(pointer); this.pointer = pointer; setmousetracking(node, updateslider.bind(this)); sliders[topic] = this; setvalue(topic, this.value); } var setbuttoncomponent = function setbuttoncomponent(node) { var type = node.getattribute('data-type'); var topic = node.getattribute('data-topic'); if (type === "sub...
...'; node.addeventlistener("click", function() { decrement(topic); }); } if (type === "add") { node.textcontent = '+'; node.addeventlistener("click", function() { increment(topic); }); } } var setinputcomponent = function setinputcomponent(node) { var topic = node.getattribute('data-topic'); var unit_type = node.getattribute('data-unit'); var input = document.createelement('input'); var unit = document.createelement('span'); unit.textcontent = unit_type; input.setattribute('type', 'text'); node.appendchild(input); node.appendchild(unit); input.addeventlistener('click', function(e) { this.select(); }); input.addeventlistener('change', function(e) { setvalue(topic, e.target.value | 0); }); subscribe(topic, function(value) { nod...
...ttonmanager */ var buttonmanager = (function checkboxmanager() { var subscribers = []; var buttons = []; var checkbox = function checkbox(node) { var topic = node.getattribute('data-topic'); var state = node.getattribute('data-state'); var name = node.getattribute('data-label'); var align = node.getattribute('data-text-on'); state = (state === "true"); var checkbox = document.createelement("input"); var label = document.createelement("label"); var id = 'checkbox-' + topic; checkbox.id = id; checkbox.setattribute('type', 'checkbox'); checkbox.checked = state; label.setattribute('for', id); if (name) { label.classname = 'text'; if (align) label.classname += ' ' + align; label.textcontent = name; } node.appendchild(checkbox); node.appendchild...
...And 5 more matches
Introduction to formatting contexts - CSS: Cascading Style Sheets
any block-level element can be made to create a bfc by the application of certain css properties.
... a new bfc is created in the following situations: elements made to float using float absolutely positioned elements (including position: fixed or position: sticky) elements with display: inline-block table cells or elements with display: table-cell, including anonymous table cells created when using the display: table-* properties table captions or elements with display: table-caption block elements where overflow has a value other than visible elements with display: flow-root or display: flow-root list-item elements with contain: layout, content, or strict flex items grid items multicol containers elements with column-span set to all this is useful because a new bfc will behave much like the outermost document in that it becomes a mini-layout inside the main layout.
... setting overflow: auto created a new bfc containing the float.
...And 5 more matches
Cross-browser audio basics - Developer guides
this article provides: a basic guide to creating a cross-browser html5 audio player with all the associated attributes, properties, and events explained a guide to custom controls created using the media api basic audio example the code below is an example of a basic audio implementation using html5: <audio controls> <source src="audiofile.mp3" type="audio/mpeg"> <source src="audiofile.ogg" type="audio/ogg"> <!-- fallback for non supporting browsers goes here --> <p>your browser does not support html5 audio, but you can still <a href="audiofile.mp3">download the music</a>.</p> </audio> note: you can also use an mp4 file instead of mp3.
...so the ideal place to create a fallback or inform of incompatibility is before the closing </audio> tag.
...if you don't specify this attribute, no controls will appear — and you will instead have to create your own controls and program their functionality using the media api (see below).
...And 5 more matches
<input type="date"> - HTML: Hypertext Markup Language
WebHTMLElementinputdate
<input> elements of type="date" create input fields that let the user enter a date, either with a textbox that validates the input or a special date picker interface.
...as an example, the date picker on firefox for android looks like this: unsupporting browsers gracefully degrade to a text input, but this creates problems in consistency of user interface (the presented controls are different) and data handling.
... examples in this example, we create 2 sets of ui elements for choosing dates: a native <input type="date"> picker and a set of 3 <select> elements for older browsers that don't support the native date input.
...And 5 more matches
Grammar and types - JavaScript
this form creates an undeclared global variable.
... constants you can create a read-only, named constant with the const keyword.
...when you create an array using an array literal, it is initialized with the specified values as its elements, and its length is set to the number of arguments specified.
...And 5 more matches
Numbers and dates - JavaScript
you cannot change the values of these properties and you use them as follows: var biggestnum = number.max_value; var smallestnum = number.min_value; var infinitenum = number.positive_infinity; var neginfinitenum = number.negative_infinity; var notanum = number.nan; you always refer to a property of the predefined number object as shown above, and not as a property of a number object you create yourself.
... unlike many other objects, you never create a math object of your own.
... to create a date object: var dateobjectname = new date([parameters]); where dateobjectname is the name of the date object being created; it can be a new object or a property of an existing object.
...And 5 more matches
Functions - JavaScript
however, object references are values, too, and they are special: if the function changes the referred object's properties, that change is visible outside the function, as shown in the following example: /* declare the function 'myfunc' */ function myfunc(theobject) { theobject.brand = "toyota"; } /* * declare variable 'mycar'; * create and initialize a new object; * assign reference to it to 'mycar' */ var mycar = { brand: "honda", model: "accord", year: 1998 }; /* logs 'honda' */ console.log(mycar.brand); /* pass object reference to the function */ myfunc(mycar); /* * logs 'toyota' as the value of the 'brand' property * of the object, as changed to by the function.
... here is an example of an anonymous function expression (the name is not used): var myfunction = function() { statements } it is also possible to provide a name inside the definition in order to create a named function expression: var myfunction = function namedfunction(){ statements } one of the benefits of creating a named function expression is that in case we encountered an error, the stack trace will contain the name of the function, making it easier to find the origin of the error.
... the function constructor note: using the function constructor to create functions is not recommended since it needs the function body as a string which may prevent some js engine optimizations and can also cause other problems.
...And 5 more matches
Array - JavaScript
common operations 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'...
... creating an array using the result of a match the result of a match between a regexp and a string can create a javascript array.
... [1]: "bb" [2]: "d" constructor array() creates a new array object.
...And 5 more matches
core/heritage - Archive of obsolete content
pet.prototype = object.create(dog.prototype); // if you want correct instanceof behavior you need to make a dance with // another special `constructor` property of the `prototype` object.
...constructors created using class function don't require new keyword (even though it can be used) for instantiation.
... also, idiomatic sdk code does not uses optional new keywords, but you're free to use it in your add-on code: var fluffy = dog('fluffy'); // instatiation fluffy instanceof dog // => true fluffy instanceof class // => true as you could notice from example above classes created via class function by default inherits from a class itself.
...And 4 more matches
Getting Started (jpm) - Archive of obsolete content
prerequisites to create add-ons for firefox using the sdk, you'll need: firefox version 38 or later.
... initializing an empty add-on in the command prompt, create a new directory.
... navigate to it, type jpm init, and hit enter: mkdir my-addon cd my-addon jpm init you'll then be asked to supply some information about your add-on: this will be used to create your add-on's package.json file.
...And 4 more matches
Modifying Web Pages Based on URL - Archive of obsolete content
to create a page-mod, you need to specify two things: one or more content scripts to run whose job is to interact with web content.
... a simple code snippet where content script is supplied as contentscript option and url pattern is given as include option is as follows: // import the page-mod api var pagemod = require("sdk/page-mod"); // create a page-mod // it will run a script whenever a ".org" url is loaded // the script replaces the page contents with a message pagemod.pagemod({ include: "*.org", contentscript: 'document.body.innerhtml = ' + ' "<h1>page matches ruleset</h1>";' }); do as follows: create a new directory and navigate to it.
... for example, if we save the script above under the add-on's data directory in a file called my-script.js: // import the page-mod api var pagemod = require("sdk/page-mod"); // import the self api var self = require("sdk/self"); // create a page-mod // it will run a script whenever a ".org" url is loaded // the script replaces the page contents with a message pagemod.pagemod({ include: "*.org", contentscriptfile: self.data.url("my-script.js") }); or from firefox 34 onwards: // import the page-mod api var pagemod = require("sdk/page-mod"); // create a page-mod // it will run a script whenever a ".org" url is loaded // the sc...
...And 4 more matches
Bookmarks - Archive of obsolete content
firefox 2 and earlier creating a new bookmark var win = mybrowser.contentwindow; // get the bookmarks service const bmsvc = components.classes["@mozilla.org/browser/bookmarks-service;1"] .getservice(components.interfaces.nsibookmarksservice); // create the bookmark bmsvc.createbookmarkincontainer(win.document.title, // bookmark name win.location.href.tostring(), // uri of the bookmark null, // shortcut win.document.title, // description win.document.characterset, // charset null, // postdata bookmarksservice.getbookmarkstoolbarfolder(), // bookmark folder ...
...he bookmarks service as is the case with nearly all interfaces, before you can use the bookmarks service, you need to get access to it: var bmsvc = components.classes["@mozilla.org/browser/nav-bookmarks-service;1"] .getservice(components.interfaces.nsinavbookmarksservice); creating a bookmark folder creating a new bookmark folder is done using the nsinavbookmarksservice.createfolder() method.
... for example, to create a new folder in the bookmarks menu: var menufolder = bmsvc.bookmarksmenufolder; // bookmarks menu folder var newfolderid = bmsvc.createfolder(menufolder, "folder name here", bmsvc.default_index); this code locates the bookmarks menu's folder, then creates a new folder named "folder name here" in it.
...And 4 more matches
Appendix: What you should know about open-source software licenses - Archive of obsolete content
what is important to us now is the following three rights: open source rights: a user can create and distribute copies of the source code; a user can obtain a program’s source code; a user can modify the source code.
... pros and cons the modified bsd license was originally created by the university of california at berkeley for distributing a unix-like operating system.
... however, the fact that software derived from bsd-licensed code can be redistributed under a different license creates the possibility that it will be wrapped in another proprietary program.
...And 4 more matches
Appendix D: Loading Scripts - Archive of obsolete content
additionally, as sandbox objects can be created with an arbitrary prototype object, the evaluated code can be given access to the global properties of any existing scope.
...let context = content; // create the sandbox let sandbox = components.utils.sandbox(context, { // make properties of the context object available via the // script's global scope sandboxprototype: context, // wrap objects retrieved from the sandbox in xpcnativewrappers.
...the script will execute in the same security context as the current script and will have access to the same globals, but any new globals it creates will be accessible only to the script itself.
...And 4 more matches
Local Storage - Archive of obsolete content
the common practice is to create a directory with the name of your project at the root of the profile folder, and keep your files inside.
... the structure could be something like this: s435l.default (your profile directory) xulschool log.txt somedbfile.sqlite the directory service and the nsifile interface are used to create the local directory.
... here's what we usually do: we have a function that returns a reference to our root directory and creates it if necessary.
...And 4 more matches
Setting up an extension development environment - Archive of obsolete content
overview you'll create a new user profile to run your development specific firefox session.
...as we are specifically defining the user profile dev, if you don't have the dev profile already created, the profile selection window opens, where you can create it.
...(linux, mac os x, windows instructions.) you'll see the list of available user profiles one which is default (stable) and other (unstable) profile(s) created automatically when you run other versions of firefox earlier.
...And 4 more matches
Signing an XPI - Archive of obsolete content
initialize the certificate database decide which folder to create the certificate database in.
... use this command to create it (note the trailing dot is required).
... the dot will cause the database to be created in the current directory.
...And 4 more matches
Actionscript Acceptance Tests - Archive of obsolete content
you must create a testname.as.avm_args file with the uses_swfversion directive.
...eg: -no-optimize merge| -as3 a dir.asc_args file can also be created with the same contents that will apply to the entire directory.
... here is a more complicated example that passes both avm args, multiple abcs and test args: -ojit |multiabc| $dir/testname_support/a.abc -- test_args a dir.avm_args file can also be created with the same contents that will apply to the entire directory.
...And 4 more matches
toolbarbutton.type - Archive of obsolete content
if this attribute is not present, a normal button is created.
... you can set this attribute to the value menu to create a button with a menu popup.
... menu: set the type attribute to the value menu to create a button with a menu popup.
...And 4 more matches
MenuModification - Archive of obsolete content
this method will create a new menuitem element and insert it into the popup.
...the appenditem method will create a menupopup element if it doesn't already exist.
... <script> function addsubmenu() { var popup = document.getelementbyid("file-popup"); var newmenu = document.createelement("menu"); popup.appendchild(newmenu); newmenu.label = "new"; newmenu.appenditem("document", "doc"); newmenu.appenditem("image", "image"); } </script> <menu label="file" onpopupshowing="addsubmenu()"> <menupopup id="file-popup"/> </menu>.
...And 4 more matches
Popup Guide - Archive of obsolete content
popups and menus there are various types of popups and menus that may be created.
... popup types xul provides a number of different types of elements which may be used to create popup menus or other types of popup widgets, which vary based on the manner in which they are attached to an element and the manner in which they are opened.
...a popup is not created as a separate window or file, instead it is included inside another window or dialog.
...And 4 more matches
List Controls - Archive of obsolete content
xul provides two types of elements to create lists, a listbox element to create multi-row list boxes, and a menulist element to create drop-down list boxes.
...you would use this to create column headers.
... drop-down lists drop-down lists can be created in html using the select element.
...And 4 more matches
Scroll Bars - Archive of obsolete content
scroll bars can be created in a number of ways.
... in xul, one can be created using the scrollbar tag.
...a scroll bar creates all of these elements automatically.
...And 4 more matches
XUL Questions and Answers - Archive of obsolete content
as an extension author, you have at least two options: use dom methods to dynamically create or rearrange elements file an enhancement request in bugzilla to have extra ids added.
...json string) from the server, parsing it on client, and building the menupopup using dom methods (such as document.createelementns).
...*/ how do i create xul elements dynamically in javascript?
...And 4 more matches
NPN_GetURL - Archive of obsolete content
« gecko plugin api reference « plug-in side plug-in api summary asks the browser to create a stream for the specified url.
...safest target, even though, when used with a mailto or news url, this creates an extra blank the browser instance.
... if the target is null, the browser creates a new stream and delivers the data to the current instance regardless of the mime type of the url.
...And 4 more matches
Processing XML with E4X - Archive of obsolete content
it is possible to interpolate variables into an xml literal to create an element name (or to create content).
... var h = 'html'; var text = "here's some text"; var doc = <{h}><body>{text}</body></{h}>; alert(doc.toxmlstring()); // gives <html> <body>here's some text</body> </html> working with attributes xml literal syntax has a significant advantage over the xml constructor when you need to create markup dynamically.
...variables and expressions can be used to create attribute values by simply wrapping them with braces ({}) and omitting quotation marks that would normally go around an attribute value, as the following example illustrates: var a = 2; var b = <foo bar={a}>"hi"</foo>; upon execution the variable is evaluated and quotes are automatically added where appropriate.
...And 4 more matches
Bounding volume collision detection with THREE.js - Game development
instantiating boxes to create a box3 instance, we need to provide the lower and upper boundaries of the box.
... we can easily debug collisions by rendering the meshes that boxhelper creates.
... by default they are created with a linebasicmaterial material (a three.js material for drawing wireframe-style geometries).
...And 4 more matches
GLSL Shaders - Game development
three.js and other 3d libraries abstract a lot of things for you — if you wanted to create such an example in raw webgl, you'd have to write a lot of extra code to actually make it work.
... create a directory to store your experiments in.
...we'll create a scene featuring a simple cube in this file to explain how the shaders work.
...And 4 more matches
Implementing game control mechanisms - Game development
streamlining cross device differences creates multiple challenges, not least when providing appropriate controls for different contexts.
... captain rogers was created using the phaser framework, the most popular tool for simple 2d game development in javascript right now, but it should be fairly easy to reuse the knowledge contained within these articles when building games in pure javascript or any other framework.
... every state has its own default methods: preload(), create(), and update().
...And 4 more matches
Plug-in Development Overview - Gecko Plugin API Reference
plan your plug-in: decide on the services you want the plug-in software to provide and how it will interact with the browser and the special media for which the plug-in is created.
...you can use a variety of environments to create a plug-in, but make sure that you have the necessary files from the plugin sdk.
... create a plug-in project.
...And 4 more matches
Accessible multimedia - Learn web development
previous overview: accessibility next another category of content that can create accessibility problems is multimedia — video, audio, and image content need to be given proper textual alternatives so they can be understood by assistive technologies and their users.
... to remedy this, we can create our own custom controls.
... create a new file called main.js and save it in the same directory.
...And 4 more matches
How to build custom form controls - Learn web development
designing new interactions is generally only an option for very large industry players who have enough reach that an interaction they create can become a standard.
... .select { /* this will create a positioning context for the list of options; adding this to .select:focus-within will be a better option when fully supported */ position: relative; /* this will make our control become part of the text flow and sizable at the same time */ display : inline-block; } we need an extra class active to define the look and feel of our control when it is in its active state.
...we've created a similar control to our custom control, that works even if the javascript fails.
...And 4 more matches
Test your skills: Other controls - Learn web development
other controls 1 in our first "other controls" assessment, we'll get you to create a multi-line text input.
... create a basic multi-line text input.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
...And 4 more matches
Test your skills: Conditionals - Learn web development
we want you to create a conditional that checks whether season contains the string "summer", and if so assigns a string to response that gives the user an appropriate message about the season.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... you need to create an if...else structure that checks whether the machine is switched on and puts a message into the response variable if it isn't, telling the user to switch the machine on.
...And 4 more matches
Useful string methods - Learn web development
when you create a string, for example by using let string = 'this is my string'; your variable becomes a string object instance, and as a result has a large number of properties and methods available to it.
...as my love', 'a happy christmas to all the family', 'you\'re all i want for christmas', 'get well soon']; for (let i = 0; i < greetings.length; i++) { let input = greetings[i]; // your conditional test needs to go inside the parentheses // in the line below, replacing what's currently there if (greetings[i]) { let listitem = document.createelement('li'); listitem.textcontent = input; list.appendchild(listitem); } } </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="reset"> <input id="solution" type="button" value="show solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } b...
...tmas my love\',' + '\n \'a happy christmas to all the family\',' + '\n \'you\\\'re all i want for christmas\',' + '\n \'get well soon\'];' + '\n' + '\nfor (let i = 0; i < greetings.length; i++) {' + '\n let input = greetings[i];' + '\n if (greetings[i].indexof(\'christmas\') !== -1) {' + '\n let result = input;' + '\n let listitem = document.createelement(\'li\');' + '\n listitem.textcontent = result;' + '\n list.appendchild(listitem);' + '\n }' + '\n}'; let solutionentry = jssolution; textarea.addeventlistener('input', updatecode); window.addeventlistener('load', updatecode); // stop tab key tabbing out of textarea and // make it write a tab at the caret position instead textarea.onkeydown = function(e){ if (e.keycode === 9) {...
...And 4 more matches
Solve common problems in your JavaScript code - Learn web development
strings how do you create a string in javascript?
... arrays how do you create an array?
... how do you create your own functions?
...And 4 more matches
Server-side web frameworks - Learn web development
templates are often used to create html, but can also create other types of document.
... productivity: productivity is a measure of how quickly you can create new features once you are familiar with the framework, and includes both the effort to write and maintain code (since you can't write new features while old ones are broken).
...— other factors include: framework purpose/origin: some web frameworks were initially created to solve certain types of problems, and remain better at creating web apps with similar constraints.
...And 4 more matches
Ember interactivity: Events, classes and state - Learn web development
objective: to learn how to create component classes and use events to control interactivity, and keep track of app state using a service.
... to create a header class to go with your header component, type this in to your terminal: ember generate component-class header this will create the following empty class file — todomvc/app/components/header.js: import component from '@glimmer/component'; export default class headercomponent extends component { } inside this file we will implement the event handler code.
... run this terminal command to generate a service for us to store our todo-list data in: ember generate service todo-data this should give you a terminal output like so: installing service create app/services/todo-data.js installing service-test create tests/unit/services/todo-data-test.js this creates a todo-data.js file inside the todomvc/app/services directory to contain our service, which initially contains an import statement and an empty class: import service from '@ember/service'; export default class tododataservice extends service { } first of all, we want to define what a...
...And 4 more matches
React interactivity: Events and state - Learn web development
handling form submission at the top of the form() component function, create a function named handlesubmit().
... we want our handlesubmit() function to ultimately help us create a new task, so we need a way to pass information from <form /> to <app />.
... handling form submission via callbacks inside the top of our app() component function, create a function named addtask() which has a single parameter of name: function addtask(name) { alert(name); } next, we'll pass addtask() into <form /> as a prop.
...And 4 more matches
Deployment and next steps - Learn web development
a look behind the svelte compilation process by default, when you create a new app with npx degit sveltejs/template my-svelte-project, svelte will use rollup as the module bundler.
...[y/n] n linked to opensas/mdn-svelte-tutorial (created .vercel) inspect: https://vercel.com/opensas/mdn-svelte-tutorial/[...] [1s] ✅ production: https://mdn-svelte-tutorial.vercel.app [copied to clipboard] [19s] deployed to production.
... first you'll have to register at gitlab and then create a new project.
...And 4 more matches
Understanding client-side JavaScript frameworks - Learn web development
react tutorials note: react tutorials last tested in may 2020, with react/reactdom 16.13.1 and create-react-app 3.4.1.
...we'll discover a little bit of detail about its background and use cases, set up a basic react toolchain on our local computer, and create and play with a simple starter app, learning a bit about how react works in the process.
...getting started with ember in our first ember article we will look at how ember works and what it's useful for, install the ember toolchain locally, create a sample app, and then do some initial setup to get it ready for development.
...And 4 more matches
Strategies for carrying out testing - Learn web development
note: some efforts have been made to create publically accessible device labs — see open device labs.
...a good option provided by most virtual machine apps is to create a dynamically allocated hard drive that grows and shrinks as the need arises.
... open the app; you'll be presented with a view like the following: to create a new virtual machine, press the new button in the top left hand corner.
...And 4 more matches
Configuring Build Options
create a blank mozconfig file: echo "# my first mozilla config" > mozconfig if your mozconfig isn't in your source directory, you can also use the mozconfig environment variable to specify the path to your mozconfig.
...to avoid the time it takes to do a full rebuild, you can create multiple mozconfig files which specify different objdirs.
... you can either create multiple mozconfig files, or alternatively, use the moz_build_projects make option.
...And 4 more matches
Multiple Firefox profiles
if you want to do this frequently and more easily, you may wish to create an automator application, as explained in this tutorial.
... to start the create profile wizard, click "create profile..." in the profile manager.
... to create the new profile, click finish.
...And 4 more matches
Embedding Tips
alternatively, create a standalone webbrowser persist object and call the nsiwebbrowserpersist interface on that to save uris and documents.
...in response it creates a persist object, creates a listener and starts the operation.
...the nsiwindowcreator::createchromewindow method will be called whenever gecko needs to open a new window.
...And 4 more matches
JavaScript-DOM Prototypes in Mozilla
when xpconnect wraps a c++ object it will create a jsobject that is unique to this c++ object.
... the prototype object that xpconnect creates for the classes that have class info are shared within a scope (window).
...the prototype of a constructor will either be the prototype object that xpconnect creates for a class (if the name is the name of a real class) or simply an empty jsobject of a specific jsclass that is defined in nsdomclassinfo.cpp (nsdomclassinfo::sdomconstructorprotoclass).
...And 4 more matches
Localization content best practices
this document provides best practices for developers to create localizable code, and describes how to avoid some localizability (l12y) common mistakes.
...this would waste everybody's time and create unnecessary frustration: localizers have to translate strings that are destined to change, developers will need to use new ids later to update them.
... create localizable strings don't assume grammar structures you need to consider the need for different grammar structures in different locales, and add switching mechanisms to present them appropriately.
...And 4 more matches
PR_OpenSemaphore
creates or opens a named semaphore with the specified name.
... syntax #include <pripcsem.h> #define pr_sem_create 0x1 /* create if not exist */ #define pr_sem_excl 0x2 /* fail if already exists */ nspr_api(prsem *) pr_opensemaphore( const char *name, printn flags, printn mode, pruintn value ); parameters the function has the following parameters: name the name to be given the semaphore.
... flags how to create or open the semaphore.
...And 4 more matches
PR_OpenSharedMemory
opens an existing shared memory segment or, if one with the specified name doesn't exist, creates a new one.
... syntax #include <prshm.h> nspr_api( prsharedmemory * ) pr_opensharedmemory( const char *name, prsize size, printn flags, printn mode ); /* define values for pr_opensharememory(...,create) */ #define pr_shm_create 0x1 /* create if not exist */ #define pr_shm_excl 0x2 /* fail if already exists */ parameters the function has the following parameters: name the name of the shared memory segment.
... description pr_opensharedmemory creates a new shared memory segment or associates a previously created memory segment with the specified name.
...And 4 more matches
JSS Provider Notes
if you do not wish the provider to be installed, create a cryptomanager.initializationvalues object, set its installjssprovider field to false, and pass the initializationvalues object to cryptomanager.initialize().
...once a jca object has been created it will continue to use the same token, even if the application later changes the per-thread default token.
... whenever a new thread is created, its token is initialized to the default, the internal key storage token.
...And 4 more matches
Mozilla-JSS JCA Provider notes
if you do not wish the provider to be installed, create a cryptomanager.initializationvalues object, set its installjssprovider field to false, and pass the initializationvalues object to cryptomanager.initialize().
...once a jca object has been created it will continue to use the same token, even if the application later changes the per-thread default token.
... whenever a new thread is created, its token is initialized to the default, the internal key storage token.
...And 4 more matches
NSS Sample Code Sample1
sample code #include <iostream.h> #include "pk11pub.h" #include "keyhi.h" #include "nss.h" // key management for keys share among multiple hosts // // this example shows how to use nss functions to create and // distribute keys that need to be shared among multiple servers // or hosts.
...the example here shows how to create a permanent (token) // rsa key for this purpose.
...in particular, this // creates the key pair that is used for wrapping keys int init(); // generates keys for encryption (aes) and macing.
...And 4 more matches
GC Rooting Guide
if you use these types directly, or create classes, structs or arrays that contain them, you must follow the rules set out in this guide.
...a js::handle<t> is a reference to a js::rooted<t>, and is created implicitly by referencing a js::rooted<t>: it is not valid to create a js::handle<t> manually (the whole point of a handle is that it only reference pointers that the gc knows about so it can update them when they move).
...like a reference, a js::handle is immutable: it can only ever refer to the js::rooted<t> that it was created for.
...And 4 more matches
JS_ConstructObject
create a new object of the specified class, with the specified prototype and parent, then invokes a constructor function to initialize the new object.
... syntax jsobject * js_constructobject(jscontext *cx, jsclass *clasp, jsobject *proto, jsobject *parent); jsobject * js_constructobjectwitharguments(jscontext *cx, jsclass *clasp, jsobject *proto, jsobject *parent, unsigned int argc, jsval *argv); name type description cx jscontext * the context in which to create the new object.
...if this is null, an ordinary javascript object is created.
...And 4 more matches
JS_DefineObject
create an object that is a property of another object.
... syntax jsobject * js_defineobject(jscontext *cx, js::handleobject obj, const char *name, const jsclass *clasp = nullptr, unsigned attrs = 0); name type description cx jscontext * the context in which to create the new object.
... description js_defineobject creates a new object of the class clasp and assigns it to a new property of an existing object, obj.
...And 4 more matches
JS_GetParent
each object is assigned a parent when it is created: the standard library objects and functions all have the global object as their parent.
... objects created by standard library functions, such as array.prototype.concat, have the global object as their parent.
... an object created by a script via the new keyword has the same parent as the constructor.
...And 4 more matches
Shell global objects
ce use the isrunonce compiler option (default: false) noscriptrval use the no-script-rval compiler option (default: false) filename filename for error messages and debug info linenumber starting line number for error messages and debug info columnnumber starting column number for error messages and debug info global global in which to execute the code newcontext if true, create and use a new cx (default: false) catchtermination if true, catch termination (failure without an exception value, as for slow scripts or out-of-memory) and return 'terminated' element if present with value v, convert v to an object o and mark the source as being attached to the dom element o.
... createmappedarraybuffer(filename, [offset, [size]]) create an array buffer that mmaps the given file.
...note that these values don't get cached, so repeatedly getting the same value creates multiple distinct clones.
...And 4 more matches
Web Replay
this is done in the following ways: instead of creating or destroying threads on demand, while recording/replaying all threads which will be needed are created during process initialization.
... if during the recording the content tries to create more threads than were spawned up front, then the recording fails.
... these threads idle until the recording/replaying content tries to 'create' them, then they run their main function, and after completing it will idle indefinitely.
...And 4 more matches
Signing Mozilla apps for Mac OS X
while testing and debugging for test and debug purposes, the easiest way to get a signing certificate is to use apple's keychain feature to create one.
... there are good instructions available under "to use the certificate assistant to create a self-signed signing identity".
...once you have that you can do the following to create your id: open the developer certificate utility.
...And 4 more matches
mozIStorageAggregateFunction
objects implementing this interface can be registered with mozistorageconnection.createaggregatefunction().
... javascript // first, create our object that will represent our function.
...dbconn.createaggregatefunction("stddev", 1, standarddeviationfunc); // run some query that uses the function.
...And 4 more matches
mozIStorageStatement
storage/public/mozistoragestatement.idlscriptable this interface lets you create and execute sql statements on a mozistorageconnection.
...to initialize a statement, consumers should call mozistorageconnection.createstatement().
... clone() creates a copy of the statement whose state will be mozistoragestatement.moz_storage_statement_ready.
...And 4 more matches
nsIAppStartup
to use the service: var appstartup = components.classes["@mozilla.org/toolkit/app-startup;1"] .getservice(components.interfaces.nsiappstartup); method overview void createhiddenwindow(); boolean createstartupstate(in long awindowwidth, in long awindowheight); obsolete since gecko 1.9.1 void destroyhiddenwindow(); void doprofilestartup(in nsicmdlineservice acmdlineservice, in boolean caninteract); obsolete since gecko 1.9.1 void ensure1window(in nsicmdlineservice acmdlineservice); obsolete since gecko 1.9.1 void enterlas...
... methods createhiddenwindow() create the hidden window.
... void createhiddenwindow(); parameters none.
...And 4 more matches
nsIMsgFolder
void setfilterlist(in nsimsgfilterlist filterlist); void forcedbclosed(); void delete(); void deletesubfolders(in nsisupportsarray folders, in nsimsgwindow msgwindow); void propagatedelete(in nsimsgfolder folder, in boolean deletestorage,in nsimsgwindow msgwindow); void recursivedelete(in boolean deletestorage, in nsimsgwindow msgwindow); void createsubfolder(in astring foldername, in nsimsgwindow msgwindow); nsimsgfolder addsubfolder(in astring foldername); void createstorageifmissing(in nsiurllistener urllistener); void compact(in nsiurllistener alistener, in nsimsgwindow amsgwindow); void compactall(in nsiurllistener alistener, innsimsgwindow amsgwindow,in nsisupportsarray afolderarray, in boolean acompa...
...e.g., you might want to associate an identity with a particular newsgroup, or for imap shared folders in the other users namespace, you might want to create a delegated identity.
... cansubscribe boolean readonly canfilemessages boolean readonly noselect boolean readonly: this is an imap no select folder imapshared boolean readonly: this is an imap shared folder candeletemessages boolean readonly: can't delete from imap read-only cancreatesubfolders boolean readonly: does this folder allow subfolders.
...And 4 more matches
nsIScriptableIO
the file does not have to exist already; this method simply creates the file reference which may then be passed to the newinputstream() or newoutputstream() method to open the file for reading or writing.
... newuri() creates a uri object that implements the nsiuri interface.
... nsiuri newuri( in nsivariant auri ); parameters auri the file for which to create a new nsiuri object.
...And 4 more matches
nsIURIFixup
inherits from: nsisupports last changed in gecko 9.0 (firefox 9.0 / thunderbird 9.0 / seamonkey 2.6) implemented by: @mozilla.org/docshell/urifixup;1 as a service: var urifixup = components.classes["@mozilla.org/docshell/urifixup;1"] .createinstance(components.interfaces.nsiurifixup); method overview nsiuri createexposableuri(in nsiuri auri); nsiuri createfixupuri(in autf8string auritext, in unsigned long afixupflags); nsiuri keywordtouri(in autf8string akeyword); nsiurifixupinfo getfixupuriinfo(in autf8string auritext, in unsigned long afixupflags); constants constant value description ...
... methods createexposableuri() converts an internal uri (for example a wysiwyg uri) into one which we can expose to the user, for example on the url bar.
... nsiuri createexposableuri( in nsiuri auri ); parameters auri the uri to be converted.
...And 4 more matches
nsIXULTemplateBuilder
if a result passes a rule's conditions, this is considered a match, and the content within the rule's <action> body is inserted as a sibling of the <template>, assuming the template builder creates real dom content.
...for a tree builder, for example, the content within the action body is used to create the tree rows instead.
...resultbindingchanged(in nsixultemplateresult aresult); nsixultemplateresult getresultforid(in astring aid); nsixultemplateresult getresultforcontent(in nsidomelement aelement); boolean hasgeneratedcontent(in nsirdfresource anode, in nsiatom atag); void addrulefilter(in nsidomnode arule, in nsixultemplaterulefilter afilter); [noscript] void init(in nsicontent aelement); [noscript] void createcontents(in nsicontent aelement, in boolean aforcecreation); void addlistener(in nsixulbuilderlistener alistener); void removelistener(in nsixulbuilderlistener alistener); attributes attribute type description root nsidomelement readonly: the root node in the dom to which this builder is attached.
...And 4 more matches
XPCOM
since binary components are linked against a single gecko sdk, a dependency to a particular version of gecko is created.
...this can create a difficult situation for extension developers trying to support multiple gecko versions (firefox 2 and 3, for example).creating a python xpcom componentcreating applications with mozilla already provides a tutorial for making a simple javascript or c++ component (implementing the nsisimple interface).
... here is how to make the same component in python using pyxpcom.fun with xbl and xpconnectgenerating guidsguids are used in mozilla programming for identifying several types of entities, including xpcom interfaces (this type of guids is callled iid), components (cid), and legacy add-ons—like extensions and themes—that were created prior to firefox 1.5.
...And 4 more matches
Zombie compartments
when are compartments created?
... any compartments with the following forms are created by firefox for its own internal use, and can usually be ignored when looking for zombie compartments.
... so it's common for multiple compartments to be created for a single web page.
...And 4 more matches
Plug-in Development Overview - Plugins
plan your plug-in: decide on the services you want the plug-in software to provide and how it will interact with the browser and the special media for which the plug-in is created.
...you can use a variety of environments to create a plug-in, but make sure that you have the necessary files from the plugin sdk.
... create a plug-in project.
...And 4 more matches
Using the CSS Typed Object Model - Web APIs
/ get the <dl> we'll be populating const styleslist = document.queryselector('#regurgitation'); // retrieve all computed styles with computedstylemap() const defaultcomputedstyles = myelement.computedstylemap(); // iterate thru the map of all the properties and values, adding a <dt> and <dd> for each for (const [prop, val] of defaultcomputedstyles) { // properties const cssproperty = document.createelement('dt'); cssproperty.appendchild(document.createtextnode(prop)); styleslist.appendchild(cssproperty); // values const cssvalue = document.createelement('dd'); cssvalue.appendchild(document.createtextnode(val)); styleslist.appendchild(cssvalue); } the computedstylemap() method returns a stylepropertymapreadonly object containing the size property, which indicates how many properties a...
...let's start by adding some css to our example, including a custom property and an inhertable property: p { font-weight: bold; } a { --color: red; color: var(--color); } instead of getting all the properties, we create an array of properties of interest and use the stylepropertymapreadonly.get() method to get each of their values: <p> <a href="https://example.com">link</a> </p> <dl id="regurgitation"></dl> // get the element const myelement = document.queryselector('a'); // get the <dl> we'll be populating const styleslist = document.queryselector('#regurgitation'); // retrieve all computed styles with...
... computedstylemap() const allcomputedstyles = myelement.computedstylemap(); // array of properties we're interested in const ofinterest = ['font-weight', 'border-left-color', 'color', '--color']; // iterate through our properties of interest for ( let i = 0; i < ofinterest.length; i++ ) { // properties const cssproperty = document.createelement('dt'); cssproperty.appendchild(document.createtextnode(ofinterest[i])); styleslist.appendchild(cssproperty); // values const cssvalue = document.createelement('dd'); cssvalue.appendchild(document.createtextnode( allcomputedstyles.get(ofinterest[i]))); styleslist.appendchild(cssvalue); } we included border-left-color to demonstrate that, had we included all the properties, every value that defaults to currentcolor (including caret-c...
...And 4 more matches
CanvasRenderingContext2D - Web APIs
gradients and patterns canvasrenderingcontext2d.createlineargradient() creates a linear gradient along the line given by the coordinates represented by the parameters.
... canvasrenderingcontext2d.createradialgradient() creates a radial gradient given by the coordinates of the two circles represented by the parameters.
... canvasrenderingcontext2d.createpattern() creates a pattern using the specified image (a canvasimagesource).
...And 4 more matches
Using images - Web APIs
« previousnext » until now we have created our own shapes and applied styles to them.
... getting images to draw the canvas api is able to use any of the following data types as an image source: htmlimageelement these are images created using the image() constructor, as well as any <img> element.
... creating an image from scratch another option is to create new htmlimageelement objects in our script.
...And 4 more matches
CustomElementRegistry.define() - Web APIs
there are two types of custom elements you can create: autonomous custom element: standalone elements; they don't inherit from built-in html elements.
...used to create a customized built-in element.
... // create a class for the element class popupinfo extends htmlelement { constructor() { // always call super first in constructor super(); // create a shadow root var shadow = this.attachshadow({mode: 'open'}); // create spans var wrapper = document.createelement('span'); wrapper.setattribute('class','wrapper'); var icon = document.createelement('span'); icon.setattr...
...And 4 more matches
FileSystemDirectoryEntry - Web APIs
basic concepts you can create a new directory by calling getdirectory().
... if you want to create subdirectories, create each child directory in sequence.
...so create the hierarchy by recursively adding a new path after creating the parent directory.
...And 4 more matches
FileHandle API - Web APIs
api overview this api is based on the following interfaces: idbdatabase.mozcreatefilehandle (was called idbdatabase.mozcreatefilehandle.) idbmutablefile (was previously filehandle.) lockedfile filerequest it also has connections with the file api, especially the file and blob interfaces.
... basic operations create a filehandle because the intent is to allow the storage of files through indexeddb, creating a filehandle instance requires an indexeddb database.
... var idbreq = indexeddb.open("myfilestoragedatabase"); idbreq.onsuccess = function(){ var db = this.result; var buildhandle = db.mozcreatefilehandle("test.txt", "plain/text"); buildhandle.onsuccess = function(){ var myfilehandle = this.result; console.log('handle', myfilehandle); }; }; mozcreatefilehandle() takes two arguments: a name and an optional type.
...And 4 more matches
Working with the History API - Web APIs
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.
... state object the state object is a javascript object which is associated with the new history entry created by pushstate().
... in a sense, calling pushstate() is similar to setting window.location = "#foo", in that both will also create and activate another history entry associated with the current document.
...And 4 more matches
IDBDatabaseSync - Web APIs
method overview idbobjectstoresync createobjectstore (in domstring name, in domstring keypath, in optional boolean autoincrement) raises (idbdatabaseexception); idbobjectstoresync openobjectstore (in domstring name, in optional unsigned short mode) raises (idbdatabaseexception); void removeobjectstore (in domstring storename) raises (idbdatabaseexception); void setversion (in domstring version); idbtr...
...has the null value when the database is first created.
... methods createobjectstore() creates and returns a new object store with the given name in the connected database.
...And 4 more matches
RTCDtlsTransport - Web APIs
description allocation of dtls transports rtcdtlstransport objects are created when an app calls either setlocaldescription() or setremotedescription().
... the number of dtls transports created and how they're used depends on the bundling mode used when creating the rtcpeerconnection.
... for example, to create the connection using the highest level of bundling: const rtcconfig = { bundlepolicy: "max-bundle" }; const pc = new rtcpeerconnection(rtcconfig); bundling lets you use one rtcdtlstransport to carry the data for multiple higher-level transports, such as multiple rtcrtptransceivers.
...And 4 more matches
RTCPeerConnection.addTrack() - Web APIs
since streams are specific to each peer, specifying one or more streams means the other peer will create a corresponding stream (or streams) automatically on the other end of the connection, and will then automatically add the received track to those streams.
...otherwise, the first time ontrack is called, a new stream is created and attached to the video element, and then the track is added to the new stream.
... you could also just create a new stream for each track received: pc.ontrack = ev => { if (ev.streams && ev.streams[0]) { videoelem.srcobject = ev.streams[0]; } else { let inboundstream = new mediastream(ev.track); videoelem.srcobject = inboundstream; } } associating tracks with specific streams by specifying a stream and allowing rtcpeerconnection to create streams for you, the streams' track associations are automatically managed for you by the webrtc infrastructure.
...And 4 more matches
ReadableStream.getReader() - Web APIs
the getreader() method of the readablestream interface creates a reader and locks the stream to it.
... syntax var reader = readablestream.getreader({mode}); parameters {mode} optional an object containing a property mode, which takes as its value a domstring specifying the type of reader to create.
... values can be: "byob", which results in a readablestreambyobreader being created that can read readable byte streams (i.e.
...And 4 more matches
SVGTransformList - Web APIs
clear() svgtransform initialize(in svgtransform newitem) svgtransform getitem(in unsigned long index) svgtransform insertitembefore(in svgtransform newitem, in unsigned long index) svgtransform replaceitem(in svgtransform newitem, in unsigned long index) svgtransform removeitem(in unsigned long index) svgtransform appenditem(in svgtransform newitem) svgtransform createsvgtransformfrommatrix(in svgmatrix) svgtransform consolidate() properties readonly unsigned long numberofitems readonly unsigned long length normative document svg 1.1 (2nd edition) properties name type description numberofitems unsigned long the number of items in the list.
... createsvgtransformfrommatrix(in svgmatrix) svgtransform creates an svgtransform object which is initialized to transform of type svg_transform_matrix and whose values are the given matrix.
...the consolidation operation creates new svgtransform object as the first and only item in the list.
...And 4 more matches
WebGL2RenderingContext - Web APIs
buffers webgl2renderingcontext.bufferdata() initializes and creates the buffer object's data store.
... webgl2renderingcontext.renderbufferstoragemultisample() creates and initializes a renderbuffer object's data store and allows specifying the number of samples to be used.
... webgl2renderingcontext.createquery() creates a new webglquery object.
...And 4 more matches
WebGLRenderingContext - Web APIs
webglrenderingcontext.createbuffer() creates a webglbuffer object.
... webglrenderingcontext.createframebuffer() creates a webglframebuffer object.
... webglrenderingcontext.createrenderbuffer() creates a webglrenderbuffer object.
...And 4 more matches
Basic concepts behind Web Audio API - Web APIs
this modular design provides the flexibility to create complex audio functions with dynamic effects.
...a simple, typical workflow for web audio would look something like this: create the audio context.
... inside the context, create sources — such as <audio>, oscillator, or stream.
...And 4 more matches
Backwards Compatibility of Flexbox - CSS: Cascading Style Sheets
to create a flex container you would use display: box and there were a number of box-* properties, which did things that you will recognise from flexbox today.
... ultimately the specification was updated to define display: flex as the way to create a flex container.
... there are a few old articles in existence that refer to the older versions of flexbox, which are pretty easy to identify due to the change in the way that a flex container is created.
...And 4 more matches
Shapes from box values - CSS: Cascading Style Sheets
a straightforward way to create a shape is to use a value from the css box model.
... the box values allowable as a shape value are: content-box padding-box border-box margin-box the border-radius values are also supported, this means that you can have something in your page with a curved border, and your shape can follow the created shape.
...the border-radius property has been used to create a circle by setting border-radius: 50%.
...And 4 more matches
Creating and triggering events - Developer guides
this article demonstrates how to create and dispatch dom events.
... creating custom events events can be created with the event constructor as follows: const event = new event('build'); // listen for the event.
... for example, the event could be created as follows: const event = new customevent('build', { detail: elem.dataset.time }); this will then allow you to access the additional data in the event listener: function eventhandler(e) { console.log('the time is: ' + e.detail); } the old-fashioned way the older approach to creating events uses apis inspired by java.
...And 4 more matches
<input type="time"> - HTML: Hypertext Markup Language
WebHTMLElementinputtime
<input> elements of type time create input fields designed to let the user easily enter a time (hours and minutes, and optionally seconds).
...be prepared for this situation to arise: const input = document.createelement('input'); input.type = 'time'; input.min = '23:00'; input.max = '01:00'; input.value = '23:59'; if (input.validity.valid && input.type === 'time') { // <input type=time> reversed range supported } else { // <input type=time> reversed range unsupported } making times required in addition, you can use the required attribute to make filling in the time mandatory.
...for example, the time picker on chrome for android looks like this: browsers that don't support time inputs gracefully degrade to a text input, but this creates problems both in terms of consistency of user interface (the presented control will be different), and data handling.
...And 4 more matches
HTTP Index - HTTP
WebHTTPIndex
this directive declares a white-list of trusted type policy names created with trustedtypes.createpolicy from trusted types api.
... 142 feature-policy: publickey-credentials the http feature-policy header publickey-credentials directive controls whether the current document is allowed to access web authentcation api, i.e, via navigator.credentials.create({publickey: ...,...}) and navigator.credentials.get({publickey: ...,...}).
...it only provides a meaning when served with a 3xx (redirection) or 201 (created) status response.
...And 4 more matches
Using Promises - JavaScript
since most people are consumers of already-created promises, this guide will explain consumption of returned promises before explaining how to create them.
... imagine a function, createaudiofileasync(), which asynchronously generates a sound file given a configuration record and two callback functions, one called if the audio file is successfully created, and the other called if an error occurs.
... here's some code that uses createaudiofileasync(): function successcallback(result) { console.log("audio file ready at url: " + result); } function failurecallback(error) { console.error("error generating audio file: " + error); } createaudiofileasync(audiosettings, successcallback, failurecallback); modern functions return a promise that you can attach your callbacks to instead: if createaudiofileasync() were rewritten to return a promise, using it could be as simple as this: createaudiofileasync(audiosettings).then(successcallback, failurecallback); that's shorthand for: const promise = createaudiofileasync(audiosettings); promise.then(successcallback, failurecallback); we call this an asynchronous function call.
...And 4 more matches
Function() constructor - JavaScript
the function constructor creates a new function object.
... calling the constructor directly can create functions dynamically, but suffers from security and similar (but far less significant) performance issues to eval.
... however, unlike eval, the function constructor creates functions which execute in the global scope only.
...And 4 more matches
Function - JavaScript
constructor function() creates a new function object.
... calling the constructor directly can create functions dynamically but suffers from security and similar (but far less significant) performance issues to eval.
... however, unlike eval, the function constructor creates functions that execute in the global scope only.
...And 4 more matches
Object.prototype.__proto__ - JavaScript
instead, create a new object with the desired [[prototype]] using object.create().
... the __proto__ property can also be used in an object literal definition to set the object [[prototype]] on creation, as an alternative to object.create().
...for objects created using an object literal, this value is object.prototype.
...And 4 more matches
Promise - JavaScript
description a promise is a proxy for a value not necessarily known when the promise is created.
...if you are looking to lazily evaluate an expression, consider the arrow function with no arguments: f = () => expression to create the lazily-evaluated expression, and f() to evaluate.
...any termination other than a throw creates a "resolved" state, while terminating with a throw creates a "rejected" state.
...And 4 more matches
Symbol - JavaScript
description to create a new primitive symbol, you write symbol() with an optional string as its description: let sym1 = symbol() let sym2 = symbol('foo') let sym3 = symbol('foo') the above code creates three new symbols.
...it creates a new symbol each time: symbol('foo') === symbol('foo') // false the following syntax with the new operator will throw a typeerror: let sym = new symbol() // typeerror this prevents authors from creating an explicit symbol wrapper object instead of a new symbol value and might be surprising as creating explicit wrapper objects around primitive data types is generally possible (for example, new boolean, new string and new number).
... if you really want to create a symbol wrapper object, you can use the object() function: let sym = symbol('foo') typeof sym // "symbol" let symobj = object(sym) typeof symobj // "object" shared symbols in the global symbol registry the above syntax using the symbol() function will not create a global symbol that is available in your whole codebase.
...And 4 more matches
Fills and Strokes - SVG: Scalable Vector Graphics
miter extends the line slightly beyond its normal width to create a square corner where only one angle is used.
... round creates a rounded line segment.
... bevel creates a new angle to aid in the transition between the two segments.
...And 4 more matches
Web Components
web components is a suite of different technologies allowing you to create reusable custom elements — with their functionality encapsulated away from the rest of your code — and utilize them in your web apps.
... web components aims to solve such problems — it consists of three main technologies, which can be used together to create versatile custom elements with encapsulated functionality that can be reused wherever you like without fear of code collisions.
... the basic approach for implementing a web component generally looks something like this: create a class in which you specify your web component functionality, using the ecmascript 2015 class syntax (see classes for more information).
...And 4 more matches
Modules - Archive of obsolete content
we show how to create your own custom loaders, using the loader constructor provided by the sdk.
...like any other custom loader, cuddlefish is created using the loader constructor.
... in the final section, we will take a look at some of the options passed by the sdk to the loader constructor to create the cuddlefish loader.
...And 3 more matches
page-mod - Archive of obsolete content
attachto controls whether to attach scripts to tabs that were already open when the page-mod was created, and whether to attach scripts to iframes as well as the topmost document.
...note that this is a very naive implementation, created only for demonstration purposes, and will not work properly in many real-world cases.
... the following add-on creates a button which, when clicked, highlights all the div elements in the document loaded into the active tab: require("sdk/ui/button/action").actionbutton({ id: "highlight-divs", label: "highlight divs", icon: "./icon-16.png", onclick: function() { require("sdk/tabs").activetab.attach({ contentscript: 'var divs = document.getelementsbytagname("div");' + 'for (var i...
...And 3 more matches
cfx - Archive of obsolete content
there are four supported cfx commands: cfx init create a skeleton add-on as a starting point for your own add-on.
... cfx init create a new directory called "my-addon", change into it, and run cfx init.
... this command will create an skeleton add-on, as a starting point for your own add-on development, with the following file structure: my-addon data docs main.md lib main.js package.json readme.md tests test-main.js cfx run this command is used to run the add-on.
...And 3 more matches
Creating annotations - Archive of obsolete content
we'll use two objects to create annotations: a page-mod to find page elements that the user can annotate, and a panel for the user to enter the annotation text itself.
... 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); }); ...
...next we will create the editor panel, which enables the user to enter an annotation associated with the selected element.
...And 3 more matches
Creating Event Targets - Archive of obsolete content
in this tutorial we'll create part of a module to access the browser's places api.
... create a new directory called "bookmarks", navigate to it, and run jpm init, accepting all the defaults.
... create a new file in "lib" called "bookmarks.js", and add the following code: var { emit, on, once, off } = require("sdk/event/core"); var {cc, ci} = require("chrome"); var { xpcomutils }= require("resource://gre/modules/xpcomutils.jsm"); var bookmarkservice = cc["@mozilla.org/browser/nav-bookmarks-service;1"] .getservice(ci.nsinavbookmarksservice); var bookmarkobserver = { ...
...And 3 more matches
Getting started (cfx) - Archive of obsolete content
see: getting started with jpm cfx to jpm prerequisites to create add-ons for firefox using the sdk, you'll first need to follow the instructions to install and activate the sdk.
... initializing an empty add-on in the command prompt, create a new directory.
... the directory doesn't have to be under the sdk root: you can create it anywhere you like.
...And 3 more matches
Forms related code snippets - Archive of obsolete content
|*| http://www.gnu.org/licenses/gpl-3.0-standalone.html |*| \*/ (function () { function datepicker (otarget) { const otable = document.createelement("table"), ohrow = document.createelement("tr"), othead = document.createelement("thead"), ocapt = document.createelement("caption"), odecryear = document.createelement("span"), oincryear = document.createelement("span"), odecrmonth = document.createelement("span"), oincrmonth = document.createelement("span"); var nid = ainstances.length, oth; this.target ...
...= otarget; this.display = document.createelement("span"); this.current = new date(); this.container = otable; this.display.classname = sprefs + "-current-month"; this.id = nid; otable.classname = sprefs + "-calendar"; otable.id = sprefs + "-cal-" + nid; odecryear.classname = sprefs + "-decrease-year"; odecrmonth.classname = sprefs + "-decrease-month"; oincrmonth.classname = sprefs + "-increase-month"; oincryear.classname = sprefs + "-increase-year"; odecryear.innerhtml = "\u00ab"; /* &laquo; */ odecrmonth.innerhtml = "\u003c"; /* &lt; */ oincrmonth.innerhtml = "\u003e"; /* &gt; */ oincryear.innerhtml = "\u00bb"; /* &raquo; */ odecryear.id = sprefs + "-decr-year-" + nid; odecrmonth.id = sprefs + "-decr-month-" + nid; oincrmon...
...th.id = sprefs + "-incr-month-" + nid; oincryear.id = sprefs + "-incr-year-" + nid; odecryear.onmousedown = oincryear.onmousedown = odecrmonth.onmousedown = oincrmonth.onmousedown = onheadclick; for (var nthid = 0; nthid < 7; nthid++) { oth = document.createelement("th"); oth.innerhtml = sdays[nthid]; ohrow.appendchild(oth); } othead.appendchild(ohrow); ocapt.appendchild(odecryear); ocapt.appendchild(odecrmonth); ocapt.appendchild(oincryear); ocapt.appendchild(oincrmonth); ocapt.appendchild(this.display); this.container.appendchild(ocapt); this.container.appendchild(othead); this.current.setdate(1); this.writedays(); otarget.onclick = function () { if (otable.parentnode) { otable.parentnode.removechild(otable); r...
...And 3 more matches
Rosetta - Archive of obsolete content
|*| http://www.gnu.org/licenses/gpl-3.0.html |*| |*| syntax: |*| |*| rosetta.appendcompiler([ "text/x-csrc", "text/x-c" ], yourcompiler); |*| \*/ var rosetta = new (function () { function createscript (oscript, oxhr200) { var smimetype = oscript.getattribute("type").tolowercase(), obaton = document.createcomment(" the previous code has been automatically translated from \"" + smimetype + "\" to \"text/ecmascript\".
... "); if (!odicts.hasownproperty(smimetype)) { alert("rosetta.translatescript() \u2013 unknown mime-type \"" + smimetype + "\": script ignored."); return; } var ocompiled = document.createelement("script"); oscript.parentnode.insertbefore(obaton, oscript); oscript.parentnode.removechild(oscript); for (var aattrs = oscript.attributes, nattr = 0; nattr < aattrs.length; nattr++) { ocompiled.setattribute(aattrs[nattr].name, aattrs[nattr].value); } ocompiled.type = "text\/ecmascript"; if (oxhr200) { ocompiled.src = "data:text\/javascript," + encodeuricomponent(odicts[smimetype](oxhr200.responsetext)); } ocompiled.text = oxhr200 ?
... "" : odicts[smimetype](oscript.text); obaton.parentnode.insertbefore(ocompiled, obaton); } function reqerror (oerror) { throw new urierror("the script " + oerror.target.src + " is not accessible."); } function reqsuccess () { createscript(this.refscript, this); } function getsource (oscript) { var oreq = new xmlhttprequest(); oreq.onload = reqsuccess; oreq.onerror = reqerror; oreq.refscript = oscript; oreq.open("get", oscript.src, true); oreq.send(null); } function parsescript (oscript) { if (oscript.hasattribute("type") && !rignoremimes.test(oscript.getattribute("type").tolowercase())) { oscript.hasattribute("src") ?
...And 3 more matches
Jetpack Processes - Archive of obsolete content
jetpack processes are created by components that implement the nsijetpackservice interface, and their parent chrome process communicates with them via the nsijetpack interface.
...createhandle() similar to nsijetpack.createhandle(), this function creates a new handle and returns it.
... createsandbox() this creates a new javascript sandbox and returns its global scope.
...And 3 more matches
Handling Preferences - Archive of obsolete content
adding preferences to an extension extensions can read and write firefox preferences and, most importantly, create and manage their own.
... to add preferences to your extension you should first create a js preferences file that describes the preferences and their default values, although setting defaults is not required.
... the preferences file you need to create should be defaults/preferences/yourextensionname.js, under your extension root.
...And 3 more matches
Setting Up a Development Environment - Archive of obsolete content
or you can create an equivalent system using batch, ant or whatever you prefer.
...this is where all the resulting build files will be created, and where you'll find the extension xpi file once you get it to build.
...with that, you should now have a very easy way to build your xpi, by just double clicking on the created commands.
...And 3 more matches
XPCOM Objects - Archive of obsolete content
the fact that it allows to easily create os-independent applications is a big selling point for xulrunner.
...the method you call on cc["some-string"] should either be getservice or createinstance, depending on what you're asking for.
...the getservice and createinstance methods allow you to get the component already set to an interface.
...And 3 more matches
Block and Line Layout Cheat Sheet - Archive of obsolete content
ns_frame_first_reflow this flag is set on a newly created frame, and later cleared by the frame's reflow() method when the frame has had its initial reflow.
... ns_block_space_mgr this indicates that a block frame should create its own space manager.
...this is set by default for document frames, area frames, table cell inner frames, absolutely positioned wrapper frames, and floated frames when the frame is created.
...And 3 more matches
Style System Overview - Archive of obsolete content
detail: !important declarations cause an extra rule object cssimportantrule to be created since they are in a separate part of the cascade other nsistylerule implementations nshtmlmappedattributes represents stylistic html attributes turned into a style rule (one instance per unique set of attributes) bodyrule handles marginwidth/marginheight mixes on body and on frame.
... we create one style context per frame, since frames point to style contexts rather than the other way around.
... managing style contexts style contexts must (in most cases) be created before frames are constructed, to determine what frame to create.
...And 3 more matches
Introducing the Audio API extension - Archive of obsolete content
this enables users to visualize audio data, to process this audio data and to create new audio data.
... " " + framebuffer[1]; raw.innerhtml = text; } var raw = document.getelementbyid('raw'); var audio = document.getelementbyid('audio-element'); audio.addeventlistener('mozaudioavailable', audioavailable, false); audio.addeventlistener('loadedmetadata', loadedmetadata, false); </script> </body> </html> creating an audio stream it is also possible to create and setup an <audio> element for raw writing from script (i.e., without a src attribute).
...users must create an audio object and then use the mozsetup() function to specify the number of channels and the frequency (in hz).
...And 3 more matches
Building accessible custom components in XUL - Archive of obsolete content
finally, if the user hits tab while editing, we treat this as acceptance and recreate the label with the new value, then let firefox manage changing focus to the spreadsheet's next sibling.
...note that when we recreate the label element after editing, we need to explicitly restore the role attribute of the label, so that assistive technologies will continue to treat it as a cell within the spreadsheet.
... <code> const xul_ns = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"; const x2_ns ="http://www.w3.org/tr/xhtml2" function start_edit(label) { var value = label.value; settimeout(function(){ var textbox = document.createelementns(xul_ns, "textbox"); label.parentnode.replacechild(textbox, label); textbox.value = value; textbox.origvalue = value; textbox.flex = 1; textbox.focus(); textbox.select(); textbox.addeventlistener("blur", editable_cell_blur, true); textbox.addeventlistener("keypress", editable_cell_keypress, true); }, 0); } function done_edit(textbox, keepvalue) { var value = textbox.value; var label = document.createelementns(xul_ns, "label"); label.setattributens(x2_ns, "role", "wairole:gridcell"); textbox.parentnode.replacechild(l...
...And 3 more matches
Dynamically modifying XUL-based user interface - Archive of obsolete content
there are also dom methods that create, move, or delete elements from a document.
...examples: using dom methods this section demonstrates the use of appendchild(), createelement(), insertbefore(), and removechild() dom methods.
...it uses document.createelementns() method to create the items, and insertbefore() with appendchild() to insert the created xml elements within the document.
...And 3 more matches
Static Content - Archive of obsolete content
one interesting thing about this example is that only one menupopup will be created, even though there are two in the code, one outside the template and another one inside the action body.
...what's going on here is that the xul parser first creates the outer menulist element.
... the static content outside the template will also be created.
...And 3 more matches
Adding Methods to XBL-defined Elements - Archive of obsolete content
methods are only available to call after the page is rendered, which may cause problems if using createelement.
... for example, the following code will probably fail: var element = document.createelement("my_element"); element.getmaximum() // this will fail by the way, it is safe to call methods from the constructor, other methods on the object and event handlers.
...these elements are created anonymously and are not accessible from the regular dom functions.
...And 3 more matches
Anonymous Content - Archive of obsolete content
this inner content is created anonymously and cannot be seen using the dom.
... override the bound element the anonymous content is created automatically whenever a binding is attached to an element.
...for example, a simplified version of an editable menulist element, might be created as follows: xul: <menu class="dropbox"> <menupopup> <menuitem label="1000"/> <menuitem label="2000"/> </menupopup> </menu> css: menu.dropbox { -moz-binding: url('chrome://example/skin/example.xml#dropbox'); } xbl: <binding id="dropbox"> <content> <children/> <xul:textbox flex="1"/> <xul:button src="chrome://global/skin/images/dropbox.jpg"/> </content> </bind...
...And 3 more matches
Creating an Installer - Archive of obsolete content
create a web page from which the user can download the software to be installed.
... let's create an example install trigger.
... next, we create an array xpi which will hold the name (calendar) and url (calendar.xpi) of the installer.
...And 3 more matches
Input Controls - Archive of obsolete content
without any attributes, the textbox element creates a box in which the user can enter text.
... textbox.type you can set this attribute to the special value password to create a textbox that hides what it types.
... note that while in html, several different kinds of fields can be created with the input element, in xul there are separate elements for each type.
...And 3 more matches
Popup Menus - Archive of obsolete content
first, an example: <popupset> <menupopup id="clipmenu"> <menuitem label="cut"/> <menuitem label="copy"/> <menuitem label="paste"/> </menupopup> </popupset> as can be seen here, a simple popup menu with three commands on it has been created.
... associating a popup with an element now that we've created the popup, it's time to make the popup appear.
...the attribute you add depends on which type of popup you want to create.
...And 3 more matches
Stacks and Decks - Archive of obsolete content
the box tag creates the simplest box with no special properties.
...a scroll bar is just a special type of box that creates its own elements if you don't provide them.
...for example, a progress bar might be created using a bar and a label overlaid on top of it.
...And 3 more matches
listbox - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] this element is used to create a list of items where one or more of the items may be selected.
...if you wish to create a list with variable height rows, or with non-text content, you should instead use the richlistbox element.
...stcol/> <listcol flex="1"/> </listcols> </listbox> var thelist = document.getelementbyid('thelist'); gems = [ {gem: "ruby", price: "$3,500 - $4,600"}, {gem: "emerald", price: "$700 - 4,250"}, {gem: "blue sapphire", price: "$3,400 - $4,500"}, {gem: "diamond", price: "$5,600 - $16,000"} ]; for (var i = 0; i < gems.length; i++) { var row = document.createelement('listitem'); var cell = document.createelement('listcell'); cell.setattribute('label', gems[i].gem); row.appendchild(cell); cell = document.createelement('listcell'); cell.setattribute('label', gems[i].price ); row.appendchild(cell); thelist.appendchild(row); } attributes disabled type: boolean indicates whether the element is disabled or not.
...And 3 more matches
XULRunner tips - Archive of obsolete content
when using xulrunner 1.9 or greater, you can create your own alias in your chrome manifest add a "skin" line: skin communicator classic/1.0 skin/communicator/ add a skin folder named "communicator" and add a single css file named "communicator.css" with this content: @import url("chrome://global/skin"); dom inspector to add dom inspector 2.0.* to your xulrunner 1.9.0.* application follow these steps: download th...
...h dom inspector in your application, you need to open its main window, with a command like this: window.open("chrome://inspector/content/inspector.xul", "", "chrome"); alternatively, the dom inspector may also be added as an extension: (if you already have inspector installed for another application you can skip to the next step) follow the instructions above through "unzip the package." create a file in the extensions directory of your application with the same name as the dom inspector id (inspector@mozilla.org) containing one line of text -- the exact path to the root directory of dom inspector (where the install.rdf is) like this one: /home/username/.mozilla/firefox/numbersandletters/extensions/inspector@mozilla.org/ now create a javascript file with the following code and incl...
... var windowds = components.classes["@mozilla.org/rdf/datasource;1?name=window-mediator"] .getservice(components.interfaces.nsiwindowdatasource); var tmpnamespace = {}; var sl = components.classes["@mozilla.org/moz/jssubscript-loader;1"] .createinstance(components.interfaces.mozijssubscriptloader); sl.loadsubscript("chrome://inspector/content/hooks.js", tmpnamespace); tmpnamespace.inspectdomdocument(document); } now create a hook in your application window to start dom inspector, like this one: <button label="start inpector" oncommand="startdomi()"/> start your application and dom inspector will be installed.
...And 3 more matches
calICalendarViewController - Archive of obsolete content
summary a calicalendarviewcontroller provides a way for a calicalendarview to create, modify, and delete items.
... interface code [scriptable, uuid(1f783898-f4c2-4b2d-972e-360e0de38237)] interface calicalendarviewcontroller : nsisupports { void createnewevent (in calicalendar acalendar, in calidatetime astarttime, in calidatetime aendtime); void modifyoccurrence (in caliitemoccurrence aoccurrence, in calidatetime anewstarttime, in calidatetime anewendtime); void deleteoccurrence (in caliitemoccurrence aoccurrence); }; methods createnewevent void createnewevent (in calicalendar acalendar, ...
... in calidatetime astarttime, in calidatetime aendtime); the createnewevent method is used for creating a new calievent in the calicalendar specified by the acalendar parameter.
...And 3 more matches
Table Reflow Internals - Archive of obsolete content
if the page is incomplete then the page sequence creates a continuation for the page and sets it as the page's next sibling (it is also the page's nextinflow).
... intro to paginated reflow if the reflowee is incomplete, the reflower has the responsiblity to: create a continuation for the reflowee ensure that the continuation gets put in the frame hierarchy at the right place and gets reflowed at the right time.
...if it is incomplete, the block will create a continuation for the outer table (which also creates a continuation for the table).
...And 3 more matches
Browser Detection and Cross Browser Support - Archive of obsolete content
the easiest way to support gecko is to create content which follows web standards.
...due to a lack of communication and understanding, many sites have created inappropriate detection strategies based upon the netscape 6 user agent string.
...if your pages make use of advanced javascript which manipulates or creates new content using the w3c dom core, then opera 5 and 6 should be considered downlevel as well due to their limited support for the w3c dom.
...And 3 more matches
Old Proxy API - Archive of obsolete content
proxy factory the object or method that creates intercessive proxies.
...there are two kinds of proxies: object proxies var proxy = proxy.create(handler, proto); and function proxies : var proxy = proxy.createfunction(handler, calltrap, constructtrap); where: proto is an optional object representing the proxy’s prototype (defaults to null if none is provided).
... var p = proxy.create({get: function(receiver, name) { print(receiver); // looks for receiver's tostring method.
...And 3 more matches
Building up a basic demo with Three.js - Game development
create a directory to store your experiments in.
...let's create it, by adding the following line below our previous lines: var scene = new three.scene(); later, we will be using the .add() method, to add objects to this scene.
...to speed up development, three.js provides a bunch of predefined primitives, which you can use to create shapes instantly in a single line of code.
...And 3 more matches
Audio for Web games - Game development
var myaudio = document.createelement("audio"); myaudio.src = "mysprite.mp3"; myaudio.play(); myaudio.pause(); you'll need to sample the current time to know when to stop.
...the web audio api contains the notion of an internal clock that starts ticking the moment you create an audio context.
... let's create our audio context: // for cross browser compatibility const audiocontext = window.audiocontext || window.webkitaudiocontext; const audioctx = new audiocontext(); now let's select all the <li> elements; later we can harness these elements to give us access to the track file path and each individual play button.
...And 3 more matches
Desktop gamepad controls - Game development
first, we need an event listener to listen for the connection of the new device: window.addeventlistener("gamepadconnected", gamepadhandler); it's executed once, so we can create some variables we will need later on for storing the controller info and the pressed buttons: var controller = {}; var buttonspressed = []; function gamepadhandler(e) { controller = e.gamepad; output.innerhtml = "gamepad: " + controller.id; } the second line in the gamepadhandler function shows up on the screen when the device is connected: we can also show the id of the device — i...
... you could also create a helper function that would assign proper names to the listed buttons, so for example istead of checking out if gamepadbuttonpressedhandler(3) is pressed, you could do a more descriptive check: gamepadbuttonpressedhandler('dpad-right').
... phaser approach let's move on to the final gamepad api implementation in the captain rogers: battle at andromeda game we created with phaser.
...And 3 more matches
Build the brick field - Game development
let's explore how to create a group of bricks and print them on screen using a loop.
... defining new variables first, let's define the needed variables — add the following below your previous variable definitions: var bricks; var newbrick; var brickinfo; the bricks variable will be used to create a group, newbrick will be a new object added to the group on every iteration of the loop, and brickinfo will store all the data we need.
...add a call to initbricks at the end of the create() function: function create(){ // ...
...And 3 more matches
Test your skills: Grid Layout - Learn web development
grid layout one in this task you should create a grid into which the four child elements will auto-place.
... try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: additional questions: can you now cause the first item to display on top without changing the order of items in the source?
...And 3 more matches
Introduction to CSS layout - Learn web development
for many of the elements on your page the normal flow will create exactly the layout you need, however for more complex layouts you will need to alter this default behavior using some of the tools available to you in css.
...if you create a link around some text inside a paragraph, that link remains inline with the rest of the text, and doesn’t break onto a new line.
...i don’t need to put any rules on the child elements; they are automatically placed into the cells our grid has created.
...And 3 more matches
Supporting older browsers - Learn web development
couple this information with the knowledge that browsers ignore css that they don’t understand, and you have a way to create simple layouts using the legacy techniques we have already covered, which are then overwritten by your grid layout in modern browsers that understand it.
...you can choose the one that makes the most sense for the layout pattern you need to create.
... display: inline-block this method can be used to create column layouts, if an item has display: inline-block set but then becomes a flex or grid item, the inline-block behaviour is ignored.
...And 3 more matches
Advanced form styling - Learn web development
the appearance property was created as a way to control what os- or system-level styling was applied to web form controls.
... you can see the live result: we've also created a couple of other examples to give you more ideas: styled radio buttons: custom radio button styling.
...to fix this in our example we first used our old friend appearance: none to get rid of the icon altogether: select { -webkit-appearance: none; appearance: none; } we then created our own icon using generated content.
...And 3 more matches
JavaScript basics - Learn web development
with more experience, you'll be able to create games, animated 2d and 3d graphics, comprehensive database-driven apps, and much more!
... go to your test site and create a new folder named scripts.
... within the scripts folder, create a new file called main.js, and save it.
...And 3 more matches
Introducing asynchronous JavaScript - Learn web development
let's look at a simple example (see it live here, and see the source): const btn = document.queryselector('button'); btn.addeventlistener('click', () => { alert('you clicked me!'); let pelem = document.createelement('p'); pelem.textcontent = 'this is a newly-added paragraph.'; document.body.appendchild(pelem); }); in this block, the lines are executed one after the other: we grab a reference to a <button> element that is already available in the dom.
... once the alert is dismissed, we create a <p> element.
... an example of an async callback is the second parameter of the addeventlistener() method (as we saw in action above): btn.addeventlistener('click', () => { alert('you clicked me!'); let pelem = document.createelement('p'); pelem.textcontent = 'this is a newly-added paragraph.'; document.body.appendchild(pelem); }); the first parameter is the type of event to be listened for, and the second parameter is a callback function that is invoked when the event is fired.
...And 3 more matches
Client-Server Overview - Learn web development
post: create a new resource (e.g.
... put: update an existing resource (or create a new one if it doesn't exist).
... after the coach submits the form with the team name and number of players, the sequence of operations is: the web browser creates an http get request to the server using the base url for the resource (/best) and encoding the team and player number either as url parameters (e.g.
...And 3 more matches
Getting started with Ember - Learn web development
previous overview: client-side javascript frameworks next in our first ember article we will look at how ember works and what it's useful for, install the ember toolchain locally, create a sample app, and then do some initial setup to get it ready for development.
... objective: to learn how to install ember, and create a starter app.
... now type the following into your terminal to install ember-cli: npm install -g ember-cli this tool provides the ember program in your terminal, which is used to create, build, develop, test, and scaffold your application (run ember --help for a full list of commands and their options).
...And 3 more matches
Dynamic behavior in Svelte: working with variables and props - Learn web development
we'll also create two variables to keep track of the total number of tasks and the completed tasks.
... create a <script> section at the top of src/components/todos.svelte and give it some content, as follows: <script> let todos = [ { id: 1, name: 'create a svelte starter app', completed: true }, { id: 2, name: 'create your first component', completed: true }, { id: 3, name: 'complete the rest of the tutorial', completed: false } ] let totaltodos = todos.length let completedtodos = todos.filter(todo => todo.completed).length </script> now let's do something with that information.
...update src/app.svelte as follows: <script> import todos from './components/todos.svelte' let todos = [ { id: 1, name: 'create a svelte starter app', completed: true }, { id: 2, name: 'create your first component', completed: true }, { id: 3, name: 'complete the rest of the tutorial', completed: false } ] </script> <todos todos={todos} /> when the attribute and the variable have the same name, svelte allows you to just specify the variable as a handy shortcut, so we can rewrite our last line like this.
...And 3 more matches
Implementing feature detection - Learn web development
give it the following contents: const conditional = document.queryselector('.conditional'); const testelem = document.createelement('div'); if (testelem.style.flex !== undefined && testelem.style.flexflow !== undefined) { conditional.setattribute('href', 'flex-layout.css'); } else { conditional.setattribute('href', 'float-layout.css'); } here we are grabbing a reference to the second <link> element, and creating a <div> element as part of our test.
...} property on element create an element in memory using document.createelement() and then check if a property exists on it.
... function supports_canvas() { return !!document.createelement('canvas').getcontext; } if(supports_canvas()) { ...
...And 3 more matches
Gecko info for Windows accessibility vendors
in total, gecko supports the following window classes: mozillauiwindowclass - root ui window, at the root of the window hierarchy mozillacontentwindowclass -- root document window mozillacontentframewindowclass - root of a subdocument created by a <frame> or <iframe> element mozillahiddenwindowclass - ignore these windows, they are used to help manage other windows mozillawindowclass - general filler window, a catch all starting in firefox 2, however, you should begin switching your code to use navrelation_embeds.
... going forward, this may be the only way to efficiently find the content area, as mozilla will begin to become a windowless application, with an exception for plugins which create their own window.
... once the new page is ready to be displayed and traversed via its iaccessible tree, the old content window is destroyed, and a new window is created.
...And 3 more matches
Command line options
-createprofile profile_name create a new profile in the default directory, but do not start the application.
... firefox -createprofile joeluser -createprofile "profile_name profile_dir" creates a new profile in the profile_dir directory, but do not start the application.
... firefox -createprofile "joeluser c:\internet\joelusers-moz-profile" note: profile_dir must not exist and you must not already have a profile called profile_name.
...And 3 more matches
HTML parser threading
script-created parsers (i.e.
... parsers created using document.open()) don't have an nshtml5streamparser instance.
...if the parser is not script-created, nshtml5parser::markasnotscriptcreated() is called to create an nshtml5streamparser for the nshtml5parser.
...And 3 more matches
HTTP Cache
//github.com/realityripple/uxp/blob/master/netwerk/base/public/nsiloadcontextinfo.idl it is a helper interface wrapping following four arguments into a single one: private-browsing boolean flag anonymous load boolean flag app id number (0 for no app) is-in-browser boolean flag helper functions to create nsiloadcontextinfo objects: c++ consumers: functions at loadcontextinfo.h exported header js consumers: resource://gre/modules/loadcontextinfo.jsm module methods two storage objects created with the same set of nsiloadcontextinfo arguments are identical, containing the same cache entries.
... two storage objects created with in any way different nsiloadcontextinfo arguments are strictly and completely distinct and cache entries in them do not overlap even when having the same uris.
... the writer then calls recreate on the cache entry.
...And 3 more matches
Extending a Protocol
now let's implement the method in ./dom/base/navigator.cpp - we add a little bit of error boilerplate stuff, as is customary: already_addrefed<promise> navigator::echo(const nsastring& astring, errorresult& arv) { if (!mwindow || !mwindow->getdocshell()) { arv.throw(ns_error_unexpected); return nullptr; } refptr<promise> echopromise = promise::create(mwindow->asglobal(), arv); if (ns_warn_if(arv.failed())) { return nullptr; } // message passing magic will happen here!
... defining echochild.h create ./dom/ipc/echochild.h, and define it as follows - the inline comments describe what's going on: #ifndef mozilla_dom_echochild_h #define mozilla_dom_echochild_h // we include the protocol, which is automatically generated for us.
... defining echoparent.h like before, create ./dom/ipc/echoparent.h, and code it as follows - the inline comments describe what's going on.
...And 3 more matches
Downloads.jsm
to use it, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/downloads.jsm"); method overview promise<download> createdownload(object aproperties); promise<void> fetch(asource, atarget, [optional] object aoptions); promise<downloadlist> getlist(atype); promise<downloadsummary> getsummary(atype); constants constant description public work on downloads that were not started from a private browsing window.
...example (using task.jsm): try { yield downloads.fetch(sourceuri, targetfile); } catch (ex if ex instanceof downloads.error && ex.becausetargetfailed) { console.log("unable to write to the target file, ignoring the error."); } methods createdownload() creates a new download object.
... promise<download> createdownload( object aproperties ); parameters aproperties provides the initial properties for the newly created download.
...And 3 more matches
FileUtils.jsm
ls.import("resource://gre/modules/fileutils.jsm"); the file constructor if you have a path to a file (or directory) you want to obtain an nsifile for, you can do so using the file constructor, like this: var f = new fileutils.file(mypath); method overview nsifile getfile(string key, array patharray, bool followlinks); nsifile getdir(string key, array patharray, bool shouldcreate, bool followlinks); nsifileoutputstream openfileoutputstream(nsifile file, int modeflags); nsifileoutputstream openatomicfileoutputstream(nsifile file, int modeflags); nsifileoutputstream opensafefileoutputstream(nsifile file, int modeflags); void closeatomicfileoutputstream(nsifileoutputstream stream); void closesafefileoutputstream(nsifileoutputstrea...
...m stream); constants constant value description mode_rdonly 0x01 corresponds to the pr_rdonly parameter to pr_open mode_wronly 0x02 corresponds to the pr_wronly parameter to pr_open mode_create 0x08 corresponds to the pr_create_file parameter to pr_open mode_append 0x10 corresponds to the pr_append parameter to pr_open mode_truncate 0x20 corresponds to the pr_truncate parameter to pr_open perms_file 0644 default permissions when creating files.
...the file is not created if it does not exist, however all required directories along the way are.
...And 3 more matches
XPCOMUtils.jsm
create an array of component constructors.
...if not // provided, the default factory is used, which returns // |(new mycomponent()).queryinterface(iid)| in its createinstance().
... create an array of component constructors you need to create an array that lists the constructors for each component.
...And 3 more matches
Application Translation with Mercurial
you can create translation patches, but creating language packs for the application, binary repacks of the application (changing the localization of the program), and compiling the application likely won't work.
...so let's go to c:\mozilla by typing cd /c/mozilla/ create a new directory for the source code: mkdir mozilla-aurora initialize the new directory as new repository: hg init mozilla-aurora go into the new directory: cd mozilla-aurora unpack the source code: hg unbundle /path/to/the/downloaded/mozilla-aurora.hg this can take some time, mostly depending on the performance of the hard drive.
...for a windows user, it looks like c:\users\myname , depending on your windows version: cd /c/users/myname now list all the files here: ls -a if there is no file called .hgrc , create it with > .hgrc this file stores your general mercurial settings (mercurial is the tool which manages the source code and its history of changes).
...And 3 more matches
Index
3 bootstrapping a new locale localization, mercurial, translate, bit bucket (see also https://developer.mozilla.org/en/create_a_new_localization) 4 encodings for localization files internationalization, localization when creating a localization for mozilla products, it’s important to be aware of the encoding of the files that you generate.
... 9 localization content best practices apps, extensions, internationalization, localization, mozilla, l10n, l12y this document provides best practices for developers to create localizable code, and describes how to avoid some localizability (l12y) common mistakes.
...the localizable data fields of an extension are: 23 localizing with koala this tutorial will guide you through making a couple of changes to firefox's user interface using koala, an add-on for komodo edit created to help localizing mozilla.
...And 3 more matches
Patching a Localization
start bash and do the following: create a clean directory for your work.
... for example, create a directory like localization-workdir (in this example it is located in your home directory): mkdir ~/localization-workdir navigate to the directory you just created.
... creating a l10n patch you've made your changes, now create your patch.
...And 3 more matches
Setting up the infrastructure
create a new branch for l10n (optional if starting a new project).
... create a locale directory in your website (usually something like docroot/locale).
... create en-us locale (locale/lc_messages/) in the locale folder.
...And 3 more matches
Mozilla Style System Documentation
(mozilla has a bunch of its pseudo-elements that are not in the css specification.) we also create style contexts for some things that are not css formatting objects: text nodes and placeholder frames.
... these three types of style contexts correspond to the three ways of creating a style context: nsiprescontext::resolvestylecontextfor, nsiprescontext::resolvepseudostylecontextfor, and.nsiprescontext::resolvestylecontextfornonelement there is also a fourth method, nsiprescontext::probepseudostylecontextfor, which creates a style context only if there are style rules that match the pseudo-element.
... this is useful for the pseudo-elements defined in the css specification (:before, :after, :first-line, :first-letter), but few of mozilla's custom pseudo-elements, many of which are hacks for further formatting objects that we create.
...And 3 more matches
PR_Open
also used to create a file.
... pr_create_file 0x08 if the file does not exist, the file is created.
... pr_excl 0x80 with pr_create_file, if the file does not exist, the file is created.
...And 3 more matches
PKCS11 FAQ
MozillaProjectsNSSPKCS11FAQ
if the token cannot do ckm_rsa_pkcs_gen_keypair, nss uses its software key generation code and writes the private and public keys into the token using c_createobject.
... the private key is created using c_generatekeypair or stored using c_createobject (depending on who generates the key).
... are persistent objects that are stored on the token, such as private keys and certificates, created by the pkcs #11 module?
...And 3 more matches
S/MIME functions
text_finishmultiple mxr 3.2 and later nss_cmsdigestcontext_finishsingle mxr 3.2 and later nss_cmsdigestcontext_startmultiple mxr 3.2 and later nss_cmsdigestcontext_startsingle mxr 3.2 and later nss_cmsdigestcontext_update mxr 3.2 and later nss_cmsdigesteddata_create mxr 3.2 and later nss_cmsdigesteddata_destroy mxr 3.2 and later nss_cmsdigesteddata_getcontentinfo mxr 3.2 and later nss_cmsderencode mxr 3.2 and later nss_cmsencoder_cancel mxr 3.2 and later nss_cmsencoder_finish mxr 3.2 and later ...
... nss_cmsencoder_start mxr 3.2 and later nss_cmsencoder_update mxr 3.2 and later nss_cmsencrypteddata_create mxr 3.2 and later nss_cmsencrypteddata_destroy mxr 3.2 and later nss_cmsencrypteddata_getcontentinfo mxr 3.2 and later nss_cmsenvelopeddata_addrecipient mxr 3.2 and later nss_cmsenvelopeddata_create mxr 3.2 and later nss_cmsenvelopeddata_destroy mxr 3.2 and later nss_cmsenvelopeddata_getcontentinfo mxr 3.2 and later nss_cmsmessage_contentlevel mxr 3.2 and later nss_cmsmessage_contentlevelcount mxr 3.2 a...
...nd later nss_cmsmessage_copy mxr 3.2 and later nss_cmsmessage_create mxr 3.2 and later nss_cmsmessage_createfromder mxr 3.2 and later nss_cmsmessage_destroy mxr 3.2 and later nss_cmsmessage_getcontent mxr 3.2 and later nss_cmsmessage_getcontentinfo mxr 3.2 and later nss_cmsmessage_isencrypted mxr 3.4.1 and later nss_cmsmessage_issigned mxr 3.4 and later nss_cmsrecipientinfo_create mxr 3.2 and later nss_cmsrecipientinfo_createfromder mxr 3.8 and later nss_cmsrecipientinfo_createnew mxr 3.8 and ...
...And 3 more matches
Utility functions
dsau_decodedersig mxr 3.2 and later dsau_decodedersigtolen mxr 3.9 and later dsau_encodedersig mxr 3.2 and later dsau_encodedersigwithlen mxr 3.9 and later hash_begin mxr 3.4 and later hash_clone mxr 3.10 and later hash_create mxr 3.4 and later hash_destroy mxr 3.4 and later hash_end mxr 3.4 and later hash_gethashobject mxr 3.2 and later hash_gethashobjectbyoidtag mxr 3.8 and later hash_gethashtypebyoidtag mxr 3.8 and later hash_gettype mxr 3...
...env mxr 3.2 and later nss_registershutdown mxr 3.11.1 and later nss_shutdown mxr 3.2 and later nss_unregistershutdown mxr 3.11.1 and later nss_versioncheck mxr 3.2 and later nssbase64_decodebuffer mxr 3.4 and later nssbase64decoder_create mxr 3.2 and later nssbase64decoder_destroy mxr 3.2 and later nssbase64decoder_update mxr 3.2 and later nssbase64_encodeitem mxr 3.4 and later nssbase64encoder_create mxr 3.2 and later nssbase64encoder_destroy mxr 3.2 and later nssb...
... mxr 3.2 and later secitem_freeitem mxr 3.2 and later secitem_itemsareequal mxr 3.8 and later secitem_zfreeitem mxr 3.2 and later seckey_copyencryptedprivatekeyinfo mxr 3.2 and later seckey_copyprivatekeyinfo mxr 3.2 and later seckey_creatersaprivatekey mxr 3.2 and later seckey_destroyencryptedprivatekeyinfo mxr 3.2 and later seckey_destroyprivatekeyinfo mxr 3.2 and later seckey_destroypublickey mxr 3.2 and later seckey_publickeystrength mxr 3.2 and later seckey_updatecertpqg mxr 3.2...
...And 3 more matches
SpiderMonkey Build Documentation
no configure: error: installation or configuration problem: c compiler cannot create executables." you can try configuring like so: cc=clang cxx=clang++ ../configure it is also possible that baldrdash may fail to compile with /usr/local/cellar/llvm/7.0.1/lib/clang/7.0.1/include/inttypes.h:30:15: fatal error: 'inttypes.h' file not found /usr/local/cellar/llvm/7.0.1/lib/clang/7.0.1/include/inttypes.h:30:15: fatal error: 'inttypes.h' file not found, err: true this is because...
...thus, in addition to following the steps above, you should also create a debug build using these steps: cd js/src # this name should end with "_dbg.obj" to make the version control system ignore it.
... for a list of other available build options, type (assuming the current working directory is one of the above-created build directories): /bin/sh ../configure.in --help generating a compilation database some tools (like ides, static analyzers and refactoring tools) consume a file called compile_commands.json which contains a description of all the pieces required to build a piece of software so that tools don't have to also understand a build system.
...And 3 more matches
JS_AliasElement
create an aliased index entry for an existing numeric property of a native object.
... syntax jsbool js_aliaselement(jscontext *cx, jsobject *obj, const char *name, jsint alias); name type description cx jscontext * the context in which to create the alias.
... obj jsobject * the object for which to create the alias.
...And 3 more matches
JS_NewExternalString
create a new jsstring whose characters are stored in external memory.
...ring * js_newexternalstring(jscontext *cx, const char16_t *chars, size_t length, const jsstringfinalizer *fin); jsstring * js_newexternalstringwithclosure(jscontext *cx, jschar *chars, size_t length, int type, void *closure); // obsolete since jsapi 13 name type description cx jscontext * the context in which to create the new string.
...this array is used as the character buffer of the jsstring to be created.
...And 3 more matches
JS_NewFunction
create a new javascript function that is implemented in c/c++ as a jsnative.
..., jsnative call, unsigned nargs, unsigned flags, js::handle<jsobject*> parent, const char *name); jsfunction * js_newfunctionbyid(jscontext *cx, jsnative call, unsigned nargs, unsigned flags, js::handle<jsobject*> parent, js::handle<jsid> id); // added in spidermonkey 17 name type description cx jscontext * the context in which to create the new function.
...added in spidermonkey 17 description js_newfunction creates a new javascript function implemented in c/c++.
...And 3 more matches
JS_NewGlobalObject
this article covers features introduced in spidermonkey 17 create a new javascript object for use as a global object.
... syntax jsobject * js_newglobalobject(jscontext *cx, const jsclass *clasp, jsprincipals *principals, js::onnewglobalhookoption hookoption, const js::compartmentoptions &options = js::compartmentoptions()); name type description cx jscontext * the context in which to create the new global object.
...added in spidermonkey 31 description js_newglobalobject creates a new global object based on the specified class.
...And 3 more matches
Redis Tips
in node, create client with explicit host and port like so: > var r = require('redis').createclient(6379, '127.0.0.1') commands are asynchronous.
... here's a stupid node script to show how this works: #!/usr/bin/env node var r = require('redis').createclient(); r.multi() .set("foo", 42) .set("bar", "ice cream") .set("baz", 6.28) .get("foo") .get("bar") .get("baz") .exec(function(err, resultlist) { console.log(json.stringify(resultlist, null, 2)); r.end(); // terminate the redis connection; node can quit }); when run, this prints: [ "ok", "ok", "ok", "42", "ice cream", "6.28" ] the result list includes one...
... for example, here's some node code: var redis = require("redis"), client = redis.createclient({ ...
...And 3 more matches
Setting up an update server
these changes will need to be made in order to use the locally built mar: put this line in the mozconfig file in root of the build directory (create it if it does not exist): ac_add_options --disable-verify-mar several files contain a line that must be uncommented.
...if you want it to be the same before and after updating, this step is unnecessary and you can use the same build that you used to create the installation.
... serving the update preparing the update files first, create the directory that updates will be served from and put the mar file in it.
...And 3 more matches
Manipulating bookmarks using Places
he bookmarks service as is the case with nearly all interfaces, before you can use the bookmarks service, you need to get access to it: var bmsvc = components.classes["@mozilla.org/browser/nav-bookmarks-service;1"] .getservice(components.interfaces.nsinavbookmarksservice); creating a bookmark folder creating a new bookmark folder is done using the nsinavbookmarksservice.createfolder() method.
... for example, to create a new folder in the bookmarks menu: var menufolder = bmsvc.bookmarksmenufolder; // bookmarks menu folder var newfolderid = bmsvc.createfolder(menufolder, "folder name here", bmsvc.default_index); this code locates the bookmarks menu's folder, then creates a new folder named "folder name here" in it.
... creating a new bookmark to create a new bookmark, use the nsinavbookmarksservice.insertbookmark() method.
...And 3 more matches
How to build an XPCOM component in JavaScript
here's the xpidl definition for our helloworld component: helloworld.idl #include "nsisupports.idl" [scriptable, uuid(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)] interface nsihelloworld : nsisupports { string hello(); }; note that you must generate a new uuid for each xpcom component that you create.
... note: (the -i flag is an uppercase i, not a lowercase l.) this will create the typelib file helloworld.xpt in the current working directory.
... for a new component in firefox/thunderbird/b2g if you are adding a new feature to applications in the mozilla-central repository, you can create a makefile listing the idl files and the build system will automatically generate the typelib.
...And 3 more matches
Preface
accordingly, the book is arranged so that you can follow along and create your own components or learn about different xpcom topics individually, as in a reference work.
...though you can create xpcom components in javascript and other languages, and though you might be able to follow along as a c programmer, the component implementation code is written in c++, and much of the discussion of how to make your codeinto an xpcom component starts from c++.
... create the generic module code for the component.
...And 3 more matches
Using XPCOM Components
scriptability, this ability to get and use xpcom components from javascript and other languages for which xpconnect bindings have been created, is a core feature of xpcom.
...it registers itself for use when the browser starts up, and provides a factory that creates an instance of it for use when the user or administrator clicks the weblock icon in the browser's user interface.
...in the following code fragment from the cookie manager dialog in mozilla, you can see a singleton of the cookiemanager component being created with the getservice() method and used to provide the functionality that lets users load and remove cookies from the user interface.
...And 3 more matches
How to build a binary XPCOM component using Visual Studio
recap: use the right gecko sdk for your xulrunner release use a microsoft compiler use pre-built glib-1.2.dll & libidl-0.6.dll libraries from wintools.zip download the sample project here is what the folder structure looks like: create a vc++ project visual studio project and file templates (or wizards) for creating xpcom modules and components do not currently exist.
...i am not defining xpcom_glue and i am linking against xpcomglue_s.lib create an xpcom component a full tutorial of xpcom is beyond the scope of this posting.
...the blank vc++ project has a bat file that will create the xpt and the h files.
...And 3 more matches
XPConnect wrappers
basic xpconnect objects xpcwrappednative these objects are created when any natively implemented xpcom object (that is, any object implemented in c++) needs to be reflected into javascript.
... they are implicitly created by xpconnect and you should not have to worry about how that happens.
...this means that whenever you pass your javascript object into a c++ function, we create one of these wrappers.
...And 3 more matches
Language bindings
e components object is actually a native instance of the nsixpccomponents interface which is reflected into javascript as a top level object using xpconnect.components.classescomponents.classes is a read-only object whose properties are classes indexed by contractid.components.classesbyidcomponents.classesbyid is a read-only object whose properties are classes indexed by cid.components.constructorcreates a javascript function which can be used to create or construct new instances of xpcom components.components.exceptioncomponents.exception is a javascript constructor to create nsixpcexception objects.
... these exception objects may be thrown when implementing xpcom interfaces in javascript, and they can provide better diagnostics in the error console if not caught than simply throwing an nsresult's value will.components.idcomponents.id is a constructor that creates native objects that conform to the nsijsid interface.components.interfacescomponents.interfaces is a read-only object whose properties are interfaces indexed by their names.components.interfacesbyidcomponents.interfacesbyid is a read-only array of classes indexed by iid.components.issuccesscodedetermines whether a given xpcom return code (that is, an nsresult value) indicates the success or failure of an operation, returning true or false respectively.components.lastresultcomponents.managercomponents.manager is a convenience reflecti...
...its interface is defined at js/xpconnect/idl/xpccomponents.idl.components.utils.cloneintothis function provides a safe way to take an object defined in a privileged scope and create a structured clone of it in a less-privileged scope.
...And 3 more matches
Observer Notifications
prepend "service," to the contract id in the category registration to be invoked via getservice() instead of createinstance().
... topic subject data description chrome-document-global-created nsidomwindow null sent immediately after a chrome document window has been set up, but before any script code has been executed.
... content-document-global-created nsidomwindow origin sent immediately after a web content document window has been set up, but before any script code has been executed.
...And 3 more matches
nsIDOMWindowUtils
enativemenuitemat(in astring indexstring); void clearmozafterpaintevents(); pruint32 comparecanvases(in nsidomhtmlcanvaselement acanvas1, in nsidomhtmlcanvaselement acanvas2, out unsigned long amaxdifference); double computeanimationdistance(in nsidomelement element, in astring property, in astring value1, in astring value2); nsicompositionstringsynthesizer createcompositionstringsynthesizer(); obsolete since gecko 38.0 void disablenontestmouseevents(in boolean adisable); boolean dispatchdomeventviapresshell(in nsidomnode atarget, in nsidomevent aevent, in boolean atrusted); nsidomelement elementfrompoint(in float ax, in float ay, in boolean aignorerootscrollframe, in boolean aflushlayout); void entermodalstate(); ...
... double computeanimationdistance( in nsidomelement element, in astring property, in astring value1, in astring value2 ); parameters element property value1 value2 return value createcompositionstringsynthesizer() obsolete since gecko 38 method for creating an instance which has nsicompositionstringsynthesizer.
... nsicompositionstringsynthesizer createcompositionstringsynthesizer(); return value an instance of nsicompositionstringsynthesizer.
...And 3 more matches
nsIIOService
newchannelfromuri() obsolete since gecko 48 creates a channel for a given uri.
... newchannelfromuri2() creates a channel for a given uri.
... newchannelfromuriwithloadinfo() creates a channel for a given uri.
...And 3 more matches
nsISHEntry
docshell/shistory/public/nsishentry.idlscriptable each document or subframe in session history will have a nsishentry associated with it which will hold all information required to recreate the document from history.
...to create an instance, use: var shentry = components.classes["@mozilla.org/browser/session-history-entry;1"] .createinstance(components.interfaces.nsishentry); method overview void addchildshell(in nsidocshelltreeitem shell); nsidocshelltreeitem childshellat(in long index); void clearchildshells(); nsishentry clone(); void create(in nsiuri uri, in astring title, in nsiinputstream inputstream, in nsilayouthistorystate layouthistorystate, in nsisupports cachekey, in acstring contenttype, in nsisupports owner, in unsigned long long docshellid, in boolean dynamiccreation); native code only!
...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().
...And 3 more matches
nsISocketTransportService
to create an instance, use: var sockettransportservice = components.classes["@mozilla.org/network/socket-transport-service;1"] .getservice(components.interfaces.nsisockettransportservice); method overview void attachsocket(in prfiledescptr afd, in nsasockethandlerptr ahandler); native code only!
... nsisockettransport createtransport(in array<acstring> asockettypes, in autf8string ahost, in long aport, in nsiproxyinfo aproxyinfo); void init(); obsolete since gecko 1.8 void notifywhencanattachsocket(in nsirunnable aevent); native code only!
... createtransport() creates a transport for a specified host and port.
...And 3 more matches
nsIThreadPool
when you send events to the thread pool, the pool creates a new thread to process the event, up to the number of threads specified by the threadlimit attribute.
... listener nsithreadpoollistener an optional listener that will be notified when a thread is created or destroyed in the course of the thread pool's operation.
... a listener will only receive notifications about threads created after the listener is set so it is recommended that the consumer set the listener before dispatching the first event.
...And 3 more matches
nsIToolkitProfileService
to access the service, you can use the following code: var toolkitprofileservice = components.classes["@mozilla.org/toolkit/profile-service;1"] .createinstance(components.interfaces.nsitoolkitprofileservice); prior to gecko 1.9.1 only the built-in profile manager was able to access the toolkit profile service.
... method overview nsitoolkitprofile createprofile(in nsilocalfile arootdir, in autf8string aname); void flush(); nsitoolkitprofile getprofilebyname(in autf8string aname); nsiprofilelock lockprofilepath(in nsilocalfile adirectory, in nsilocalfile atempdirectory); attributes attribute type description profilecount unsigned long the number of user profiles currently in existence.
... startoffline boolean startwithlastprofile boolean methods createprofile() creates a new profile.
...And 3 more matches
nsIWinTaskbar
to create an instance, use: var wintaskbar = components.classes["@mozilla.org/windows-taskbar;1"] .getservice(components.interfaces.nsiwintaskbar); method overview nsijumplistbuilder createjumplistbuilder(); nsitaskbartabpreview createtaskbartabpreview(in nsidocshell shell, in nsitaskbarpreviewcontroller controller); nsitaskbarprogress gettaskbarprogress(in nsidocshell shell); n...
...methods createjumplistbuilder() retrieve a taskbar jump list builder.
...nsijumplistbuilder createjumplistbuilder(); parameters none.
...And 3 more matches
nsIXULWindow
inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) an nsixulwindow is created as part of the creation of a top-level chrome window.
... void assumechromeflagsarefrozen(); void center(in nsixulwindow arelative, in boolean ascreen, in boolean aalert); nsixulwindow createnewwindow(in print32 achromeflags, in nsiappshell aappshell); nsidocshelltreeitem getcontentshellbyid(in wstring id); void removechildwindow(in nsixulwindow achild); void showmodal(); attributes attribute type description chromeflags pruint32 chromeflags are from nsiwebbrowserchrome.
... createnewwindow() create a new window.
...And 3 more matches
Xray vision
xray vision helps javascript running in a privileged security context safely access objects created by less privileged code, by showing the caller only the native version of the objects.
... as well as these two levels of privilege, chrome code can create sandboxes.
... the security machinery in gecko ensures that there's asymmetric access between code at different privilege levels: so for example, content code can't access objects created by chrome code, but chrome code can access objects created by content.
...And 3 more matches
nsIMsgCloudFileProvider
init(in string aaccountkey); void uploadfile(in nsilocalfile afile, in nsirequestobserver acallback); acstring urlforfile(in nsilocalfile afile); void cancelfileupload(in nsilocalfile afile); void refreshuserinfo(in boolean awithui, in nsirequestobserver acallback); void deletefile(in nsilocalfile afile, in nsirequestobserver acallback); void createnewaccount(in acstring aemailaddress, in acstring apassword, in acstring afirstname, in acstring alastname, in nsirequestobserver acallback); void createexistingaccount(in nsirequestobserver acallback); acstring providerurlforerror(in unsigned long aerror); attributes attribute type description ty...
... createnewaccount() creates a new user account for the storage provider represented by the nsimsgcloudfileprovider.
...this might change in the future, but as it stands, this function can simply return ns_error_not_implemented unless there are plans to call createnewaccount from the management or settings xhtml files.
...And 3 more matches
Activity Manager examples
// step 1: adding a process into the activity manager const nsiap = components.interfaces.nsiactivityprocess; const nsiae = components.interfaces.nsiactivityevent; const nsiam = components.interfaces.nsiactivitymanager; let gactivitymanager = components.classes["@mozilla.org/activity-manager;1"].getservice(nsiam); let process = components.classes["@mozilla.org/activity-process;1"].createinstance(nsiap); // assuming folder is an instance of nsimsgfolder interface // localization is omitted, initiator is not provided process.init("processing folder: " + folder.prettiestname, null); // note that we don't define a custom icon, default process icon // will be used process.contexttype = "account"; // group this activity by account process.contextobj = folder.server; ...
...rocess); // step 2: showing some progress let percent = 50; process.setprogress(percent, "junk processing 25 of 50 messages", 25, 50); // step 3: removing the process and adding an event using process' attributes process.state = components.interfaces.nsiactivityprocess.state_completed; gactivitymanager.removeactivity(process.id); let event = components.classes["@mozilla.org/activity-event;1"].createinstance(nsiae); // localization is omitted, initiator is omitted event.init(folder.prettiestname + " is processed", null, "no junk found", process.starttime, // start time date.now()); // completion time event.contexttype = process.contexttype; // optional event.contextobj = process.contextobj; // optional gactivitymanager.addactivity(event...
... // step 1: create a nsiactivitycancelhandler implementation function canceljunkprocess() { // user stuff here..
...And 3 more matches
Standard OS Libraries
(msdn - getcursorpos) this example was created on windows xp sp2.
... components.utils.import("resource://gre/modules/ctypes.jsm"); var lib = ctypes.open("user32.dll"); /* note: if you go to getcursorpos page on msdn, it says first argument is of structure point, so lets create that structure, * the link here shows that that x and y are type long which is ctypes.long */ // https://msdn.microsoft.com/en-us/library/windows/desktop/dd162805%28v=vs.85%29.aspx var point = new ctypes.structtype("tagpoint", [ { "x": ctypes.long }, { "y": ctypes.long } ]); /* declare the signature of the function we are going to call */ var getcursorpos = lib.declare('getcursorpos', ctypes.winapi_abi, ctypes.bool, point.ptr ); /* use it like this */ var point = point(); var ret = getcursorpos(point.ad...
... components.utils.import("resource://gre/modules/ctypes.jsm"); let coregraphics = ctypes.open("/system/library/frameworks/coregraphics.framework/coregraphics"); let corefoundation = ctypes.open("/system/library/frameworks/corefoundation.framework/corefoundation"); let cgeventref = ctypes.voidptr_t; let cgeventsourceref = ctypes.voidptr_t; let cgeventcreate = coregraphics.declare("cgeventcreate", ctypes.default_abi, cgeventref, cgeventsourceref); let cgfloat = ctypes.voidptr_t.size == 4 ?
...And 3 more matches
Int64
you use the int64 object to create and manipulate 64-bit signed integers.
... note: it's important to note that the 64-bit integer objects created by int64 are not int64 objects; rather, they're opaque objects whose values you manipulate through the other methods on the int64 object.
... syntax creates and returns a new 64-bit signed integer.
...And 3 more matches
UInt64
you use the uint64 object to create and manipulate 64-bit unsigned integers.
... note: it's important to note that the 64-bit integer objects created by uint64 are not uint64 objects; rather, they're opaque objects whose values you manipulate through the other methods on the uint64 object.
... syntax creates and returns a new 64-bit unsigned integer.
...And 3 more matches
Debugger - Firefox Developer Tools
the debugger object when called as a constructor, the debugger object creates a new debugger instance.
... new debugger([global, …]) create a debugger object, and apply its adddebuggee method to each of the givenglobal objects to add them as the initial debuggees.
...this property is initially true in a freshly created debugger instance.
...And 3 more matches
Storage Inspector - Firefox Developer Tools
currently it can be used to inspect the following storage types: cache storage — any dom caches created using the cache api.
... cookies — all the cookies created by the page or any iframes inside of the page.
... cookies created as a part of response of network calls are also listed, but only for calls that happened while the tool is open.
...And 3 more matches
AudioWorkletProcessor - Web APIs
instead, they are created only internally by the creation of an associated audioworkletnodes.
... audioworkletprocessor() creates a new instance of an audioworkletprocessor object.
...the array of audioparamdescriptor-based objects returned is used internally to create the audioparams during the instantiation of the audioworkletnode.
...And 3 more matches
Compositing example - Web APIs
var canvas1 = document.createelement("canvas"); var canvas2 = document.createelement("canvas"); var gco = [ 'source-over','source-in','source-out','source-atop', 'destination-over','destination-in','destination-out','destination-atop', 'lighter', 'copy','xor', 'multiply', 'screen', 'overlay', 'darken', 'lighten', 'color-dodge', 'color-burn', 'hard-light', 'soft-light', 'difference', 'exclusion', 'hue', 'saturation', 'color', 'luminosity' ].reverse(); var gcotext = [ 'this is the default setting and draws new shapes on top of the existing canvas conte...
... function createcanvas() { var canvas = document.createelement("canvas"); canvas.style.background = "url("+op_8x8.data+")"; canvas.style.border = "1px solid #000"; canvas.style.margin = "5px"; canvas.width = width/2; canvas.height = height/2; return canvas; } function runcomposite() { var dl = document.createelement("dl"); document.body.appendchild(dl); while(gco.length) {...
... var pop = gco.pop(); var dt = document.createelement("dt"); dt.textcontent = pop; dl.appendchild(dt); var dd = document.createelement("dd"); var p = document.createelement("p"); p.textcontent = gcotext.pop(); dd.appendchild(p); var canvastodrawon = createcanvas(); var canvastodrawfrom = createcanvas(); var canvastodrawresult = createcanvas(); var ctx = canvastodrawresult.getcontext('2d'); ctx.clearrect(0, 0, width, height) ctx.save(); ctx.drawimage(canvas1, 0, 0, width/2, height/2); ctx.globalcompositeoperation = pop; ctx.drawimage(canvas2, 0, 0, width/2, height/2); ctx.globalcompositeoperation = "source-over"; ctx.fillstyle = "rgba(0,0,0,0.8)...
...And 3 more matches
DOMImplementation - Web APIs
domimplementation.createdocument() creates and returns an xmldocument.
... domimplementation.createdocumenttype() creates and returns a documenttype.
... domimplementation.createhtmldocument() creates and returns an html document.
...And 3 more matches
Document.execCommand() - Web APIs
createlink creates an hyperlink from the selection, but only if there is a selection.
...(internet explorer will create a link with a null value.) cut removes the current selection and copies it to the clipboard.
...(not supported by internet explorer.) defaultparagraphseparator changes the paragraph separator used when new paragraphs are created in editable text regions.
...And 3 more matches
Element.classList - Web APIs
WebAPIElementclassList
examples const div = document.createelement('div'); div.classname = 'foo'; // our starting state: <div class="foo"></div> console.log(div.outerhtml); // use the classlist api to remove and add classes div.classlist.remove("foo"); div.classlist.add("anotherclass"); // <div class="anotherclass"></div> console.log(div.outerhtml); // if visible is set remove it, otherwise add it div.classlist.toggle("visible"); // add/remove visibl...
...see https://bugzilla.mozilla.org/show_bug.cgi?id=814014 polyfill the legacy onpropertychange event can be used to create a living classlist mockup thanks to a element.prototype.classname property that fires the specified event once it is changed.
... document.documentelement.firstchild.appendchild(document.createelement('style')).stylesheet.csstext=( '_*{x-uclp:expression(!this.hasownproperty("classlist")&&window[" ucl"](this))}' + // ie6 '[class]{x-uclp/**/:expression(!this.hasownproperty("classlist")&&window[" ucl"](this))}' //ie7-8 ); } })(window); // 3.
...And 3 more matches
Using the Frame Timing API - Web APIs
when one of those event types is added to the browser's performance timeline, the application is notified of the event via the observer's callback function that was specified when the observer was created.
... creating an observer to observe "frame" performance entry types, the application first creates a performanceobserver object with a specific frame observer callback.
... in the following example, two observers for the "frame" performance entry type are created and the first observer constructor uses inline function syntax.
...And 3 more matches
HTMLCanvasElement.toBlob() - Web APIs
the htmlcanvaselement.toblob() method creates a blob object representing the image contained in the canvas; this file may be cached on the disk or stored in memory at the discretion of the user agent.
...the created image is in a resolution of 96dpi.
...the code snippet below, for example, takes the image in the <canvas> element whose id is "canvas", obtains a copy of it as a png image, then appends a new <img> element to the document, whose source image is the one created using the canvas.
...And 3 more matches
Using microtasks in JavaScript with queueMicrotask() - Web APIs
a microtask is a short function which is executed after the function or program which created it exits and only if the javascript execution stack is empty, but before returning control to the event loop being used by the user agent to drive the script's execution environment.
... a timeout or interval created with settimeout() or setinterval() is reached, causing the corresponding callback to be added to the task queue.
... enqueueing microtasks as such, you should typically use microtasks only when there's no other solution, or when creating frameworks or libraries that need to use microtasks in order to create the functionality they're implementing.
...And 3 more matches
Drag Operations - Web APIs
you can also create your own types.
...this image is created automatically, so you do not need to create it yourself.
...this technique is useful when drawing custom drag images using the canvas element, as in the following example: function dragwithcustomimage(event) { const canvas = document.createelement("canvas"); canvas.width = canvas.height = 50; const ctx = canvas.getcontext("2d"); ctx.linewidth = 4; ctx.moveto(0, 0); ctx.lineto(50, 50); ctx.moveto(0, 50); ctx.lineto(50, 0); ctx.stroke(); const dt = event.datatransfer; dt.setdata('text/plain', 'data to drag'); dt.setdragimage(canvas, 25, 25); } in this example, we make one canvas the drag image.
...And 3 more matches
IDBObjectStoreSync - Web APIs
method overview any add (in any value, in optional any key) raises (idbdatabaseexception); idbindexsync createindex (in domstring name, in domstring storename, in domstring keypath, in optional boolean unique); any get (in any key) raises (idbdatabaseexception); idbcursorsync opencursor (in optional idbkeyrange range, in optional unsigned short direction) raises (idbdatabaseexception); idbindexsync openindex (in domstring name) raises (idbdatabaseexception); any put (...
... snapshot_read 2 any read operations must access a snapshot view of the data, which cannot change once it is created.
... createindex() creates and returns a new index with the given name in the connected database.
...And 3 more matches
MediaElementAudioSourceNode - Web APIs
a mediaelementsourcenode has no inputs and exactly one output, and is created using the audiocontext.createmediaelementsource() method.
... number of inputs 0 number of outputs 1 channel count defined by the media in the htmlmediaelement passed to the audiocontext.createmediaelementsource method that created it.
... constructor mediaelementaudiosourcenode() creates a new mediaelementaudiosourcenode object instance.
...And 3 more matches
MediaRecorder - Web APIs
it is created using the mediarecorder() constructor.
... constructor mediarecorder() creates a new mediarecorder object, given a mediastream to record.
... properties mediarecorder.mimetype read only returns the mime type that was selected as the recording container for the mediarecorder object when it was created.
...And 3 more matches
Using the Media Capabilities API - Web APIs
you can, therefore, test for the presence of the api like so: if ("mediacapabilities" in navigator) { // mediacapabilities is available } else { // mediacapabilities is not available } taking video as an example, to obtain information about video decoding abilities, you create a video decoding configuration which you pass as a parameter to mediacapabilities.decodinginfo() method.
... const videoconfiguration = { type: "file", video: { contenttype: "video/webm;codecs=vp8", width: 800, height: 600, bitrate: 10000, framerate: 15 } }; had we been querying the decodability of an audio file, we would create an audio configuration including the number of channels and sample rate, leaving out the properties that apply only to video—namely, the dimensions and the frame rate: const audioconfiguration = { type: "file", audio: { contenttype: "audio/ogg", channels: 2, bitrate: 132700, samplerate: 5200 } }; had we been testing encoding capabilities, we would have created...
... querying the browser about decoding abilities now that we've created a video decoding configuration we can pass it as a paramater of the decodinginfo() method to determine if a video matching this configuration would be decodable and if the playback would be smooth and power efficient.
...And 3 more matches
OfflineAudioContext.OfflineAudioContext() - Web APIs
the offlineaudiocontext() constructor—part of the web audio api—creates and returns a new offlineaudiocontext object instance, which can then be used to render audio to an audiobuffer rather than to an audio output device.
... syntax var offlineaudioctx = new offlineaudiocontext(numberofchannels, length, samplerate); var offlineaudioctx = new offlineaudiocontext(options); parameters you can specify the parameters for the offlineaudiocontext() constructor as either the same set of parameters as are inputs into the audiocontext.createbuffer() method, or by passing those parameters in an options object.
... length an integer specifying the size of the buffer to create for the audio context, in sample-frames, where one sample-frame is a unit that can contain a single sample of audio data for every channel in the audio data.
...And 3 more matches
OscillatorNode - Web APIs
it is an audioscheduledsourcenode audio-processing module that causes a specified frequency of a given wave to be created—in effect, a constant tone.
... an oscillatornode is created using the baseaudiocontext.createoscillator() method.
...its basic property defaults (see audionode for definitions) are: number of inputs 0 number of outputs 1 channel count mode max channel count 2 (not used in the default count mode) channel interpretation speakers constructor oscillatornode() creates a new instance of an oscillatornode object, optionally providing an object specifying default values for the node's properties.
...And 3 more matches
Using Performance Timeline - Web APIs
performance.mark not supported"); return; } // create some performance entries via the mark() and measure() methods performance.mark("begin"); do_work(50000); performance.mark("end"); do_work(50000); performance.measure("measure1", "begin", "end"); // use getentries() to iterate all entries var p = performance.getentries(); for (var i=0; i < p.length; i++) { log("all entry[" + i + "]"); print_perf_entry(p[i]); } // use ...
... function print_performanceentry(ev) { var properties = ["name", "entrytype", "starttime", "duration"]; // create a few performance entries performance.mark("start"); do_work(50000); performance.mark("stop"); performance.measure("measure-1"); var p = performance.getentries(); for (var i=0; i < p.length; i++) { log("perfentry[" + i + "]"); for (var j=0; j < properties.length; j++) { // check each property in window.performance var supported = properties[j] in p[i]; if (s...
... function perfentry_tojson() { // create a few performance entries performance.mark("mark-1"); performance.mark("mark-2"); performance.measure("meas-1", "mark-1", "mark-2"); var pelist = performance.getentries(); var pe = pelist[0]; if (pe.tojson === undefined) { log ("performanceentry.tojson() is not supported"); return; } // print the performanceentry object var json = pe.tojson(); var s = json.stringify(json)...
...And 3 more matches
PeriodicWave - Web APIs
the periodicwave itself is created/returned by audiocontext.createperiodicwave().
... constructor periodicwave.periodicwave() creates a new periodicwave object instance using the default values for all properties.
... if you wish to establish custom property values at the outset, use the audiocontext.createperiodicwave() factory method instead.
...And 3 more matches
RTCPeerConnection.setLocalDescription() - Web APIs
if the signaling state is one of stable, have-local-offer, or have-remote-pranswer, the webrtc runtime automatically creates a new offer and sets that as the new local description.
... otherwise, setlocaldescription() creates an answer, which becomes the new local description.
...they're interchangeable: mypeerconnection.createoffer().then(function(offer) { return mypeerconnection.setlocaldescription(offer); }); this is equivalent to: mypeerconnection.createoffer().then(function(offer) { return mypeerconnection.setlocaldescription(new rtcsessiondescription(offer)); }); for this reason, the rtcsessiondescription() constructor is deprecated.
...And 3 more matches
Using Service Workers - Web APIs
there have been various attempts to create technologies to solve this problem, and some of the issues have been solved.
... when we come to call the imgload() function, we call it with the url to the image we want to load, as we might expect, but the rest of the code is a little different: let body = document.queryselector('body'); let myimage = new image(); imgload('mylittlevader.jpg').then((response) => { var imageurl = window.url.createobjecturl(response); myimage.src = imageurl; body.appendchild(myimage); }, (error) => { console.log(error); }); on to the end of the function call, we chain the promise then() method, which contains two functions — the first one is executed when the promise successfully resolves, and the second is called when the promise is rejected.
... service workers demo to demonstrate just the very basics of registering and installing a service worker, we have created a simple demo called sw-test, which is a simple star wars lego image gallery.
...And 3 more matches
Using writable streams - Web APIs
constructing a writable stream to create a writable stream, we use the writablestream() constructor; the syntax looks complex at first, but actually isn’t too bad.
...the first object is required, and creates a model in javascript of the underlying sink the data is being written to.
...trategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) { return new promise((resolve, reject) => { var buffer = new arraybuffer(2); var view = new uint16array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listitem = document.createelement('li'); listitem.textcontent = "chunk decoded: " + decoded; list.appendchild(listitem); result += decoded; resolve(); }); }, close() { var listitem = document.createelement('li'); listitem.textcontent = "[message received] " + result; list.appendchild(listitem); }, abort(err) { console.log("sink error:", err); } }, queuingstrategy); t...
...And 3 more matches
User Timing API - Web APIs
the user timing interface allows the developer to create application specific timestamps that are part of the browser's performance timeline.
... performance marks a performance mark is a named performance entry that is created by the application.
... creating a performance mark the performance.mark() method is used to create a performance mark.
...And 3 more matches
Using textures in WebGL - Web APIs
you'll need to include it if you create your own project based on this code.
...// function loadtexture(gl, url) { const texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); // because images have to be download over the internet // they might take a moment until they are ready.
...re_wrap_s, gl.clamp_to_edge); gl.texparameteri(gl.texture_2d, gl.texture_wrap_t, gl.clamp_to_edge); gl.texparameteri(gl.texture_2d, gl.texture_min_filter, gl.linear); } }; image.src = url; return texture; } function ispowerof2(value) { return (value & (value - 1)) == 0; } the loadtexture() routine starts by creating a webgl texture object texture by calling the webgl createtexture() function.
...And 3 more matches
Inputs and input sources - Web APIs
by combining these two types of input with the changing of viewing position and/or orientation through the headset or other mechanisms, you can create an interactive simulated environment.
... transient input sources some devices may create transient input sources to be used in tandem with an action which doesn't really come from that device, but is being presented as if it is.
... for example, if an xr device provides a mode in which the mouse is used to simulate events on the device, a new xrinputsource object might be created to represent the simulated input source for the duration of handling the action.
...And 3 more matches
Functions and classes available to Web Workers - Web APIs
40 (40) no support (yes) no support textencoder and textdecoder create and return a new textencoder, or respectively textdecoder, allowing to encode or decode strings into specific encodings.
... 20 (20) no support no support no support url workers can use the static methods url.createobjecturl and url.revokeobjecturl with blob objects accesible to the worker.
... workers can also create a new url using the url() constructor and call any normal method on the returned object.
...And 3 more matches
Window - Web APIs
WebAPIWindow
staticrange read only returns a staticrange() constructor which creates a staticrange object.
... window.localstorage read only returns a reference to the local storage object used to store data that may only be accessed by the origin that created it.
... window.sessionstorage returns a reference to the session storage object used to store data that may only be accessed by the origin that created it.
...And 3 more matches
Border-radius generator - CSS: Cascading Style Sheets
ashed #999; border-radius: 3px; -moz-user-select: text; -webkit-user-select: text; -ms-user-select: text; user-select: text; float: right; } javascript content 'use strict'; /** * ui-inputslidermanager */ var inputslidermanager = (function inputslidermanager() { var subscribers = {}; var sliders = []; var inputcomponent = function inputcomponent(obj) { var input = document.createelement('input'); input.setattribute('type', 'text'); input.addeventlistener('click', function(e) { this.select(); }); input.addeventlistener('change', function(e) { var value = parseint(e.target.value); if (isnan(value) === true) setvalue(obj.topic, obj.value); else setvalue(obj.topic, value); }); subscribe(obj.topic, function(value) { input.value = value + ...
...obj.unit; }); return input; } var slidercomponent = function slidercomponent(obj, sign) { var slider = document.createelement('div'); var startx = null; var start_value = 0; slider.addeventlistener("click", function(e) { setvalue(obj.topic, obj.value + obj.step * sign); }); slider.addeventlistener("mousedown", function(e) { startx = e.clientx; start_value = obj.value; document.body.style.cursor = "e-resize"; document.addeventlistener("mousemove", slidermotion); }); document.addeventlistener("mouseup", function(e) { document.removeeventlistener("mousemove", slidermotion); document.body.style.cursor = "auto"; slider.style.cursor = "pointer"; }); var slidermotion = function slidermotion(e) { slider.style.cursor = "e-resize"; var delta = ...
...sensivity : 5; var input = new inputcomponent(this); var slider_left = new slidercomponent(this, -1); var slider_right = new slidercomponent(this, 1); slider_left.classname = 'ui-input-slider-left'; slider_right.classname = 'ui-input-slider-right'; if (name) { var info = document.createelement('span'); info.classname = 'ui-input-slider-info'; info.textcontent = name; node.appendchild(info); } node.appendchild(slider_left); node.appendchild(input); node.appendchild(slider_right); node.classname = 'ui-input-slider ui-input-slider-container'; this.input = input; sliders[topic] = this; setvalue(topic, value); } var setvalue = function setvalue(topic, va...
...And 3 more matches
CSS Grid Layout and Accessibility - CSS: Cascading Style Sheets
back in the early days of web design, the way we constructed page layout was to use html tables, then fragment our design into the cells of those tables in order to create a layout.
...the ultimate aim being that we could create a semantic and well structured document, then apply css to create the layout we desired.
...the css zen garden challenged us to take identical markup and create a unique design using css.
...And 3 more matches
conic-gradient() - CSS: Cascading Style Sheets
the conic-gradient() css function creates an image consisting of a gradient with color transitions rotated around a center point (rather than radiating from the center).
... to create a conic gradient that repeats so as to fill a 360 degree rotation, use the repeating-conic-gradient() function instead.
... customizing gradients by adding more angled color-stop points on the gradient arc, you can create a highly customized transition between multiple colors.
...And 3 more matches
mask-border-slice - CSS: Cascading Style Sheets
when one position is specified, it creates all four slices at the same distance from their respective sides.
... when two positions are specified, the first value creates slices measured from the top and bottom, the second creates slices measured from the left and right.
... when three positions are specified, the first value creates a slice measured from the top, the second creates slices measured from the left and right, the third creates a slice measured from the bottom.
...And 3 more matches
<input type="month"> - HTML: Hypertext Markup Language
WebHTMLElementinputmonth
<input> elements of type month create input fields that let the user enter a month and year allowing a month and year to be easily entered.
...as an example, the month picker on chrome for android looks like this: non-supporting browsers gracefully degrade to a text input, but this creates problems both in terms of consistency of user interface (the presented control will be different), and data handling.
... examples in this example, we create two sets of ui elements, each designed to let the user select a month and year.
...And 3 more matches
<input type="week"> - HTML: Hypertext Markup Language
WebHTMLElementinputweek
<input> elements of type week create input fields allowing easy entry of a year plus the iso 8601 week number during that year (i.e., week 1 to 52 or 53).
...for example, the week picker on chrome for android looks like this: non-supporting browsers gracefully degrade to a text input, but this creates problems both in terms of consistency of user interface (the presented control will be different), and data handling.
... examples in this example we create two sets of ui elements for choosing weeks: a native picker created using <input type="week">, and a set of two <select> elements for choosing weeks/years in older browsers that don't support the week input type.
...And 3 more matches
JavaScript modules - JavaScript
introducing an example to demonstrate usage of modules, we've created a simple set of examples that you can find on github.
... these examples demonstrate a simple set of modules that create a <canvas> element on a webpage, and then draw (and report information about) different shapes on the canvas.
... the modules directory's two modules are described below: canvas.js — contains functions related to setting up the canvas: create() — creates a canvas with a specified width and height inside a wrapper <div> with a specified id, which is itself appended inside a specified parent element.
...And 3 more matches
Array.from() - JavaScript
the array.from() static method creates a new, shallow-copied array instance from an array-like or iterable object.
... description array.from() lets you create arrays from: array-like objects (objects with a length property and indexed elements); or iterable objects (objects such as map and set).
... array.from() has an optional parameter mapfn, which allows you to execute a map() function on each element of the array being created.
...And 3 more matches
BigInt64Array - JavaScript
constructor bigint64array() creates a new bigint64array object.
... static methods bigint64array.from() creates a new bigint64array from an array-like or iterable object.
... bigint64array.of() creates a new bigint64array with a variable number of arguments.
...And 3 more matches
BigUint64Array - JavaScript
constructor biguint64array() creates a new biguint64array object.
... static methods biguint64array.from() creates a new biguint64array from an array-like or iterable object.
... biguint64array.of() creates a new biguint64array with a variable number of arguments.
...And 3 more matches
Float32Array - JavaScript
constructor float32array() creates a new float32array object.
... static methods float32array.from() creates a new float32array from an array-like or iterable object.
... float32array.of() creates a new float32array with a variable number of arguments.
...And 3 more matches
Float64Array - JavaScript
constructor float64array() creates a new float64array object.
... static methods float64array.from() creates a new float64array from an array-like or iterable object.
... float64array.of() creates a new float64array with a variable number of arguments.
...And 3 more matches
Int16Array - JavaScript
constructor int16array() creates a new int16array object.
... static methods int16array.from() creates a new int16array from an array-like or iterable object.
... int16array.of() creates a new int16array with a variable number of arguments.
...And 3 more matches
Int32Array - JavaScript
constructor int32array() creates a new int32array object.
... static methods int32array.from() creates a new int32array from an array-like or iterable object.
... int32array.of() creates a new int32array with a variable number of arguments.
...And 3 more matches
Int8Array - JavaScript
constructor int8array() creates a new int8array object.
... static methods int8array.from() creates a new int8array from an array-like or iterable object.
... int8array.of() creates a new int8array with a variable number of arguments.
...And 3 more matches
Object.defineProperty() - JavaScript
normal property addition through assignment creates properties which show up during property enumeration (for...in loop or object.keys method), whose values may be changed, and which may be deleted.
...in order to ensure these defaults are preserved, you might freeze the object.prototype upfront, specify all options explicitly, or point to null with object.create(null).
... // using __proto__ var obj = {}; var descriptor = object.create(null); // no inherited properties descriptor.value = 'static'; // not enumerable, not configurable, not writable as defaults object.defineproperty(obj, 'key', descriptor); // being explicit object.defineproperty(obj, 'key', { enumerable: false, configurable: false, writable: false, value: 'static' }); // recycling same object function withvalue(value) { var d = withvalue.d || ( withvalue.d = { enumerable: false, writable: false, configurable: false, value: value } ); // avoiding duplicate operation for assigning value if (d.value !== value) d.value = value; return d; } // ...
...And 3 more matches
Proxy - JavaScript
the proxy object enables you to create a proxy for another object, which can intercept and redefine fundamental operations for that object.
... description a proxy is created with two parameters: target: the original object which you want to proxy handler: an object that defines which operations will be intercepted and how to redefine intercepted operations.
... redefine others: const target = { message1: "hello", message2: "everyone" }; const handler3 = { get: function (target, prop, receiver) { if (prop === "message2") { return "world"; } return reflect.get(...arguments); }, }; const proxy3 = new proxy(target, handler3); console.log(proxy3.message1); // hello console.log(proxy3.message2); // world constructor proxy() creates a new proxy object.
...And 3 more matches
String - JavaScript
creating strings strings can be created as primitives, from string literals, or as objects, using the string() constructor: const string1 = "a string primitive"; const string2 = 'also a string primitive'; const string3 = `yet another string primitive`; const string4 = new string("a string object"); string primitives and string objects can be used interchangeably in most situations.
...for example: let s1 = '2 + 2' // creates a string primitive let s2 = new string('2 + 2') // creates a string object console.log(eval(s1)) // returns the number 4 console.log(eval(s2)) // returns the string "2 + 2" for these reasons, the code may break when it encounters string objects when it expects a primitive string instead, although generally, authors need not worry about the distinction.
... constructor string() creates a new string object.
...And 3 more matches
Symbol.for() - JavaScript
otherwise a new symbol gets created in the global symbol registry with this key.
... return value an existing symbol with the given key if found; otherwise, a new symbol is created and returned.
... description in contrast to symbol(), the symbol.for() function creates a symbol available in a global symbol registry list.
...And 3 more matches
Uint16Array() constructor - JavaScript
the uint16array() typed array constructor creates an array of 16-bit unsigned integers in the platform byte order.
... syntax new uint16array(); // new in es2017 new uint16array(length); new uint16array(typedarray); new uint16array(object); new uint16array(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros.
... object when called with an object argument, a new typed array is created as if by the typedarray.from() method.
...And 3 more matches
Uint16Array - JavaScript
constructor uint16array() creates a new uint16array object.
... static methods uint16array.from() creates a new uint16array from an array-like or iterable object.
... uint16array.of() creates a new uint16array with a variable number of arguments.
...And 3 more matches
Uint32Array - JavaScript
constructor uint32array() creates a new uint32array object.
... static methods uint32array.from() creates a new uint32array from an array-like or iterable object.
... uint32array.of() creates a new uint32array with a variable number of arguments.
...And 3 more matches
Uint8Array - JavaScript
constructor uint8array() creates a new uint8array object.
... static methods uint8array.from() creates a new uint8array from an array-like or iterable object.
... uint8array.of() creates a new uint8array with a variable number of arguments.
...And 3 more matches
Uint8ClampedArray - JavaScript
constructor uint8clampedarray() creates a new uint8clampedarray object.
... static methods uint8clampedarray.from() creates a new uint8clampedarray from an array-like or iterable object.
... uint8clampedarray.of() creates a new uint8clampedarray from a variable number of arguments.
...And 3 more matches
Object initializer - JavaScript
objects can be initialized using new object(), object.create(), or using the literal notation (initializer notation).
... examples creating objects an empty object with no properties can be created like this: let object = {} however, the advantage of the literal or initializer notation is, that you are able to quickly create objects with properties inside the curly braces.
... the following code creates an object with three properties and the keys are "foo", "age" and "baz".
...And 3 more matches
var - JavaScript
'use strict'; function foo() { var x = 1; function bar() { var y = 2; console.log(x); // 1 (function `bar` closes over `x`) console.log(y); // 2 (`y` is in scope) } bar(); console.log(x); // 1 (`x` is in scope) console.log(y); // referenceerror in strict mode, `y` is scoped to `bar` } foo(); variables declared using var are created before any code is executed in a process known as hoisting.
... the property created on the global object for global variables, is set to be non-configurable because the identifier is to be treated as a variable, rather than a straightforward property of the global object.
...the corollary, in non-strict mode, is that assignment to unqualified identifiers will, if there is no variable of the same name declared in the scope chain, assume you want to create a property with that name on the global object.
...And 3 more matches
Strict mode - JavaScript
sometimes this fixes the immediate problem, but sometimes this creates worse problems in the future.
... first, strict mode makes it impossible to accidentally create global variables.
... in normal javascript mistyping a variable in an assignment creates a new property on the global object and continues to "work" (although future failure is possible: likely, in modern javascript).
...And 3 more matches
JavaScript typed arrays - JavaScript
you can't directly manipulate the contents of an arraybuffer; instead, you create a typed array view or a dataview which represents the buffer in a specific format, and use that to read and write the contents of the buffer.
... examples using views with buffers first of all, we will need to create a buffer, here with a fixed length of 16-bytes: let buffer = new arraybuffer(16); at this point, we have a chunk of memory whose bytes are all pre-initialized to 0.
...we can confirm that it is indeed 16 bytes long, and that's about it: if (buffer.bytelength === 16) { console.log("yes, it's 16 bytes."); } else { console.log("oh no, it's the wrong size!"); } before we can really work with this buffer, we need to create a view.
...And 3 more matches
Graphic design for responsive sites - Progressive web apps (PWAs)
high res and low res image copies one option here is to create a hi res and a low res set of images, then use resolution media queries to serve the hi res images only to hi res devices.
... javascript javascript has functions that enable developers to create animations, and any other type of interactivity you want.
...you can also add links direcly into svg and can create animations using smil (synchronized multimedia intergration language).
...And 3 more matches
Mobile first - Progressive web apps (PWAs)
a simple example to demonstrate the concepts, i wanted to cover in this article, i created a very simple app containing a nav menu, heading and single column of text.
...to make my simple example i created a sample app structure from a mozilla mortar template.
... i installed the volo automation tool by running the following on the command line sudo npm install -g volo (you'll also need to get node.js too if you don't already have it) i then created my sample project using volo create myapp mozilla/mortar-app-stub this creates a sample project inside a directory called myapp.
...And 3 more matches
Namespaces crash course - SVG: Scalable Vector Graphics
dtds were never designed with mixed content in mind, and past attempts to create mixed content dtds are now considered to have failed.
...the binding created by the xmlns:xlink parameter in the example above is absolutely essential for the xlink:href parameter to not cause an error.
... the dom level 1 recommendation was created before the original namespaces in xml recommendation was released; therefore, dom1 isn't namespace aware.
...And 3 more matches
Gradients in SVG - SVG: Scalable Vector Graphics
« previousnext » perhaps more exciting than just fills and strokes is the fact that you can also create and apply gradients as either fills or strokes.
...to insert one, you create a <lineargradient> node inside the definitions section of your svg file.
...you can insert as many stop colors as you like to create a blend that's as beautiful or hideous as you need, but the offsets should always increase from 0% (or 0 if you want to drop the % sign) to 100% (or 1).
...And 3 more matches
Using templates and slots - Web Components
this article explains how you can use the <template> and <slot> elements to create a flexible template that can then be used to populate the shadow dom of a web component.
... class extends htmlelement { constructor() { super(); let template = document.getelementbyid('my-paragraph'); let templatecontent = template.content; const shadowroot = this.attachshadow({mode: 'open'}) .appendchild(templatecontent.clonenode(true)); } } ); the key point to note here is that we append a clone of the template content to the shadow root, created using the node.clonenode() method.
... the following set of code snippets show how to use <slot> together with <template> and some javascript to: create a <element-details> element with named slots in its shadow root design the <element-details> element in such a way that, when used in documents, it is rendered from composing the element’s content together with content from its shadow root—that is, pieces of the element’s content are used to fill in named slots in its shadow root note that it is technically possible to use <slot> element...
...And 3 more matches
Private Properties - Archive of obsolete content
moreover, to create each thumbnail only when it's first required: function getthumbnail(image) { let thumbnail = image._thumbnail; if (!thumbnail) { thumbnail = createthumbnail(image); image._thumbnail = thumbnail; } return thumbnail; } this approach is straightforward, but relies on the use of prefixes.
... a better approach would be to store thumbnails in their own, separate hash map: let thumbnails = {}; function getthumbnail(image) { let thumbnail = thumbnails[image]; if (!thumbnail) { thumbnail = createthumbnail(image); thumbnails[image] = thumbnail; } return thumbnail; } there are two problems with the above approach.
...ap, but differs from it in two crucial ways: it can use ordinary objects as keys it does not maintain a strong reference to its values to understand how weakmaps are used in practice, the following rewrites the thumbnail cache using a weakmap: let thumbnails = new weakmap(); function getthumbnail(image) { let thumbnail = thumbnails.get(image); if (!thumbnail) { thumbnail = createthumbnail(image); thumbnails.set(image, thumbnail); } return thumbnail; } this version suffers from none of the problems we mentioned earlier.
...And 2 more matches
remote/parent - Archive of obsolete content
for consistency and to make writing multiprocess compatible code easier, remoterequire() will also create a new module loader and load modules in the main process.
...listen to attach and detach events to hear as processes are started and stopped: const { processes } = require("sdk/remote/parent"); processes.on("attach", function(process) { console.log("new process is remote: " + process.isremote); }); methods forevery(callback) calls the callback for every existing process and any new processes created in the future.
...listen to attach and detach events to hear as frames are created and destroyed.
...And 2 more matches
ui/sidebar - Archive of obsolete content
experimental enables you to create sidebars.
... addon.port.emit("ping"); addon.port.on("pong", function() { console.log("sidebar script got the reply"); }); the "main.js" file creates a sidebar object and adds a listener to its attach event.
... addon.port.on("ping", function() { console.log("sidebar script got the message"); addon.port.emit("pong"); }); the "main.js" file creates a sidebar object and adds a listener to its attach event.
...And 2 more matches
ui/toolbar - Archive of obsolete content
unlike a panel, a toolbar: does not overlap with any web content is persistent, remaining visible until the user chooses to close it is a fixed size, and appears in a fixed location usage creating and destroying toolbars you don't specify toolbar content directly: instead, you create other ui components and supply them to the toolbar constructor.
... showing and hiding toolbars by default, a toolbar is shown when it is created, although you can specify that a toolbar should be hidden initially by passing hidden:true as an option in its constructor.
... hidden state persists even over create/destroy cycles: if a toolbar is created, then hidden, then destroyed, and another toolbar with the same title is then created, the new toolbar will be in the hidden state.
...And 2 more matches
Implementing the widget - Archive of obsolete content
on a right-click, the widget should display a list of all the annotations the user has created.
... so there are three files we'll need to create: the widget's content script and its two icons.
... inside the data subdirectory create another subdirectory widget.
...And 2 more matches
Unit Testing - Archive of obsolete content
the sdk provides a framework to help create and run unit tests for your code.
...so we'll create a base64 module to expose these functions from the platform (see creating reusable modules).
... to begin with, create a new directory, navigate to it, and run jpm init.
...And 2 more matches
Canvas code snippets - Archive of obsolete content
this.ctx); } } canvas2dcontext.setup = function() { var methods = ['arc', 'arcto', 'beginpath', 'beziercurveto', 'clearrect', 'clip', 'closepath', 'drawimage', 'fill', 'fillrect', 'filltext', 'lineto', 'moveto', 'quadraticcurveto', 'rect', 'restore', 'rotate', 'save', 'scale', 'settransform', 'stroke', 'strokerect', 'stroketext', 'transform', 'translate']; var gettermethods = ['createpattern', 'drawfocusring', 'ispointinpath', 'measuretext', // drawfocusring not currently supported // the following might instead be wrapped to be able to chain their child objects 'createimagedata', 'createlineargradient', 'createradialgradient', 'getimagedata', 'putimagedata' ]; var props = ['canvas', 'fillstyle', 'font', 'globalalpha', 'globalcompositeoperation', 'linecap'...
...w promise(accept => canvas.toblob(accept, type, options)); reader.readasarraybuffer(blob); yield new promise(accept => { reader.onloadend = accept }); return yield os.file.writeatomic(path, new uint8array(reader.result), { tmppath: path + '.tmp' }); }); } loading a remote page onto a canvas element the following class first creates a hidden iframe element and attaches a listener to the frame's load event.
... remotecanvas = function() { this.url = 'http://developer.mozilla.org'; }; remotecanvas.canvas_width = 300; remotecanvas.canvas_height = 300; remotecanvas.prototype.load = function() { var windowwidth = window.innerwidth - 25; var iframe; iframe = document.createelement('iframe'); iframe.id = 'test-iframe'; iframe.height = '10px'; iframe.width = windowwidth + 'px'; iframe.style.visibility = 'hidden'; iframe.src = this.url; // here is where the magic happens...
...And 2 more matches
Miscellaneous - Archive of obsolete content
these properties can be accessed from javascript in the following manner: var common = { _bundle: components.classes["@mozilla.org/intl/stringbundle;1"] .getservice(components.interfaces.nsistringbundleservice) .createbundle("chrome://myext/locale/myext.properties"), getlocalizedmessage: function(msg) { return this._bundle.getstringfromname(msg); } }; alert(common.getlocalizedmessage("invalid.url")) another similar alternative (using both getstringfromname and formatstringfromname), is: var fcbundle = components.classes["@mozilla.org/intl/stringbundle;1"] .
...getservice(components.interfaces.nsistringbundleservice) .createbundle("chrome://myext/locale/myext.properties"); function getstr(msg, args){ //get localised message if (args){ args = array.prototype.slice.call(arguments, 1); return fcbundle.formatstringfromname(msg,args,args.length); } else { return fcbundle.getstringfromname(msg); } } /* usage */ alert(getstr("invalid.url", "http://bad/url/", "3")); //for message with parameters alert(getstr("invalid.url")); //for message without parameters getting postdata of a webpage first, you need to get the browser you want, and its historysession.
...and here's how it's done postdata.queryinterface(ci.nsiseekablestream).seek(ci.nsiseekablestream.ns_seek_set, 0); var stream = cc["@mozilla.org/binaryinputstream;1"].createinstance(ci.nsibinaryinputstream); stream.setinputstream(postdata); var postbytes = stream.readbytearray(stream.available()); var poststr = string.fromcharcode.apply(null, postbytes); //do anything to your poststr alert(poststr); getting a string from the input stream is made somewhat simpler in firefox 4, by the addition of netutil.readinputstreamtostring() getting postdata of a request befor...
...And 2 more matches
Enhanced Extension Installation - Archive of obsolete content
uninstallation, disabling, enabling these functions work on the same principle as installation - the user requests an action through the ui while the application is running and metadata is written (tobeuninstalled, tobedisabled, tobeenabled) and a .autoreg file created in the profile so that on the subsequent startup the extension system's startup routine can remove files (in the uninstall case) and write a new extensions.ini file listing the directories for the currently "active" items.
... to implement this, we create an interface that the extension manager can ask for information about the location, such as what its name is, where its located on disk (if anywhere, in the case of registry based locations which have no root directory), for a list of item directories, for a directory of a particular item, for a subdirectory or file within an item's directory, etc.
... at this stage we rewrite the extensions-startup.manifest and extensions.ini manifests and create the .autoreg file in the profile directory.
...And 2 more matches
Extension Etiquette - Archive of obsolete content
sub-menus should be used for single extensions needing multiple menu items, and a tools menu item should not be created for options and preferences (for options and preferences, see the add-on manager).
... if possible, create a menu item in the menu where it is most applicable; for instance, a bookmark sharing extension should be called from the bookmarks menu.
... about dialogs there is a default popup about dialog that is created from install.rdf data; creating a new xul about box is usually unnecessary.
...And 2 more matches
Chapter 6: Firefox extensions and XUL applications - Archive of obsolete content
on the program side, we’ll create a class called rpncalc.
... 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.
... create test case first, add the test case for the subtraction method.
...And 2 more matches
Connecting to Remote Content - Archive of obsolete content
let url = "http://www.example.com/"; let request = components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"] .createinstance(components.interfaces.nsixmlhttprequest); request.onload = function(aevent) { window.alert("response text: " + aevent.target.responsetext); }; request.onerror = function(aevent) { window.alert("error status: " + aevent.target.status); }; request.open("get", url, true); request.send(null); in this example we demonstrate how to make a xmlhttprequest call in asynchronous mode.
... you can see that an instance of the xmlhttprequest class is created and it holds all functionality for making a request.
... we create this instance using xpcom instead of the usual way (new xmlhttprequest()) because this way works both in chrome and non-chrome code.
...And 2 more matches
Add-ons - Archive of obsolete content
add-on sdk using the add-on sdk, you can create firefox add-ons.
... you can use various standard web technologies: javascript, html, and css, to create the add-ons.
... the sdk includes javascript apis, which you can use to create add-ons and tools for creating, running, testing, and packaging add-ons.
...And 2 more matches
Inner-browsing extending the browser navigation paradigm - Archive of obsolete content
many of the new web technologies in the html 4.0 specification, xml 1.0, dom level 3 were explicitly created with application-like behavior and more sophisticated navigational models in mind.
...data request \________ dynamically create a hidden iframe \_________ content is loaded -> call data binder data binder \_____ load xml||html data from iframe "container" \_____ send content to proper layout components the method presented here separates data request from data binding.
...as a general approach, the main steps to the iframe-based implementation can be represented as follows: create a hidden iframe in the page; when a new content is required, ask for the content to the iframe; the iframe will load the content and callback a function in the main page; update the main page.
...And 2 more matches
List of Mozilla-Based Applications - Archive of obsolete content
y (note: this is separate from the javascript library jslib) joybidder ebay auction tool standalone version uses xulrunner just (fr) audio a tool for setting temporal tags in audio documents jsdoc toolkit documentation tool uses mozilla rhino k-meleon gecko-based web browser for windows embeds gecko in mfc kairo.at mandelbrot creates images of mandelbrot sets xulrunner application kazehakase gecko-based web browser for unix kirix strata data browser kiwix offline version of wikipedia kneemail prayer, praise, and journal application komodo and komodo edit and open komodo development tools mozilla-based application (pre-xulrunner style), xul ui ...
...imen, genetic and molecular assay data based on xul liaison groupware client for novell’s email and collaboration server previously called mozngw linbox kiosk browser (fr) web browser dedicated browser for french prefecture and town hall litl internet computer for home uses spidermonkey and gecko lizilayers gis application 3liz also creates some gis firefox add-ons logitech harmony remote software software for remote control device uses gre or xulrunner longman dictionary of contemporary english cd-rom lotus notes / sametime groupware the latest version of ibm lotus notes and sametime can embed xul applications lucidor e-book reader lx-office accounting tool ...
...it's possible to create your own python web browser with hulahop, and much much more besides.
...And 2 more matches
Notes on HTML Reflow - Archive of obsolete content
in this case, the primary frame is the frame containing the first line of text, with continuing frames (or continuations ) created for subsequent lines.
...most of the constraints in the new reflow state are computed when the state is created; for example, the available space in the new reflow state is computed by subtracting the container frame's border and padding from the parent reflow state's available space.
...to request (or schedule ) an incremental reflow (e.g., in response to a change in the content model), a reflow command object is created and passed to the presentation shell via the nsipresshell::appendreflowcommand method.
...And 2 more matches
ActiveX Control for Hosting Netscape Plug-ins in IE - Archive of obsolete content
use a tool such as guidgen.exe or uuidgen.exe to create the new guids.
... usage insert some html like this into your content: <object classid="clsid:dbb2de32-61f1-4f7f-beb8-a37f5bc24ee2" width="500" height="300"> <param name="type" value="video/quicktime"/> <param name="src" value="http://www.foobar.com/some_movie.mov"/> <!-- custom arguments --> <param name="loop" value="true"/> </object> the classid attribute tells ie to create an instance of the plug-in hosting control, the width and height specify the dimensions in pixels.
...the control uses this value to determine which plug-in it should create to handle the content.
...And 2 more matches
Making it into a dynamic overlay and packaging it up for distribution - Archive of obsolete content
now that we have a static overlay we're in good shape to create a xpi package that installs our extension as a dynamic overlay.
...after that we'll create a contents.rdf file describing the tinderstatus component for the chrome registry and an install.js script to perform the installation.
...create a tinderstatus subdirectory in it and a content sub-subdirectory in that subdirectory.
...And 2 more matches
Drag and Drop JavaScript Wrapper - Archive of obsolete content
<script src="chrome://global/content/nsdraganddrop.js" /> <script src="chrome://global/content/nstransferable.js" /> this drag and drop library creates an object stored in the variable nsdraganddrop.
...each of the functions takes two parameters, the first is the event object and the second is an observer object that you create.
...the second parameter to this function is the observer, which we'll create soon.
...And 2 more matches
Document Loading - From Load Start to Finding a Handler - Archive of obsolete content
douriload() creates a channel, massages it to have the right post data, load flags, cache key, referrer, etc.
...if the load is not aborted, we create an nsdocumentopeninfo object for this load, passing it the "this is a link click" boolean and the window context.
...if it does, we instantiate that component using its contractid (via createinstance) and call trycontentlistener on it.
...And 2 more matches
Nanojit - Archive of obsolete content
an application using nanojit creates a nanojit::lirbuffer object to hold lir instructions.
... it creates a nanojit::lirbufwriter object to write instructions to the buffer.
...codealloc *codealloc = new codealloc(); assembler *assm = new (&gc) assembler(*codealloc, *alloc, &core, &lc); fragmento *fragmento = new (&gc) fragmento(&core, &lc, cache_size_log2, codealloc); lirbuffer *buf = new (*alloc) lirbuffer(*alloc); #ifdef debug fragmento->labels = new (*alloc) labelmap(*alloc, &lc); buf->names = new (*alloc) lirnamemap(*alloc, fragmento->labels); #endif // create a fragment to hold some native code.
...And 2 more matches
Space Manager High Level Design - Archive of obsolete content
the primary classes that interact with the space manager are: nsblockreflowstate nsblockframe nsboxtoblockadaptor the general interaction model is to create a space manager for a block frame in the context of a reflow, and to associate it with the blockreflowstate so it is passed down to child frames' reflow methods.
...there is no internal use of the nsbandtrapezoid by the space manager, rather it uses its internal bandlist to create a banddata collection, which is largely made up of nstrapezoid data.
... use case use case 1: space manager is created / destroyed space manager instances are created in the nsblockframe's reflow method.
...And 2 more matches
Supporting per-window private browsing - Archive of obsolete content
ts.interfaces.nsisupportsprbool); // if another extension has not already canceled entering the private mode if (!asubject.data) { /* you should display some user interface here */ asubject.data = true; // cancel the operation } }, "last-pb-context-exiting", false); forcing a channel into private mode usually, network channels inherit the privacy status of the document that created them, which means that they work correctly most of the time.
... however, sometimes you need to adjust the privacy status on a channel manually, for example, if you have created the channel directly yourself.
... the example below creates a channel to load a url, and forces it to be in private mode.
...And 2 more matches
Reading from Files - Archive of obsolete content
while there is only one method to create an input stream, it provides a number of options to control exactly how reading is performed.
...to create an input stream, first get a reference to a nsifile, and then use nsiscriptableio.newinputstream() to open a stream for reading from it.
...next, nsiscriptableio.newinputstream() is called to create a new input stream for reading from the file.
...And 2 more matches
Template Builder Interface - Archive of obsolete content
if so, a template builder will be created for the element and attached to the element.
... if the element is a <tree> element and has the flags attribute set to "dont-build-content", a tree builder will be created.
... otherwise, a content builder will be created.
...And 2 more matches
Adding Style Sheets - Archive of obsolete content
« previousnext » we have hardly modified the look of the elements we have created so far.
...it is much better to create a separate style sheet.
...for installed files, you'll have to create or modify a manifest file and install the skin.
...And 2 more matches
Creating a Wizard - Archive of obsolete content
xul provides a way to create wizards easily.
... xul provides a wizard element which can be used to create wizards.
...the pages of the wizard are created using the wizardpage element.
...And 2 more matches
Localization - Archive of obsolete content
usually, a table of strings is created for each language.
...a file is created which contains the entity declarations for each supported language.
... once you have created a dtd file for your xul, you will need to add a line to the xul file which indicates that you want to use the dtd file.
...And 2 more matches
More Tree Features - Archive of obsolete content
hierarchical trees the tree element is also used to create hierarchical lists, like that found in a file manager or a browser's bookmarks list.
...to create a set of nested rows, all we need to do is add a second treechildren element inside the parent treeitem.
...you can repeat this process to create deeply nested trees.
...And 2 more matches
Splitters - Archive of obsolete content
it creates a skinny bar between two sections which allows these sections to be resized.
...iew <hbox flex="1"> <iframe id="content-1" width="60" height="20" src="w1.html"/> <splitter collapse="before" resizeafter="farthest"> <grippy/> </splitter> <iframe id="content-2" width="60" height="20" src="w2.html"/> <iframe id="content-3" width="60" height="20" src="w3.html"/> <iframe id="content-4" width="60" height="20" src="w4.html"/> </hbox> here, four iframes have been created and a splitter has been placed in-between the first and second one.
...create this file and put whatever you want in it for now.
...And 2 more matches
Toolbars - Archive of obsolete content
xul has a method to create toolbars.
...a simple toolbar inside a toolbox source view <toolbox> <toolbar id="nav-toolbar"> <toolbarbutton label="back"/> <toolbarbutton label="forward"/> </toolbar> </toolbox> this has created a toolbar containing two buttons, a back button and a forward button.
... the toolbar is the main element that creates the actual toolbar.
...And 2 more matches
XBL Inheritance - Archive of obsolete content
inheritance sometimes you may want to create an xbl widget that is similar to an existing one.
... for example, let's say you want to create an xbl button with a popup.
... one way to create this is to duplicate the existing xbl code for buttons.
...And 2 more matches
Creating a Windows Inno Setup installer for XULRunner applications - Archive of obsolete content
a xulrunner application has no installer by default; however, these instructions can help you to easily create a windows installer with inno setup.
... step 3: creating the inno setup script create an inno setup script (.iss file).
...app allownoicons=yes outputdir=..\build\output outputbasefilename=myapp-1.0-win32 ; setupiconfile= compression=lzma solidcompression=yes [languages] name: english; messagesfile: compiler:default.isl [components] name: main; description: my app; types: full compact custom; flags: fixed name: runtime; description: xul runner runtime; types: full custom [tasks] name: desktopicon; description: {cm:createdesktopicon}; groupdescription: {cm:additionalicons}; flags: unchecked name: quicklaunchicon; description: {cm:createquicklaunchicon}; groupdescription: {cm:additionalicons}; flags: unchecked [files] source: c:\develop\xulrunnerinstaller\myapp\myapp.exe; destdir: {app}; components: main; flags: ignoreversion source: c:\develop\xulrunnerinstaller\myapp\application.ini; destdir: {app}; components: ...
...And 2 more matches
Getting started with XULRunner - Archive of obsolete content
step 3: create the application folder structure time to start a simple, bare bones application shell.
... on windows, i created the root in a new c:\program files\myapp folder, but you can create it wherever you like, using whatever os you like.
...you could also just create a new application root-level manifest that includes the /chrome/chrome.manifest, which is what this tutorial will do.
...And 2 more matches
Archived Mozilla and build documentation - Archive of obsolete content
calicalendarviewcontroller a calicalendarviewcontroller provides a way for a calicalendarview to create, modify, and delete items.
... chromeless [this project may not be active — check github https://github.com/mozilla/chromeless] creating a firefox sidebar extension this article describes how to create a registered sidebar for firefox 2 or greater.
... creating a skin for mozilla in order to create a skin for mozilla, you will need to know three things.
...And 2 more matches
NPP_New - Archive of obsolete content
« gecko plugin api reference « plug-in side plug-in api summary creates a new instance of a plug-in.
...values: np_embed: (1) instance was created by an embed tag and shares the browser window with other content.
... np_full: (2) instance was created by a separate file and is the primary content in the window.
...And 2 more matches
What is RSS - Archive of obsolete content
rss is almost never written by hand; it is almost always created by server-side software (usually written in a language like php, java, c#, or python) on the web server.
...netscape's rss 0.91 was created to simplify things.
...y 2005 09:55:59 -0500</pubdate> <link>http://joe-blow.example.net/log/19</link> </item> <item> <title>black cat spotted</title> <guid>http://joe-blow.example.net/log/18</guid> <pubdate>fri, 13 may 2005 13:13:13 -0500</pubdate> <link>http://joe-blow.example.net/log/18</link> </item> </channel> </rss> those who create internet radio use rss to allow users to access their shows.
...And 2 more matches
Introduction to SSL - Archive of obsolete content
using all data generated in the handshake so far, the client (with the cooperation of the server, depending on the cipher being used) creates the premaster secret for the session, encrypts it with the server's public key (obtained from the server's certificate, sent in step 2), and sends the encrypted premaster secret to the server.
... in the case of client authentication, the client encrypts some random data with the client's private key-that is, it creates a digital signature.
... the ssl protocol requires the client to create a digital signature by creating a one-way hash from data generated randomly during the handshake and known only to the client and server.
...And 2 more matches
JavaArray - Archive of obsolete content
created by any java method which returns an array.
... in addition, you can create a javaarray with an arbitrary data type using the newinstance method of the array class: public static object newinstance(class componenttype, int length) throws negativearraysizeexception description the javaarray object is an instance of a java array that is created in or passed to javascript.
...in addition, the tostring method is inherited from the object object and returns the following value: [object javaarray] you must specify a class object, such as one returned by java.lang.object.forname, for the componenttype parameter of newinstance when you use this method to create an array.
...And 2 more matches
JavaClass - Archive of obsolete content
created by a reference to the class name used with the packages object: packages.javaclass javaclassis the fully-specified name of the object's java class.
... the liveconnect java, sun, and netscape objects provide shortcuts for commonly used java packages and also create javaclass objects.
... backward compatibility javascript 1.3 and earlier you must create a wrapper around an instance of java.lang.class before you pass it as a parameter to a java method -- javaclass objects are not automatically converted to instances of java.lang.class.
...And 2 more matches
Reference - Archive of obsolete content
inheritance and private variables the guide section links to an interesting document discussing how to create and use private variables in objects, which is great if you want to protect the various properties within an object from being poked at accidentally.
...--maian 02:07, 26 aug 2005 (pdt) oh, i don't think so, but you can ask dria to create a css class for that.
...but when we create a prototype method for object its also available in function object.prototype.myfunction = function() {}; alert(object.myfunction); //available in object alert(function.myfunction); //available in function also the opposite is correct, when we create a prototype method for function it is available in object function.prototype.myfunction = function() {}; alert(object.myfunction); //available...
...And 2 more matches
Game distribution - Game development
you've followed a tutorial or two and created an html5 game — that's great!
... this article covers all you need to know about the ways in which you can distribute your newly created game into the wild.
... if you're working on a side project just for fun, then leaving the source open will benefit those who would like to learn from what you've created.
...And 2 more matches
Game promotion - Game development
website and blog you should definitely create your own website containing all the information about your games, so people can see what you've worked on.
... while you can create your website from scratch, there are also tools that can help make the process easier.
... manakeep is a website builder made for indie game developers and provides a great starting point to create your website.
...And 2 more matches
Mobile touch controls - Game development
an additional advantage of using phaser is that the buttons you create will take any type of input, whether it's a touch on mobile or a click on desktop — the framework sorts this out in the background for you.
... implementation the easiest way to add an interactive object that will listen for user input is to create a button: var buttonenclave = this.add.button(10, 10, 'logo-enclave', this.clickenclave, this); this one is formed in the mainmenu state — it will be placed ten pixels from the top left corner of the screen, use the logo-enclave image, and execute the clickenclave() function when it is touched.
... for the actual gameplay, instead of creating more buttons and covering the small mobile screen with them, we can use something a little bit different: we'll create invisible areas which respond to the given action.
...And 2 more matches
Initialize the framework - Game development
before we can start writing the game's functionality, we need to create a basic structure to render the game inside.
...using your favourite text editor, create a new html document, save it as index.html, in a sensible location, and add the following code to it: <!doctype html> <html> <head> <meta charset="utf-8" /> <title>gamedev phaser workshop - lesson 01: initialize the framework</title> <style>* { padding: 0; margin: 0; }</style> <script src="js/phaser.min.js"></script> </head> <body> <script> var game = new phaser.game(480, 320, phaser.canvas, null, { preload: preload, create: create, update: update }); function preload() {} ...
... function create() {} function update() {} </script> </body> </html> downloading the phaser code next, we need to go through the process of downloading the phaser source code and applying it to our html document.
...And 2 more matches
Player paddle and controls - Game development
we need a way to introduce gameplay, so in this article we'll create a paddle to move around and hit the ball with.
... rendering the paddle, with physics next up, we will init our paddle by adding the following add.sprite() call inside the create() function — add it right at the bottom: paddle = game.add.sprite(game.world.width*0.5, game.world.height-5, 'paddle'); we can use the world.width and world.height values to position the paddle exactly where we want it: game.world.width*0.5 will be right in the middle of the screen.
... in our case the world is the same as the canvas, but for other types of games, like side-scrollers for example, the world will be bigger, and you can tinker with it to create interesting effects.
...And 2 more matches
Visual-js game engine - Game development
external licences in this project : webcam nui control is under : created by romuald quantin.
... 1) click create application 2) enter new application name in input prompt 3) select folder for server part of application (important : www is not secure place) 4) select folder for client part of application ( any path in www) 5) new app name will appear in project list , select and click open application 6) open your server folder : install node.js modules one way - use windows bat-s file (in server r...
...see video explanation : if you use editor.js to visual create game object method , you must start ***node build_from_editor_to_visual_js_file.js*** on the end of work.
...And 2 more matches
CSS and JavaScript accessibility best practices - Learn web development
complex functionality like 3d games are not so easy to make accessible — a complex 3d game created using webgl will be rendered on a <canvas> element, which has no facility at this time to provide text alternatives or other information for severely visually impaired users to make use of.
...validation when the form is submitted — this is so that we don't update the ui too often and potentially confuse screen reader (and possibly other) users: form.onsubmit = validate; function validate(e) { errorlist.innerhtml = ''; for(let i = 0; i < formitems.length; i++) { const testitem = formitems[i]; if(testitem.input.value === '') { errorfield.style.left = '360px'; createlink(testitem); } } if(errorlist.innerhtml !== '') { e.preventdefault(); } } note: in this example, we are hiding and showing the error message box using absolute positioning rather than another method such as visibility or display, because it doesn't interfere with the screen reader being able to read content from it.
...if there are errors (if(errorlist.innerhtml !== '')) then we stop the form submitting (using preventdefault()), and display any error messages that have been created (see below).
...And 2 more matches
HTML: A good basis for accessibility - Learn web development
page layouts in the bad old days, people used to create page layouts using html tables — using different table cells to contain the header, footer, sidebar, main content column, etc.
... table layouts are a relic of the past — they made sense back when css support was not widespread in browsers, but now they just create confusion for screen reader users.
... another consideration when creating layouts is using html5 semantic elements as seen in the above example (see content sectioning) — you can create a layout using only nested <div> elements, but it is better to use appropriate sectioning elements to wrap your main navigation (<nav>), footer (<footer>), repeating content units (<article>), etc.
...And 2 more matches
HTML: A good basis for accessibility - Learn web development
page layouts in the bad old days, people used to create page layouts using html tables — using different table cells to contain the header, footer, sidebar, main content column, etc.
... table layouts are a relic of the past — they made sense back when css support was not widespread in browsers, but now they just create confusion for screen reader users.
... another consideration when creating layouts is using html5 semantic elements as seen in the above example (see content sectioning) — you can create a layout using only nested <div> elements, but it is better to use appropriate sectioning elements to wrap your main navigation (<nav>), footer (<footer>), repeating content units (<article>), etc.
...And 2 more matches
WAI-ARIA basics - Learn web development
we talked about some of the problems that prompted wai-aria to be created earlier on, but essentially, there are four main areas that wai-aria is useful in: signposts/landmarks: aria's role attribute values can act as landmarks that either replicate the semantics of html5 elements (e.g.
... accessibility of non-semantic controls: when a series of nested <div>s along with css/javascript is used to create a complex ui-feature, or a native control is greatly enhanced/changed via javascript, accessibility can suffer — screenreader users will find it difficult to work out what the feature does if there are no semantics or other clues.
... accessibility of non-semantic controls this follows on from the previous section — when a series of nested <div>s along with css/javascript is used to create a complex ui-feature, or a native control is greatly enhanced/changed via javascript, not only can keyboard accessibility suffer, but screenreader users will find it difficult to work out what the feature does if there are no semantics or other clues.
...And 2 more matches
Test your skills: Selectors - Learn web development
try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor.
...And 2 more matches
CSS building blocks - Learn web development
just looking at it, consuming the content.) a basic work environment set up as detailed in installing basic software, and an understanding of how to create and manage files, as detailed in dealing with files.
... note: if you are working on a computer/tablet/another device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as jsbin or glitch.
...the sub-articles are as follows: type, class, and id selectors attribute selectors pseudo-classes and pseudo-elements combinators the box model everything in css has a box around it, and understanding these boxes is key to being able to create layouts with css, or to align items with other items.
...And 2 more matches
Test your skills: Flexbox - Learn web development
below are four common design patterns which you might use flexbox to create, your task is to build them.
... try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: additional questions: can you now make the first item twice the size of the other items?
...And 2 more matches
Test your skills: Multicol - Learn web development
multicol one in this task you need to create three columns, with a 50px gap between each column.
... try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor.
... multicol two create columns which have a minimum width of 200px.
...And 2 more matches
The web and web standards - Learn web development
they received a fair amount of interest, enough to convince timbl's bosses to allow him to go ahead and create a global hypertext system.
... by late 1990, timbl had created all the things needed to run the first version of the web — http, html, the first web browser, which was called worldwideweb, an http server, and some web pages to look at.
... in the next few years that followed, the web exploded, with multiple browsers being released, thousands of web servers being set up, and millions of web pages being created.
...And 2 more matches
Creating hyperlinks - Learn web development
anatomy of a link a basic link is created by wrapping the text or other content, see block level links, inside an <a> element and using the href attribute, also known as a hypertext reference, or target, that contains the web address.
... active learning: creating your own example link create an html document using your local code editor and our getting started template.
...with a download link to the latest windows version of firefox: <a href="https://download.mozilla.org/?product=firefox-latest-ssl&os=win64&lang=en-us" download="firefox-latest-64bit-installer.exe"> download latest firefox for windows (64-bit) (english, us) </a> active learning: creating a navigation menu for this exercise, we'd like you to link some pages together with a navigation menu to create a multi-page website.
...And 2 more matches
Responsive images - Learn web development
vector images are great for simple graphics, patterns, interface elements, etc., but it starts to get very complex to create a vector-based image with the kind of detail that you'd find in say, a photo.
... note: the new features discussed in this article — srcset/sizes/<picture> — are all supported in release versions of modern desktop and mobile browsers (including microsoft's edge browser, although not internet explorer.) how do you create responsive images?
...create a web-sized version of it using a graphics editor, then crop it to show a smaller part that zooms in on the detail, and create a second image (about 480px wide is good for this).
...And 2 more matches
HTML table basics - Learn web development
LearnHTMLTablesBasics
the smallest container inside a table is a table cell, which is created by a <td> element ('td' stands for 'table data').
...each <td> element creates a single cell and together they make up the first row.
... place the four cells you've already created inside <tr> tags, like so: <tr> <td>hi, i'm your first cell.</td> <td>i'm your second cell.</td> <td>i'm your third cell.</td> <td>i'm your fourth cell.</td> </tr> now you've made one row, have a go at making one or two more — each row needs to be wrapped in an additional <tr> element, with each cell contained in a <td>.
...And 2 more matches
Build your own function - Learn web development
finally, add the following code inside the curly braces: const html = document.queryselector('html'); const panel = document.createelement('div'); panel.setattribute('class', 'msgbox'); html.appendchild(panel); const msg = document.createelement('p'); msg.textcontent = 'this is a message box'; panel.appendchild(msg); const closebtn = document.createelement('button'); closebtn.textcontent = 'x'; panel.appendchild(closebtn); closebtn.onclick = function() { panel.parentnode.removechild(panel); } this is quite a lot of c...
... the first line uses a dom api function called document.queryselector() to select the <html> element and store a reference to it in a constant called html, so we can do things to it later on: const html = document.queryselector('html'); the next section uses another dom api function called document.createelement() to create a <div> element and store a reference to it in a constant called panel.
...we need to do this as the element we created won't just appear on the page on its own — we need to specify where to put it.
...And 2 more matches
Test your skills: Functions - Learn web development
functions 1 for the first task, you have to create a simple function — choosename() — that prints a random name from the provided array (names) to the provided paragraph (para), and then run it once.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... functions 2 for our second functions-related task, you need to create a function that draws a rectangle on the provided <canvas> (reference variable canvas, context available in ctx), based on the five provided input variables: x — the x coordinate of the rectangle.
...And 2 more matches
Fetching data from the server - Learn web development
add the following lines inside your updatedisplay() function: verse = verse.replace(" ", ""); verse = verse.tolowercase(); let url = verse + '.txt'; to begin creating an xhr request, you need to create a new request object using the xmlhttprequest() constructor.
...(if you didn't work through the previous exercise, create a new directory and inside it make copies of xhr-basic.html and the four text files — verse1.txt, verse2.txt, verse3.txt, and verse4.txt.) inside the updatedisplay() function, find the xhr code: let request = new xmlhttprequest(); request.open('get', url); request.responsetype = 'text'; request.onload = function() { poemdisplay.textcontent = request.response; }; request.send(); ...
...we have created a sample site called the can store — it's a fictional supermarket that only sells canned goods.
...And 2 more matches
Silly story generator - Learn web development
basic setup: create a new file called main.js, in the same directory as your index.html file.
... completing the result() function: create a new variable called newstory, and set its value to equal storytext.
... this is needed so we can create a new random story each time the button is pressed and the function is run.
...And 2 more matches
Introducing JavaScript objects - Learn web development
you can even create your own objects to encapsulate related functions and variables into efficient packages and act as handy data containers.
...here we teach object theory and syntax in detail, then look at how to create your own objects.
... note: if you are working on a computer/tablet/other devices where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as jsbin or glitch.
...And 2 more matches
Aprender y obtener ayuda - Learn web development
some of the articles will be tutorials, to teach you a certain technique or important concept (such as "learn how to create a video player" or "learn the css box model"), and some of the articles will be reference material, to allow you to look up details you may have forgotten (such as "what is the syntax of the css background property"?) mdn web docs is very good for both types — the area you are currently in is great for learning techniques and concepts, and we also have several giant reference sections allowing...
... making a plan it is a good idea to create a plan to help you achieve what you want to achieve through your learning.
... for example, if you are looking at a task of "build a simple two-column website", you could break it down as follows: create the html structure work out basic site typography work out a basic color scheme implement a high-level layout — header, horizontal navigation menu, main content area with main and side columns, and footer.
...And 2 more matches
Introduction to the server side - Learn web development
on a dynamic website html pages are normally created by inserting data from a database into placeholders in html templates (this is a much more efficient way of storing large amounts of content than using static websites).
... requests for static resources are handled in the same way as for static sites (static resources are any files that don't change —typically: css, javascript, images, pre-created pdf files etc).
... server-side programming is very useful because it allows us to efficiently deliver information tailored for individual users and thereby create a much better user experience.
...And 2 more matches
Framework main features - Learn web development
when used with react, the jsx from the previous snippet would be compiled into this: var subject = "world"; var header = react.createelement("header", null, react.createelement("h1", null, "hello, ", subject, "!") ); when ultimately rendered by the browser, the above snippet will produce html that looks like this: <header> <h1>hello, world!</h1> </header> handlebars the handlebars templating language is not specific to ember applications, but it is heavily utilized in ember apps.
...you might create an authorcredit component to go with each article.
...let’s update our counterbutton code from above to allow it to count clicks: function counterbutton() { const [count, setcount] = usestate(0); return ( <button onclick={() => setcount(count + 1)}>clicked {count} times</button> ); } in this version we are using additional usestate() functionality to create a special setcount() function, which we can invoke to update the value of count.
...And 2 more matches
React interactivity: Editing, filtering, conditional rendering - Learn web development
we're about to create this.
...still in todo.js, put the following underneath the existing hook: const [newname, setnewname] = usestate(''); next, create a handlechange() function that will set the new name; put this underneath the hooks but before the templates: function handlechange(e) { setnewname(e.target.value); } now we'll update our editingtemplate's <input /> field, setting a value attribute of newname, and binding our handlechange() function to its onchange event.
... update it as follows: <input id={props.id} classname="todo-text" type="text" value={newname} onchange={handlechange} /> finally, we need to create a function to handle the edit form’s onsubmit event; add the following just below the previous function you added: function handlesubmit(e) { e.preventdefault(); props.edittask(props.id, newname); setnewname(""); setediting(false); } remember that our edittask() callback prop needs the id of the task we're editing as well as its new name.
...And 2 more matches
React resources - Learn web development
create-react-app makes it possible to import css files into javascript modules, so that css is only sent to your user when the corresponding component is rendered.
... you can read more about component stylesheets in the create-react-app docs.
... state and lifecycle in the react docs intro to react in the react docs read about javascript classes at mdn testing create-react-app provides some tools for testing your application out of the box — you may have deleted the relevant files earlier in the tutorial.
...And 2 more matches
Handling common JavaScript problems - Learn web development
when clicked, each one should alert a message containing its number (the value of i at the time it was created), however each one reports i as 11, because for loops do all their iterating before nested functions are invoked.
...<script> element so they will be available on the page already when we start trying to use fetch: <script src="es6-promise.js"></script> <script src="fetch.js"></script> inside the original <script>, add the following code: const myimage = document.queryselector('.my-image'); fetch('flowers.jpg').then(function(response) { response.blob().then(function(myblob) { let objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); }); now if you load it in a browser that doesn't support fetch (safari and ie are obvious candidates), you should still see the flower image appear — cool!
...loadscript() looks like this: function loadscript(src, done) { const js = document.createelement('script'); js.src = src; js.onload = function() { done(); }; js.onerror = function() { done(new error('failed to load script ' + src)); }; document.head.appendchild(js); } this function creates a new <script> element, then sets its src attribute to the path we specified as the first argument ('polyfills.js' when we called it in the code above).
...And 2 more matches
Creating a Language Pack
to create a language pack, or a localization repack, you first need to go through the initial setup process.
... every time you want to create a langpack, you need to be in the directory obj-firefox-build/browser/locales.
... x-testing: changed: 6 missinginfiles: 6124 missing: 5 0% of entries changed this step is not necessary anymore to create the language pack, because it is included in the next command.
...And 2 more matches
Embedding the editor
current problems the current composer architecture was created while other parts of mozilla were still under development, and as a result it suffers from a number of shortcomings, and anachronisms.
...editor incorrectly rooted the editor in a composer window is current owned by the nseditorshell, which in turn is created, owned and destroyed by the nseditorboxobject.
...xbl creates an nseditorboxobject for each <editor> tag, and allows javascript to access properties of this box object (such as the nsieditorshell).
...And 2 more matches
How to implement a custom autocomplete search component
the xul textbox element supports an autocomplete mechanism that is used to create a textbox with a popup containing a list of possible completions for what the user has started to type.
...to do so you need the following: create an xpcom component that implements the nsiautocompletesearch interface.
... = new providerautocompleteresult(searchstring, ci.nsiautocompleteresult.result_success, 0, "", results, null); listener.onsearchresult(this, autocomplete_result); }, /** * stops an asynchronous search that is in progress */ stopsearch: function() { }, queryinterface: xpcomutils.generateqi([ ci.nsiautocompletesearch ]) }; // the following line is what xpcom uses to create components const nsgetfactory = xpcomutils.generatensgetfactory([ providerautocompletesearch ]); then register your xpcom component.
...And 2 more matches
IPDL Tutorial
it is the responsibility of the implementor to create subclasses to perform the actual work involved in each message.
... struct namevaluepair { nscstring name; nscstring value; }; in implementation code, these structs can be created and used like so: namevaluepair entry(astring, anotherstring); foo(entry.name(), entry.value()); // named accessor functions return references to the members arrays ipdl has simple syntax for arrays: invokemethod(nscstring[] args); in c++ this is translated into a nstarray reference: virtual bool recvinvokemethod(nstarray<nscstring>& args); ipdl's generated data structures can be us...
...a protocol hierarchy begins with a single top-level protocol from which all subprotocol actors are eventually created.
...And 2 more matches
NetUtil.jsm
get("tmpd", ci.nsifile); file.append("test-file.tmp"); file.createunique(ci.nsifile.normal_file_type, 0666); // then, we need an output stream to our output file.
... createinstance(ci.nsifileoutputstream); ostream.init(file, -1, -1, 0); // finally, we need an input stream to take data from.
... createinstance(ci.nsistringinputstream); istream.setdata(test_data, test_data.length); netutil.asynccopy(istream, ostream, function(aresult) { if (!components.issuccesscode(aresult)) { // an error occurred!
...And 2 more matches
Promise.jsm
if you need a deferred, because you want to create a promise and manually resolve or reject it, consider using promiseutils.jsm instead.
... promises may also be created using the new promise() constructor.
... method overview deferred defer(); obsolete since gecko 30 promise resolve([optional] avalue); promise reject([optional] areason); methods defer() creates a new pending promise and provides methods to resolve or reject it.
...And 2 more matches
Using JavaScript code modules
modules can also be used to create global javascript singletons that previously required using javascript xpcom objects.
... creating a javascript code module a very simple javascript module looks like this: var exported_symbols = ["foo", "bar"]; function foo() { return "foo"; } var bar = { name : "bar", size : 3 }; var dummy = "dummy"; notice that the module uses normal javascript to create functions, objects, constants, and any other javascript type.
... scope 1: components.utils.import("resource://app/my_module.jsm"); alert(bar.size + 3); // displays "6" bar.size = 10; scope 2: components.utils.import("resource://app/my_module.jsm"); alert(foo()); // displays "foo" alert(bar.size + 3); // displays "13" this sharing behavior can be used to create singleton objects that can share data across windows and between xul script and xpcom components.
...And 2 more matches
Localizing with Mozilla Translator
if you are a ''not so good'' mt user, however, you can just create a new product (or several ones; see next recipe to know why), run file -> update on them (you'll get a list of all the strings) and then run edit -> autotranslate.
... the first thing to do, once you have your mercurial local repository up and working, is create a new product...
...these are your options: create one product for each ''root'' directories.
...And 2 more matches
Investigating leaks using DMD heap scan mode
if you have a patch that introduces a leak, you are probably better off auditing all of the strong references that your patch creates before trying this.
...the command you need to run firefox will look something like this: xpcom_mem_bloat_log=1 moz_cc_log_shutdown=1 moz_disable_content_sandbox=t moz_cc_log_directory=$logdir moz_cc_log_process=content moz_cc_log_thread=main moz_dmd_shutdown_log=$logdir moz_dmd_log_process=tab ./mach run --dmd --mode=scan breaking this down: xpcom_mem_bloat_log=1: this reports a list of the counts of every object created and destroyed and tracked by the xpcom leak tracking system.
...a garbage collector log will also be created, which you may not need.
...And 2 more matches
McCoy
this is located in: %appdata%\mozilla\mccoy (windows) ~/.mozilla/mccoy (linux) ~/library/application support/mccoy (mac os x) it is highly recommended that you back up your profile folder and store it in a safe location whenever you create a new key; without a backup, there is no way to recover your private keys if they are lost!
...the first time it runs it will ask you to create a master password.
... the first step is to create a cryptographic key.
...And 2 more matches
Anonymous Shared Memory
in the first protocol, the job of passing the inheritable shared memory is done via helper-functions with pr_createprocess.
...in the examples, the server creates the file-mapped shared memory, the client attaches to it.
... first protocol server: fm = pr_openanonfilemap(dirname, size, filemapprot); addr = pr_memmap(fm); attr = pr_newprocessattr(); pr_processattrsetinheritablefilemap( attr, fm, shmname ); pr_createprocess(client); pr_destroyprocessattr(attr); ...
...And 2 more matches
Introduction to NSPR
a thread is created by an explicit client request and remains a valid, independent execution entity until it returns from its root function or the process abnormally terminates.
... in general, it's preferable to create local user threads with normal priority and let nspr take care of the details as appropriate for each host os.
... it's usually not necessary to create a global thread explicitly unless you are planning to port your code only to platforms that provide threading services with which you are familiar or unless the thread will be executing code that might directly call blocking os functions.
...And 2 more matches
PRThreadState
threads created with a pr_unjoinable_thread state cannot be used as arguments to pr_jointhread.
... the lifetime of a thread extends from the time it is created to the time it returns from its root function.
... what happens when it returns from its root function depends on the thread state passed to pr_createthread when the thread was created.
...And 2 more matches
PR_MkDir
creates a directory with a specified name and access mode.
... syntax #include <prio.h> prstatus pr_mkdir( const char *name, printn mode); parameters the function has the following parameters: name the name of the directory to be created.
... mode the access permission bits of the file mode of the new directory if the file is created when pr_create_file is on.
...And 2 more matches
Threads
a thread is created by an explicit client request and remains a valid, independent execution entity until it returns from its root function or the process abnormally terminates.
... creating, joining, and identifying threads controlling thread priorities interrupting and yielding setting global thread concurrency getting a thread's scope creating, joining, and identifying threads pr_createthread creates a new thread.
... you set a thread's nspr priority when you create it with pr_createthread.
...And 2 more matches
HTTP delegation
http://ocsp.provider.com:80/cgi-bin/ocsp-responder if nss needs to access a http server, it will request that an "http server session object" be created (sec_httpserver_createsessionfcn).
...(nss might choose to be smart, and only create a single http server session object for each server encountered.
...should the application be unable to keep a physical connection alive all the time, the application is expected to create new connections automatically.
...And 2 more matches
HTTP delegation
http://ocsp.provider.com:80/cgi-bin/ocsp-responder if nss needs to access a http server, it will request that an "http server session object" be created (sec_httpserver_createsessionfcn).
...(nss might choose to be smart, and only create a single http server session object for each server encountered.
...should the application be unable to keep a physical connection alive all the time, the application is expected to create new connections automatically.
...And 2 more matches
nss tech note5
if not using cbc mode, just pass a null iv parm to pk11_paramfromiv function secitem ivitem; ivitem.data = /* ptr to an array of iv bytes */ ivitem.len = /* length of the array of iv bytes */ secitem *secparam = pk11_paramfromiv(ciphermech, &ivitem);</big> <big>now encrypt and decrypt using the key and parameter setup in above steps</big> create encryption context pk11context* enccontext = pk11_createcontextbysymkey(ciphermech, cka_encrypt or cka_decrypt, symkey, secparam); do the operation.
... you can also look at a sample program illustrating encryption hash / digest include headers #include "nss.h" #include "pk11pub.h" make sure nss is initialized.the simplest init function, in case you don't need a nss database is nss_nodb_init(".") <big>create digest context</big>.
... pk11context* digestcontext = pk11_createdigestcontext(sec_oid_md5); <big>digest the data</big> <big>secstatus s = pk11_digestbegin(digestcontext); s = pk11_digestop(digestcontext, data, sizeof data); s = pk11_digestfinal(digestcontext, digest, &len, sizeof digest); /* now, digest contains the 'digest', and len contains the length of the digest */</big> clean up pk11_destroycontext(digestcontext, pr_true); you can also look at a sample program illustrating this hash / digest with secret key included include headers #include "nss.h" #include "pk11pub.h" make sure nss is initialized.the simplest init function, in case you don't nee...
...And 2 more matches
Python binding for NSS
it's not possible for the binding to know in all cases, especially if the socket is created from an xternal socket passed in.
... release 0.17.0 release date 2014-11-07 scm tag pynss_release_0_17_0 source download https://ftp.mozilla.org/pub/mozilla.org/security/python-nss/releases/pynss_release_0_17_0/src/ change log the primary enhancement in this version is adding support for pbkdf2 the following module functions were added: nss.create_pbev2_algorithm_id the following class methods were added: nss.algorithmid.get_pbe_crypto_mechanism nss.algorithmid.get_pbe_iv nss.pk11slot.pbe_key_gen nss.pk11slot.format_lines nss.pk11slot.format nss.pk11symkey.format_lines nss.pk11symkey.format nss.secitem.to_base64 nss.secitem.format_lines nss.secit...
... setup_certs now creates a new sql sytle nss database (sql:pki) all tests and examples now load the sql:pki database.
...And 2 more matches
JS::CloneFunctionObject
this article covers features introduced in spidermonkey 38 create a new function object from an existing jsfunction.
... description js::clonefunctionobject creates a new function object from funobj.
...if scopechain is omitted, it creates a new function object in cx's global.
...And 2 more matches
JS_AliasProperty
create an alias for a native property.
... obj jsobject * object for which to create the alias.
... name const char * name of the property for which to create an alias.
...And 2 more matches
JS_DefineProperties
ps const jspropertyspec * pointer to the first element of an array containing names, ids, flags, and getproperty and setproperty method for the properties to create.
... description js_defineproperties creates properties on a specified object, obj.
...js_defineproperties creates one property for each element in the array before the element with a null name field.
...And 2 more matches
JS_NewArrayObject
create a new array object.
...yntax jsobject * js_newarrayobject(jscontext *cx, const js::handlevaluearray& contents); // added in spidermonkey 31 jsobject * js_newarrayobject(jscontext *cx, size_t length); // added in spidermonkey 31 jsobject * js_newarrayobject(jscontext *cx, int length, jsval *vector); // obsolete since jsapi 30 name type description cx jscontext * the context in which to create the new array.
...obsolete since jsapi 30 description js_newarrayobject with contents parameter creates a new array object with the specified contents elements.
...And 2 more matches
JS_NewObjectForConstructor
convenience function to create a new object exactly as a constructor function would.
...cx, const jsclass *clasp, const js::callargs& args); // added in jsapi 32 jsobject * js_newobjectforconstructor(jscontext *cx, jsclass *clasp, const jsval *vp); // added in jsapi 14, obsolete since jsapi 32 jsobject * js_newobjectforconstructor(jscontext *cx, const jsval *vp); // obsolete since jsapi 14 name type description cx jscontext * the context in which to create the new object.
... clasp const jsclass * the class of the object to create.
...And 2 more matches
JS_NewRegExpObject
create a new regexp object.
... unsigned flags); jsobject * js_newregexpobjectnostatics(jscontext *cx, char *bytes, size_t length, unsigned flags); jsobject * js_newucregexpobjectnostatics(jscontext *cx, char16_t *chars, size_t length, unsigned flags); name type description cx jscontext * the context in which to create the new object.
... i jsreg_glob global execution, creates array of matches.
...And 2 more matches
Embedded Dialog API
but it must be allowed to create additional windows at times perhaps unexpected by the containing appliction.
...its simplest requirements are that the app must allow gecko to create new browser windows and new simple, empty windows.
...this basic api will by itself provide the minimal functionality gecko needs to create new windows, and an embedding application must implement at least this much.
...And 2 more matches
Using XPCOM Utilities to Make Things Easier
« previousnext » this chapter goes back over the code you've already created in the first part of the tutorial (see weblock1.cpp in the previous chapter) and uses xpcom tools that make coding a lot easier and more efficient.
...much of the code created to get the software recognized and registered as a component can be reduced to a small data structure and a single macro.
... the module macros include one set of macros that define the exported nsgetmodule entry point, the required nsimodule implementation code and another that creates a generic factory for your implementation class.
...And 2 more matches
Components.classes
usage in order to retrieve the object for a given contractid, you can query the components.classes array as follows: var clazz0 = components.classes["@mozilla.org/messenger;1"]; clazz0 is the class object for the contractid @mozilla.org/messenger;1, which is not usually used by itself, but whose createinstance and getservice methods can be used to create a new instance of the component or to access the singleton instance, if the contract id represents a service.
... a new xpcom component instance can be created from the returned class object as follows: var obj = components.classes["@mozilla.org/supports-array;1"] .createinstance(components.interfaces.nsisupportsarray); which is a shortcut to var obj = components.classes["@mozilla.org/supports-array;1"] .createinstance(); obj.queryinterface(components.interfaces.nsisupportsarray); if you don't provide a specific interface to createinstance(), it will return an xpconnect wrapper for the component, which only exposes the methods of the nsisupports interface (and under certain circumstances the special wrappedjsobject property).
... to access a service (a singleton component, only single instance of which exists at any time), you should use getservice instead of createinstance: var os = components.classes["@mozilla.org/observer-service;1"] .getservice(components.interfaces.nsiobserverservice); the first time anyone accesses a service, the corresponding component is created under the hood.
...And 2 more matches
mozIStorageService
storage/public/mozistorageservice.idlscriptable this interface lets you open a mozistorageconnection to a database file, as well as create backups of an unopened database file.
... return value an nsifile object representing the newly-created backup file.
...the specified file is created if it does not already exist.
...And 2 more matches
nsIAccessibleEvent
constants constant gecko version description 1.7 - 1.8.1 1.9 - 1.9.2 2.0 event_show 0x8002 0x0001 an object has been created.
... event_table_column_insert 0x0046 0x0042 event_table_column_delete 0x0047 0x0043 event_table_column_reorder 0x0048 0x0044 event_window_activate 0x0049 0x0045 event_window_create 0x004a 0x0046 event_window_deactivate 0x004b 0x0047 event_window_destroy 0x004c 0x0048 event_window_maximize 0x004d 0x0049 event_window_minimize 0x004e 0x004a event_window_resize 0x004f 0x004b event_window_restore 0x0050 0x004c event_hyperlink_end_index_changed 0x0051 0x004d the ending index of this link within the containing string has changed.
... event_create 0x8000 event_destroy 0x8001 event_descriptionchange 0x800d event_parentchange 0x800f event_helpchange 0x8010 event_defactionchange 0x8011 event_acceleratorchange 0x8012 event_menustart 0x0004 event_menuend 0x0005 event_menupopupstart 0x0006 event_menupopupend 0x0007 event_capturestart 0x0008 event_captureend 0x0009 even...
...And 2 more matches
nsIComponentManager
66 introduced gecko 0.7 inherits from: nsisupports last changed in gecko 8.0 (firefox 8.0 / thunderbird 8.0 / seamonkey 2.5) method overview void addbootstrappedmanifestlocation(in nsilocalfile alocation); void createinstance(in nscidref aclass, in nsisupports adelegate, in nsiidref aiid, [iid_is(aiid),retval] out nsqiresult result); void createinstancebycontractid(in string acontractid, in nsisupports adelegate, in nsiidref aiid, [iid_is(aiid),retval] out nsqiresult result); void getclassobject(in nscidref aclass, in nsiidref aiid, [iid_is(aiid),retval] out nsqiresult result); void ...
... createinstance() creates an instance of the class specified by classid.
...(see also nsifactory.createinstance.) void createinstance( in nscidref aclass, in nsisupports adelegate, in nsiidref aiid, [iid_is(aiid),retval] out nsqiresult result ); parameters aclass the classid of the object instance that is being requested.
...And 2 more matches
nsIFilePicker
to create an instance, use: var filepicker = components.classes["@mozilla.org/filepicker;1"] .createinstance(components.interfaces.nsifilepicker); method overview void appendfilter(in astring title, in astring filter); void appendfilters(in long filtermask); void init(in nsidomwindow parent, in astring title, in short mode); void open(in nsifilepickershowncallback afilepicker...
... constants mode constants these constants are used to specify the type of file picker to create when calling init().
... constant value description returnok 0 the file picker dialog was closed by the user hitting 'ok' returncancel 1 the file picker dialog was closed by the user hitting 'cancel' returnreplace 2 the user chose an existing file and acknowledged that they want to overwrite the file filter constants these constants are used to create filters for commonly-used file types.
...And 2 more matches
nsIINIParserFactory
xpcom/ds/nsiiniparser.idlscriptable this interface is used to create nsiiniparser objects for use in parsing ini files.
...method overview nsiiniparser createiniparser(in nsilocalfile ainifile); methods createiniparser() creates an ini parser, returning the nsiiniparser object that you can use to parse it.
... nsiiniparser createiniparser( in nsilocalfile ainifile ); parameters ainifile the ini file to parse.
...And 2 more matches
nsIMacDockSupport
to create an instance, use: var dock = components.classes["@mozilla.org/widget/macdocksupport;1"] .getservice(components.interfaces.nsimacdocksupport); see working with the mac os x dock for details and examples.
...this is created by using the dockmenu attribute of nsimacdocksupport here: http://mxr.mozilla.org/mozilla-release/source/browser/base/content/browser.js#1562 this is seen here: if you were to copy and follow that example you would replace the default native menu.
... this can be done like this: var docksupport = cc['@mozilla.org/widget/macdocksupport;1'].getservice(ci.nsimacdocksupport); console.log('docksupport:', docksupport); var win = services.wm.getmostrecentwindow('navigator:browser'); var macmenu = win.document.createelementns('http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul', 'menupopup'); macmenu.setattribute('id', 'mymacmenu'); var macmenuitem = win.document.createelementns('http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul', 'menuitem'); macmenuitem.setattribute('label', 'show most recent window'); macmenuitem.setattribute('id', 'mymacmenuitem'); macmenuitem.addeventlistener('command', function(){ var docksupport = cc['@mozilla.org/widget/macdocksupport;1'].getservice(ci.nsimacdocksupport); docksupport.activateappli...
...And 2 more matches
nsIMsgDBHdr
setrecipientsarray() uses the header parser to recreate the recipients header from an array of names and addresses.
... setcclistarray() users the header parser to recreate the cc header from an array of names and addresses.
... getauthorcollationkey() decodes and parses the message author and creates a collation key that can be used to efficiently sort authors case insensitively.
...And 2 more matches
nsIPushService
nsipushservice supports the push api implementation in firefox, and can be used directly from privileged code to create system subscriptions.
...e); method overview void subscribe(in domstring scope, in nsiprincipal principal, in nsipushsubscriptioncallback callback); void getsubscription(in domstring scope, in nsiprincipal principal, in nsipushsubscriptioncallback callback); void unsubscribe(in domstring scope, in nsiprincipal principal, in nsiunsubscriberesultcallback callback); methods subscribe() creates a push subscription.
... callback the callback to call when the nsipushsubscription is created.
...And 2 more matches
nsIWindowCreator
embedding/base/nsiwindowcreator.idlscriptable a callback interface used by gecko to create new browser windows.
... inherits from: nsisupports last changed in gecko 0.9.6 method overview nsiwebbrowserchrome createchromewindow(in nsiwebbrowserchrome parent, in pruint32 chromeflags); methods createchromewindow() create a new window.
... gecko will/may call this method, if made available to it, to create new windows.
...And 2 more matches
nsIWindowWatcher
windows must notify this component when they are created or destroyed, so only a weak reference is kept.
... return value an nsiwebbrowserchrome object for the corresponding chrome window getnewauthprompter() return a newly created nsiauthprompt implementation.
... getnewprompter() return a newly created nsiprompt implementation.
...And 2 more matches
Working with Multiple Versions of Interfaces
to do this i used the accessibility framework: hwnd gethwnd(nsidomnode *node){ hwnd self = null; nsresult rv; nscomptr<nsiaccessibleretrieval> refp; refp = do_createinstance( "@mozilla.org/accessibleretrieval;1", &rv); if (ns_failed(rv)){ return self; } //line 6.
...what happens is that the call to do_createinstance fails with nsresult ns_error_no_interface.
... this is because the call to do_createinstance(acid, aouter, error); will eventually evolve into a request for an object supporting the interface with iid ns_get_iid(nsiaccessibleretrieval).
...And 2 more matches
Creating a Custom Column
one of the new and exciting features available to thunderbird extension developers in thunderbird 2.0 is the ability to easily create and handle custom columns in thunderbird's main view.
...our implementation will need to call something similar to: gdbview.addcolumnhandler("colreplyto", columnhandler); setting the custom column handler we've added a special event that gets fired whenever a view is created.
... window.addeventlistener("load", doonceloaded, false); function doonceloaded() { var observerservice = components.classes["@mozilla.org/observer-service;1"].getservice(components.interfaces.nsiobserverservice); observerservice.addobserver(createdbobserver, "msgcreatedbview", false); } var createdbobserver = { // components.interfaces.nsiobserver observe: function(amsgfolder, atopic, adata) { addcustomcolumnhandler(); } } in this example we have a function addcustomcolumnhandler() that is called whenever the event is fired.
...And 2 more matches
js-ctypes reference
second, they serve as constructors to create concrete instances of the given type, i.e.
...these include ctypes.pointertype(type) and the .ptr property, which creates a new type describing a pointer to an existing type.
... ctypes.arraytype(type, [length]) and the .array() method, which creates a new type describing an array of objects of an existing type.
...And 2 more matches
Debugger.Source - Firefox Developer Tools
for scripts created by eval or the function constructor, this may be a synthesized filename, starting with a valid url and followed by information tracking how the code was introduced into the system; the entire string is not a valid url.
...thus, setting a dom element’s event handler idl attribute by assigning to the corresponding javascript property creates a source whose introductionscript and introductionoffset refer to the property assignment.
...thus, they donot refer to the call that created the element; stored the source as the element’s text child; made the element a child of some uninserted parent node that was later inserted; or the like.
...And 2 more matches
Debugger.Object - Firefox Developer Tools
spidermonkey creates exactly one debugger.object instance for each debuggee object it presents to a given debugger instance: if the debugger encounters the same object through two different routes (perhaps two functions are called on the same object), spidermonkey presents the same debugger.object instance to the debugger each time.
... while most debugger.object instances are created by spidermonkey in the process of exposing debuggee's behavior and state to the debugger, the debugger can use debugger.object.prototype.makedebuggeevalue to create debugger.object instances for given debuggee objects, or use debugger.object.prototype.copy and debugger.object.prototype.create to create new objects in debuggee compartments, allocated as if by particular debuggee globals.
... environment if the referent is a function that is debuggee code, a debugger.environment instance representing the lexical environment enclosing the function when it was created.
...And 2 more matches
AudioBuffer - Web APIs
the audiobuffer interface represents a short audio asset residing in memory, created from an audio file using the audiocontext.decodeaudiodata() method, or from raw data using audiocontext.createbuffer().
... constructor audiobuffer() creates and returns a new audiobuffer object instance.
... example the following simple example shows how to create an audiobuffer and fill it with random white noise.
...And 2 more matches
CanvasRenderingContext2D.closePath() - Web APIs
syntax void ctx.closepath(); examples closing a triangle this example creates the first two (diagonal) sides of a triangle using the lineto() method.
... after that, the triangle's base is created with the closepath() method, which automatically connects the shape's first and last points.
... note: although closepath() is called after all the arcs have been created, only the last arc (sub-path) gets closed.
...And 2 more matches
ChannelMergerNode - Web APIs
if channelmergernode has one single output, but as many inputs as there are channels to merge; the number of inputs is defined as a parameter of its constructor and the call to audiocontext.createchannelmerger.
... using a channelmergernode, it is possible to create outputs with more channels than the rendering hardware is able to process.
... number of outputs 1 channel count mode "max" channel count 2 (not used in the default count mode) channel interpretation "speakers" constructor channelmergernode() creates a new channelmergernode object instance.
...And 2 more matches
ChildNode.after() - Web APIs
WebAPIChildNodeafter
examples inserting an element var parent = document.createelement("div"); var child = document.createelement("p"); parent.appendchild(child); var span = document.createelement("span"); child.after(span); console.log(parent.outerhtml); // "<div><p></p><span></span></div>" inserting text var parent = document.createelement("div"); var child = document.createelement("p"); parent.appendchild(child); child.after("text"); console.log(parent.outerhtml); ...
...// "<div><p></p>text</div>" inserting an element and text var parent = document.createelement("div"); var child = document.createelement("p"); parent.appendchild(child); var span = document.createelement("span"); child.after(span, "text"); console.log(parent.outerhtml); // "<div><p></p><span></span>text</div>" childnode.after() is unscopable the after() method is not scoped into the with statement.
...js_piece/blob/master/dom/childnode/after()/after().md (function (arr) { arr.foreach(function (item) { if (item.hasownproperty('after')) { return; } object.defineproperty(item, 'after', { configurable: true, enumerable: true, writable: true, value: function after() { var argarr = array.prototype.slice.call(arguments), docfrag = document.createdocumentfragment(); argarr.foreach(function (argitem) { var isnode = argitem instanceof node; docfrag.appendchild(isnode ?
...And 2 more matches
ConstantSourceNode - Web APIs
number of inputs 0 number of outputs 1 constructor constantsourcenode() creates and returns a new constantsourcenode instance, optionally specifying an object which establishes initial values for the object's properties.
... you can also create a constantsourcenode whose properties are initialized to their default values by calling audiocontext.createconstantsource().
... example in the article controlling multiple parameters with constantsourcenode, a constantsourcenode is created to allow one slider control to change the gain on two gainnodes.
...And 2 more matches
ConvolverNode - Web APIs
number of inputs 1 number of outputs 1 channel count mode "clamped-max" channel count 1, 2, or 4 channel interpretation "speakers" constructor convolvernode() creates a new convolvernode object instance.
... convolvernode.buffer a mono, stereo, or 4-channel audiobuffer containing the (possibly multichannel) impulse response used by the convolvernode to create the reverb effect.
... convolvernode example the following example shows basic usage of an audiocontext to create a convolver node.
...And 2 more matches
CustomEvent - Web APIs
constructor customevent() creates a customevent.
... event.timestamp read only the time at which the event was created (in milliseconds).
... this interface inherits methods from its parent, event: event.createevent() creates a new event, which must then be initialized by calling its initevent() method.
...And 2 more matches
DOMPointReadOnly.fromPoint() - Web APIs
the static dompointreadonly method frompoint() creates and returns a new dompointreadonly object given a source point.
... you can also create a new dompointreadonly object using the new dompointreadonly() constructor.
... examples creating a 2d point this sample creates a 2d point, specifying an inline object that includes the values to use for x and y.
...And 2 more matches
DataTransferItem.webkitGetAsEntry() - Web APIs
example in this example, a drop zone is created, which responds to the drop event by scanning through the dropped files and directories, outputting a hierarchical directory listing.
... let dropzone = document.getelementbyid("dropzone"); let listing = document.getelementbyid("listing"); function scanfiles(item, container) { let elem = document.createelement("li"); elem.innerhtml = item.name; container.appendchild(elem); if (item.isdirectory) { let directoryreader = item.createreader(); let directorycontainer = document.createelement("ul"); container.appendchild(directorycontainer); directoryreader.readentries(function(entries) { entries.foreach(function(entry) { scanfiles(entry, directorycontainer); ...
...the first step is to create a filesystemdirectoryreader to handle fetching the directory's contents.
...And 2 more matches
DelayNode.delayTime - Web APIs
delaytime is expressed in seconds, its minimal value is 0, and its maximum value is defined by the maxdelaytime argument of the audiocontext.createdelay() method that created it.
... syntax var audioctx = new audiocontext(); var mydelay = audioctx.createdelay(5.0); mydelay.delaytime.value = 3.0; note: though the audioparam returned is read-only, the value it represents is not.
... example we have created a simple example that allows you to play three different samples on a constant loop — see create-delay (you can also view the source code).
...And 2 more matches
DelayNode - Web APIs
WebAPIDelayNode
number of inputs 1 number of outputs 1 channel count mode "max" channel count 2 (not used in the default count mode) channel interpretation "speakers" constructor delaynode() creates a new instance of an delaynode object instance.
... alternatively, you can use the baseaudiocontext.createdelay() factory method.
... example we have created a simple example that allows you to play three different samples on a constant loop — see create-delay (you can also view the source code).
...And 2 more matches
DirectoryReaderSync - Web APIs
basic concepts before you call the only method in this interface, readentries(), create the directoryentrysync object.
... example in the following code snippet from html5rocks, we create web workers and pass data from it to the main app.
... window.resolvelocalfilesystemurl = window.resolvelocalfilesystemurl || window.webkitresolvelocalfilesystemurl; // create web workers var worker = new worker('worker.js'); worker.onmessage = function(e) { var urls = e.data.entries; urls.foreach(function(url, i) { window.resolvelocalfilesystemurl(url, function(fileentry) { // print out file's name.
...And 2 more matches
Event - Web APIs
WebAPIEvent
nstrainederror pagetransitionevent paymentrequestupdateevent pointerevent popstateevent progressevent relatedevent rtcdatachannelevent rtcidentityerrorevent rtcidentityevent rtcpeerconnectioniceevent sensorevent storageevent svgevent svgzoomevent timeevent touchevent trackevent transitionevent uievent userproximityevent webglcontextevent wheelevent constructor event() creates an event object, returning it to the caller.
... event.timestamp read only the time at which the event was created (in milliseconds).
...this does not include nodes in shadow trees if the shadow root was created with its shadowroot.mode closed.
...And 2 more matches
EventSource - Web APIs
constructor eventsource() creates a new eventsource to handle receiving server-sent events from a specified url, optionally in credentials mode.
... additionally, the event source itself may send messages with an event field, which will create ad-hoc events keyed to that value.
... examples in this basic example, an eventsource is created to receive unnamed events from the server; a page with the name sse.php is responsible for generating the events.
...And 2 more matches
FileSystemDirectoryReader.readEntries() - Web APIs
example in this example, a drop zone is created, which responds to the drop event by scanning through the dropped files and directories, outputting a hierarchical directory listing.
... let dropzone = document.getelementbyid("dropzone"); let listing = document.getelementbyid("listing"); function scanfiles(item, container) { let elem = document.createelement("li"); elem.innerhtml = item.name; container.appendchild(elem); if (item.isdirectory) { let directoryreader = item.createreader(); let directorycontainer = document.createelement("ul"); container.appendchild(directorycontainer); directoryreader.readentries(function(entries) { entries.foreach(function(entry) { scanfiles(entry, directorycontainer); ...
...the first step is to create a filesystemdirectoryreader to handle fetching the directory's contents.
...And 2 more matches
FileSystemFlags.exclusive - Web APIs
the exclusive property on the filesystemflags dictionary is used in tandem with the create property to determine whether or not it's acceptable to require that the file not already exist when the reference to it is created by calling filesystemdirectoryentry.getfile() or filesystemdirectoryentry.getdirectory().
... option values file/directory condition result create exclusive false n/a[1] path exists and matches the desired type (depending on whether the function called is getfile() or getdirectory() the successcallback is called with a filesystemfileentry if getfile() was called or a filesystemdirectoryentry if getdirectory() was called.
... true false path doesn't exist the file or directory is created, then a filesystemfileentry or a filesystemdirectoryentry is passed to the successcallback, as appropriate.
...And 2 more matches
Introduction to the File and Directory Entries API - Web APIs
you can develop apps that can read, write, and create files and directories in a sandboxed, virtual file system.
... for examples of features you can create with this app, see the sample use cases section.
...for example, you can use the file api, create a blob, redirect an iframe to the blob, and invoke the download manager.
...And 2 more matches
IDBKeyRange - Web APIs
methods static methods idbkeyrange.bound() creates a new key range with upper and lower bounds.
... idbkeyrange.only() creates a new key range containing a single value.
... idbkeyrange.lowerbound() creates a new key range with only a lower bound.
...And 2 more matches
IDBOpenDBRequest.onupgradeneeded - Web APIs
var request = window.indexeddb.open("library", 3); // this event handles the event whereby a new version of the // database needs to be created.
... either one has not been created // before, or a new version number has been submitted via the // window.indexeddb.open line above.
... var store = db.createobjectstore("books", {keypath: "isbn"}); var titleindex = store.createindex("by_title", "title", {unique: true}); var authorindex = store.createindex("by_author", "author"); } if (event.oldversion < 2) { // version 2 introduces a new index of books by year.
...And 2 more matches
MediaStreamAudioSourceNode - Web APIs
a mediastreamaudiosourcenode has no inputs and exactly one output, and is created using the audiocontext.createmediastreamsource() method.
... number of inputs 0 number of outputs 1 channel count defined by the first audio mediastreamtrack passed to the audiocontext.createmediastreamsource() method that created it.
... constructor new mediastreamaudiosourcenode() creates a new mediastreamaudiosourcenode object instance with the specified options.
...And 2 more matches
MediaStreamTrackAudioSourceNode - Web APIs
a mediastreamtrackaudiosourcenode has no inputs and exactly one output, and is created using the audiocontext.createmediastreamtracksource() method.
... number of inputs 0 number of outputs 1 channel count defined by the first audio mediastreamtrack passed to the audiocontext.createmediastreamtracksource() method that created it.
... constructor new mediastreamtrackaudiosourcenode() creates a new mediastreamtrackaudiosourcenode object instance with the specified options.
...And 2 more matches
Using the MediaStream Recording API - Web APIs
capturing the media stream once getusermedia has created a media stream successfully, you create a new media recorder instance with the mediarecorder() constructor and pass it the stream directly.
...we register an event handler for this using mediarecorder.onstop, and finalize our blob there from all the chunks we have received: mediarecorder.onstop = function(e) { console.log("recorder stopped"); const clipname = prompt('enter a name for your sound clip'); const clipcontainer = document.createelement('article'); const cliplabel = document.createelement('p'); const audio = document.createelement('audio'); const deletebutton = document.createelement('button'); clipcontainer.classlist.add('clip'); audio.setattribute('controls', ''); deletebutton.innerhtml = "delete"; cliplabel.innerhtml = clipname; clipcontainer.appendchild(audio); clipcontainer.appendchild(cliplabel);...
... clipcontainer.appendchild(deletebutton); soundclips.appendchild(clipcontainer); const blob = new blob(chunks, { 'type' : 'audio/ogg; codecs=opus' }); chunks = []; const audiourl = window.url.createobjecturl(blob); audio.src = audiourl; deletebutton.onclick = function(e) { let evttgt = e.target; evttgt.parentnode.parentnode.removechild(evttgt.parentnode); } } let's go through the above code and look at what's happening.
...And 2 more matches
OffscreenCanvas.getContext() - Web APIs
possible values are: "2d" creates a canvasrenderingcontext2d object representing a two-dimensional rendering context.
... "webgl" creates a webglrenderingcontext object representing a three-dimensional rendering context.
... "webgl2" creates a webgl2renderingcontext object representing a three-dimensional rendering context.
...And 2 more matches
Path2D() - Web APIs
WebAPIPath2DPath2D
the path2d() constructor returns a newly instantiated path2d object, optionally with another path as an argument (creates a copy), or optionally with a string consisting of svg path data.
... syntax new path2d(); new path2d(path); new path2d(d); parameters path optional when invoked with another path2d object, a copy of the path argument is created.
... d optional when invoked with a string consisting of svg path data, a new path is created from that description.
...And 2 more matches
performance.measure() - Web APIs
the measure() method creates a named timestamp in the browser's performance entry buffer between marks, the navigation start time, or the current time.
... name - set to the "name" given when the measure was created.
... return value void example the following example shows how measure() is used to create a new measure performance entry in the browser's performance entry buffer.
...And 2 more matches
RTCPeerConnection.restartIce() - Web APIs
after restartice() returns, the offer returned by the next call to createoffer() is automatically configured to trigger ice restart on both the local peer (once the local peer has been set) and on the remote peer, once the offer is sent across your signaling mechanism and the remote peer has set its description as well.
... usage notes after calling restartice(), the next offer created using createoffer() will initiate ice restart once sent to the remote peer over your signaling mechanism.
... restarting ice essentially resets ice so that it creates all new candidates using new credentials.
...And 2 more matches
Reporting API - Web APIs
reporting observers reports can also be obtained via reportingobserver objects created via javascript inside the website you are aiming to get reports on.
... a reportingobserver object is created using the reportingobserver() constructor, which is passed two parameters: a callback function that has available as parameters the reports available in the observer's report queue, and a copy of the same reportingobserver object, so observation can be controlled directly from inside the callback.
... the callback runs when observation starts an options dictionary that allows you to specify the type of reports to collect, and whether the reports that were generated before the observer was able to be created should be observable (buffered: true).
...And 2 more matches
Request() - Web APIs
WebAPIRequestRequest
the request() constructor creates a new request object.
... example in our fetch request example (see fetch request live) we create a new request object using the constructor, then fetch it using a globalfetch.fetch call.
... since we are fetching an image, we run body.blob on the response to give it the proper mime type so it will be handled properly, then create an object url of it and display it in an <img> element.
...And 2 more matches
Request - Web APIs
WebAPIRequest
you can create a new request object using the request() constructor, but you are more likely to encounter a request object being returned as the result of another api operation, such as a service worker fetchevent.request.
... constructor request() creates a new request object.
... methods request.clone() creates a copy of the current request object.
...And 2 more matches
Response - Web APIs
WebAPIResponse
you can create a new response object using the response.response() constructor, but you are more likely to encounter a response object being returned as the result of another api operation—for example, a service worker fetchevent.respondwith, or a simple windoworworkerglobalscope.fetch().
... constructor response() creates a new response object.
... methods response.clone() creates a clone of a response object.
...And 2 more matches
Text.splitText() - Web APIs
WebAPITextsplitText
after the split, the current node contains all the content up to the specified offset point, and a newly created node of the same type contains the remaining text.
... the newly created node is returned to the caller.
...if the offset is equal to the length of the original node, the newly created node has no data.
...And 2 more matches
TextRange - Web APIs
WebAPITextRange
for example, when you hold down the mouse to select the content on the page, you create a typical textrange.
... it is implemented in ie, then a textrange object can be created by element.createtextrange() or document.selection.createrange().
... var range = document.selection.createrange(); var element = document.getelementbyid("test"); range.movetoelementtext(element); range.select(); // selected "sometexttobeselected" <!doctype html> <html> <head> <title>textrange example</title> </head> <body> <p id="test">sometexttobeselected</p> </body> </html> notes use textrange to operate the selection valid only under ie9.
...And 2 more matches
URL - Web APIs
WebAPIURL
you normally create a new url object by specifying the url as a string when calling its constructor, or by providing a relative url and a base url.
... constructor new url() creates and returns a url object referencing the url specified using an absolute url string, or a relative url string and a base url string.
... static methods createobjecturl() returns a domstring containing a unique blob url, that is a url with blob: as its scheme, followed by an opaque string uniquely identifying the object in the browser.
...And 2 more matches
Creating 3D objects using WebGL - Web APIs
« previousnext » let's take our square plane into three dimensions by adding five more faces to create a cube.
...if you wonder why we need 24 vertices, and not just 8, it is because each corner belongs to three faces of different colors, and a single vertex needs to have a single specific color; therefore we will create three copies of each vertex in three different colors, one for each face.
...you'll need to include it if you create your own project based on this code.
...And 2 more matches
Lighting a WebXR setting - Web APIs
and while this article provides brief reminders as to how lighting works in general, it is not by any means a tutorial in lighting or a guide to how to create a properly-lit 3d scene.
...obviously, there are exceptions to this guideline, such as when your scene represents an otherworldly or alien setting, or when your goal is to create an unsettling visual effect.
... try to place light sources in realistic locations for the setting and the mood you're trying to create.
...And 2 more matches
Web Animations API Concepts - Web APIs
this means we can use it to create and manipulate css-like animations that go from one pre-defined state to another, or we can use variables, loops, and callbacks to create interactive animations that adapt and react to changing inputs.
... the internet explorer team requested an animations api to consolidate and normalize animation functionality across all browsers, and thus efforts began in earnest among mozilla firefox and google chrome developers to create the one animation spec to rule them all: the web animations api.
...by assembling these disparate objects, we can create animations of our own.
...And 2 more matches
Web Audio API best practices - Web APIs
there's the standardised-audio-context npm package, which creates api functionality consistently across browsers, full holes as they are found.
... autoplay policy browsers have started to implement an autoplay policy, which in general can be summed up as: "create or resume context from inside a user gesture".
... when you create an audio context (either offline or online) it is created with a state, which can be suspended, running, or closed.
...And 2 more matches
Visualizations with Web Audio API - Web APIs
one of the most interesting features of the web audio api is the ability to extract frequency, waveform, and other data from your audio source, which can then be used to create visualizations.
... basic concepts to extract data from your audio source, you need an analysernode, which is created using the audiocontext.createanalyser() method, for example: var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); this node is then connected to your audio source at some point between your source and your destination, for example: source = audioctx.createmediastreamsource(stream); source.connect(analyser); analyser.connect(distortion); distortion.connect(audioctx.destination); note: you don't need to connect the analyser's output to another node for it to work, as...
... these methods copy data into a specified array, so you need to create a new array to receive the data before invoking one.
...And 2 more matches
Using the Web Speech API - Web APIs
we also create a new speech grammar list to contain our grammar, using the speechgrammarlist() constructor.
...we then loop through this list — for each voice we create an <option> element, set its text content to display the name of the voice (grabbed from speechsynthesisvoice.name), the language of the voice (grabbed from speechsynthesisvoice.lang), and -- default if the voice is the default voice for the synthesis engine (checked by seeing if speechsynthesisvoice.default returns true.) we also create data- attributes for each option, containing the name and ...
... function populatevoicelist() { voices = synth.getvoices(); for(i = 0; i < voices.length ; i++) { var option = document.createelement('option'); option.textcontent = voices[i].name + ' (' + voices[i].lang + ')'; if(voices[i].default) { option.textcontent += ' -- default'; } option.setattribute('data-lang', voices[i].lang); option.setattribute('data-name', voices[i].name); voiceselect.appendchild(option); } } when we come to run the function, we do the following.
...And 2 more matches
Using XMLHttpRequest - Web APIs
to send an http request, create an xmlhttprequest object, open a url, and send the request.
...it starts with "xml" because when it was created the main format that was originally used for asynchronous data exchange were xml handling responses there are several types of response attributes defined by the living standard specification for the xmlhttprequest() constructor.
...">i have a bike</label><br /> <input id="vehicle_car" type="checkbox" name="vehicle[]" value="car" /> <label for="vehicle_car">i have a car</label> </p> <p> describe yourself:<br /> <textarea name="description" cols="50" rows="8"></textarea> </p> <p> <input type="submit" value="submit" /> </p> </fieldset> </form> </body> </html> to test this, create a page named register.php (which is the action attribute of these sample forms), and put the following minimalistic content: <?php /* register.php */ header("content-type: text/plain"); /* note: you should never use `print_r()` in production scripts, or otherwise output client-submitted data without sanitizing it first.
...And 2 more matches
XRView - Web APIs
WebAPIXRView
it's computed by inverting then transposing the model view matrix: mat4.invert(normalmatrix, modelviewmatrix); mat4.transpose(normalmatrix, normalmatrix); teleporting an object to programmatically move and/or rotate (often referred to as teleporting) an object, you need to create a new reference space for that object which applies a transform that encapsulates the desired changes.
... the createteleporttransform() function returns the transform needed to move and rotate an object whose current situation is described by the reference space refspace to a new position and orientation which is computed using previously recorded mouse and keyboard input data which has generated offsets for yaw, pitch, and position along all three axes.
...et newtransform = new xrrigidtransform({x: transversedistance, y: verticaldistance, z: axialdistance}, {x: inverseorientation[0], y: inverseorientation[1], z: inverseorientation[2], w: inverseorientation[3]}); mat4.copy(mousematrix, newtransform.matrix); // create a new reference space that transforms the object to the new // position and orientation, returning the new reference space.
...And 2 more matches
Detecting CSS animation support - CSS: Cascading Style Sheets
testing for css animation support this code will check to see if css animation support is available: var animation = false, animationstring = 'animation', keyframeprefix = '', domprefixes = 'webkit moz o ms khtml'.split(' '), pfx = '', elem = document.createelement('div'); if( elem.style.animationname !== undefined ) { animation = true; } if( animation === false ) { for( var i = 0; i < domprefixes.length; i++ ) { if( elem.style[ domprefixes[i] + 'animationname' ] !== undefined ) { pfx = domprefixes[ i ]; animationstring = pfx + 'animation'; keyframeprefix = '-' + pfx.tolowercase() + '-'; animation = true; break; ...
...we create an array of browser prefixes to loop over and we set pfx to an empty string.
... var keyframes = '@' + keyframeprefix + 'keyframes rotate { '+ 'from {' + keyframeprefix + 'transform:rotate( 0deg ) }'+ 'to {' + keyframeprefix + 'transform:rotate( 360deg ) }'+ '}'; if( document.stylesheets && document.stylesheets.length ) { document.stylesheets[0].insertrule( keyframes, 0 ); } else { var s = document.createelement( 'style' ); s.innerhtml = keyframes; document.getelementsbytagname( 'head' )[ 0 ].appendchild( s ); } } this code looks at the value of animation; if it's false, we know we need to use our javascript fallback code to perform our animation.
...And 2 more matches
Relationship of flexbox to other layout methods - CSS: Cascading Style Sheets
there is a note in the flexbox spec stating that in the future, once it is completed, the definitions in box alignment level 3 will supersede those of flexbox: "note: while the alignment properties are defined in css box alignment [css-align-3], flexible box layout reproduces the definitions of the relevant ones here so as to not create a normative dependency that may slow down advancement of the spec.
...until browsers implement the gap properties for flexbox, margins have to be used to create gaps between items.
... if we create a very similar layout using grid, we can control the layout in both rows and columns.
...And 2 more matches
CSS Grid Layout and Progressive Enhancement - CSS: Cascading Style Sheets
floats we have typically used floats to create multiple column layouts.
...to create gaps between the cards, i use a margin on the items, and then a negative margin on the container: * {box-sizing: border-box;} .wrapper { border: 2px solid #f76707; border-radius: 5px; background-color: #fff4e6; max-width: 600px; margin: 0 auto; } .wrapper li { border: 2px solid #ffa94d; border-radius: 5px; background-color: #ffd8a8; padding: 1em; color:...
... feature queries will look very familiar if you have ever used a media query to create a responsive layout.
...And 2 more matches
The stacking context - CSS: Cascading Style Sheets
element with a will-change value specifying any property that would create a stacking context on non-initial value (see this post).
... in summary: stacking contexts can be contained in other stacking contexts, and together create a hierarchy of stacking contexts.
... note: the hierarchy of stacking contexts is a subset of the hierarchy of html elements because only certain elements create stacking contexts.
...And 2 more matches
Testing media queries programmatically - CSS: Cascading Style Sheets
once you've created a mediaquerylist object, you can check the result of the query or receive notifications when the result changes.
... creating a media query list before you can evaluate the results of a media query, you need to create the mediaquerylist object representing the query.
... for example, to set up a query list that determines if the device is in landscape or portrait orientation: const mediaquerylist = window.matchmedia("(orientation: portrait)"); checking the result of a query once you've created your media query list, you can check the result of the query by looking at the value of its matches property: if (mediaquerylist.matches) { /* the viewport is currently in portrait orientation */ } else { /* the viewport is not currently in portrait orientation, therefore landscape */ } receiving query notifications if you need to be aware of changes to the evaluated result of the query on an ongoing basis, it's more efficient to register a listener than to poll the query's result.
...And 2 more matches
border-image-slice - CSS: Cascading Style Sheets
the slicing process creates nine regions in total: four corners, four edges, and a middle region.
... when one position is specified, it creates all four slices at the same distance from their respective sides.
... when two positions are specified, the first value creates slices measured from the top and bottom, the second creates slices measured from the left and right.
...And 2 more matches
Adding captions and subtitles to HTML5 video - Developer guides
this example uses an excerpt from the sintel open movie, created by the blender foundation.
... all we need to do is to go through the video's texttracks, reading their properties and building the menu up from there: var subtitlesmenu; if (video.texttracks) { var df = document.createdocumentfragment(); var subtitlesmenu = df.appendchild(document.createelement('ul')); subtitlesmenu.classname = 'subtitles-menu'; subtitlesmenu.appendchild(createmenuitem('subtitles-off', '', 'off')); for (var i = 0; i < video.texttracks.length; i++) { subtitlesmenu.appendchild(createmenuitem('subtitles-' + video.texttracks[i].language, video.texttracks[i].language, video.texttra...
...cks[i].label)); } videocontainer.appendchild(subtitlesmenu); } this code creates a documentfragment, which is used to hold an unordered list containing our subtitles menu.
...And 2 more matches
Creating a cross-browser video player - Developer guides
this is done by simply checking if a created <video> element supports the canplaytype() method, which any supported html5 <video> element should.
... var supportsvideo = !!document.createelement('video').canplaytype; if (supportsvideo) { // set up custom controls // ...
...a user defined function, altervolume(direction) has been created that deals with this: var altervolume = function(dir) { var currentvolume = math.floor(video.volume * 10) / 10; if (dir === '+') { if (currentvolume < 1) video.volume += 0.1; } else if (dir === '-') { if (currentvolume > 0) video.volume -= 0.1; } } this function makes use of the media api's volume attribute, which holds the current volume value of the video.
...And 2 more matches
Making content editable - Developer guides
here's a simple example which creates a <div> element whose contents the user can edit.
...for example, even something as simple as what happens when you press enter/return to create a new line of text inside an editable element was handled differently across the major browsers (firefox inserted <br> elements, ie/opera used <p>, chrome/safari used <div>).
...d) { setdocmode(true); } } function formatdoc(scmd, svalue) { if (validatemode()) { document.execcommand(scmd, false, svalue); odoc.focus(); } } function validatemode() { if (!document.compform.switchmode.checked) { return true ; } alert("uncheck \"show html\"."); odoc.focus(); return false; } function setdocmode(btosource) { var ocontent; if (btosource) { ocontent = document.createtextnode(odoc.innerhtml); odoc.innerhtml = ""; var opre = document.createelement("pre"); odoc.contenteditable = false; opre.id = "sourcetext"; opre.contenteditable = true; opre.appendchild(ocontent); odoc.appendchild(opre); document.execcommand("defaultparagraphseparator", false, "div"); } else { if (document.all) { odoc.innerhtml = odoc.innertext; }...
...And 2 more matches
Applying color to HTML elements using CSS - HTML: Hypertext Markup Language
with css, there are lots of ways to add color to your html elements to create just the look you want.
... css we'll look at the css to create the above results a piece at a time, so we can review the interesting parts one by one.
...then we can create a class for each of the two boxes that defines the properties that differ between the two.
...And 2 more matches
DASH Adaptive Streaming for HTML 5 Video - HTML: Hypertext Markup Language
use your existing webm file to create one audio file and multiple video files.
... for example: the file in.video can be any container with at least one audio and one video stream that can be decoded by ffmpeg, create the audio using: ffmpeg -i in.video -vn -acodec libvorbis -ab 128k -dash 1 my_audio.webm create each video variant.
...create the manifest file: ffmpeg \ -f webm_dash_manifest -i video_160x90_250k.webm \ -f webm_dash_manifest -i video_320x180_500k.webm \ -f webm_dash_manifest -i video_640x360_750k.webm \ -f webm_dash_manifest -i video_1280x720_1500k.webm \ -f webm_dash_manifest -i my_audio.webm \ -c copy \ -map 0 -map 1 -map 2 -map 3 -map 4 \ -f webm_dash_manifest \ -adaptation_sets "id=0,streams=0,1,...
...And 2 more matches
<input>: The Input (Form Input) element - HTML: Hypertext Markup Language
WebHTMLElementinput
the html <input> element is used to create interactive controls for web-based forms in order to accept data from the user; a wide variety of types of input data and control widgets are available, depending on the device and user agent.
...while a screen reader will announce the label of the form control receiving focus, the screen reader will not announce anything before the label, and the sighted user on a small device will equally miss the context created by the preceding content.
... name and radio buttons the name attribute creates a unique behavior for radio buttons.
...And 2 more matches
Redirections in HTTP - HTTP
308 was created to remove the ambiguity of the behavior when using non-get methods.
...307 was created to remove the ambiguity of the behavior when using non-get methods.
...there are two others: html redirections with the <meta> element javascript redirections via the dom html redirections http redirects are the best way to create redirections, but sometimes you don't have control over the server.
...And 2 more matches
Regular expressions - JavaScript
/a\*b/ and new regexp("a\\*b") create the same expression, which searches for "a" followed by a literal "*" followed by "b".
...updated at the time that the regular expression is created, not executed.
... 'd(b+)d' as shown in the second form of this example, you can use a regular expression created with an object initializer without assigning it to a variable.
...And 2 more matches
ArrayBuffer - JavaScript
it is an array of bytes, often referred to in other languages as a "byte array".you cannot directly manipulate the contents of an arraybuffer; instead, you create one of the typed array objects or a dataview object which represents the buffer in a specific format, and use that to read and write the contents of the buffer.
... the arraybuffer() constructor creates a new arraybuffer of the given length in bytes.
... constructor arraybuffer() creates a new arraybuffer object.
...And 2 more matches
BigInt64Array() constructor - JavaScript
the bigint64array() typed array constructor creates a new bigint64array object, which is, an array of 64-bit signed integers in the platform byte order.
... syntax new bigint64array(); new bigint64array(length); new bigint64array(typedarray); new bigint64array(object); new bigint64array(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros.
... object when called with an object argument, a new typed array is created as if by the typedarray.from() method.
...And 2 more matches
BigUint64Array() constructor - JavaScript
the biguint64array() typed array constructor creates a new biguint64array object, which is, an array of 64-bit unsigned integers in the platform byte order.
... syntax new biguint64array(); new biguint64array(length); new biguint64array(typedarray); new biguint64array(object); new biguint64array(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros.
... object when called with an object argument, a new typed array is created as if by the typedarray.from() method.
...And 2 more matches
Float32Array() constructor - JavaScript
the float32array() typed array constructor creates a new float32array object, which is, an array of 32-bit floating point numbers (corresponding to the c float data type) in the platform byte order.
... syntax new float32array(); // new in es2017 new float32array(length); new float32array(typedarray); new float32array(object); new float32array(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros.
... object when called with an object argument, a new typed array is created as if by the typedarray.from() method.
...And 2 more matches
Float64Array() constructor - JavaScript
the float64array() typed array constructor creates a new float64array object, which is, an array of 64-bit floating point numbers (corresponding to the c double data type) in the platform byte order.
... syntax new float64array(); // new in es2017 new float64array(length); new float64array(typedarray); new float64array(object); new float64array(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros.
... object when called with an object argument, a new typed array is created as if by the typedarray.from() method.
...And 2 more matches
Int16Array() constructor - JavaScript
the int16array() typed array constructor creates an array of twos-complement 16-bit signed integers in the platform byte order.
... syntax new int16array(); // new in es2017 new int16array(length); new int16array(typedarray); new int16array(object); new int16array(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros.
... object when called with an object argument, a new typed array is created as if by the typedarray.from() method.
...And 2 more matches
Int32Array() constructor - JavaScript
the int32array() typed array constructor creates an array of twos-complement 32-bit signed integers in the platform byte order.
... syntax new int32array(); // new in es2017 new int32array(length); new int32array(typedarray); new int32array(object); new int32array(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros.
... object when called with an object argument, a new typed array is created as if by the typedarray.from() method.
...And 2 more matches
Int8Array() constructor - JavaScript
the int8array() constructor creates a typed array of twos-complement 8-bit signed integers.
... syntax new int8array(); // new in es2017 new int8array(length); new int8array(typedarray); new int8array(object); new int8array(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros.
... object when called with an object argument, a new typed array is created as if by the typedarray.from() method.
...And 2 more matches
Intl.DisplayNames - JavaScript
constructor intl.displaynames() creates a new intl.displaynames object.
... examples region code display names to create an intl.displaynames for a locale and get the display name for a region code.
..." regionnames.of('mm'); // "myanmar (burma)" // get display names of region in traditional chinese regionnames = new intl.displaynames(['zh-hant'], {type: 'region'}); regionnames.of('419'; // "拉丁美洲" regionnames.of('bz'); // "貝里斯" regionnames.of('us'); // "美國" regionnames.of('ba'); // "波士尼亞與赫塞哥維納" regionnames.of('mm'); // "緬甸" language display names to create an intl.displaynames for a locale and get the display name for a language-script-region sequence.
...And 2 more matches
RegExp - JavaScript
description literal notation and constructor there are two ways to create a regexp object: a literal notation and a constructor.
... the following three expressions create the same regular expression: /ab+c/i new regexp(/ab+c/, 'i') // literal notation new regexp('ab+c', 'i') // constructor the literal notation results in compilation of the regular expression when the expression is evaluated.
...a new regexp from the arguments is created instead.
...And 2 more matches
SharedArrayBuffer - JavaScript
the sharedarraybuffer object is used to represent a generic, fixed-length raw binary data buffer, similar to the arraybuffer object, but in a way that they can be used to create views on shared memory.
... var sab = new sharedarraybuffer(1024); worker.postmessage(sab); updating and synchronizing shared memory with atomic operations shared memory can be created and updated simultaneously in workers or the main thread.
...require-corp to check if cross origin isolation has been successful, you can test against the crossoriginisolated property available to window and worker contexts: if (crossoriginisolated) { // post sharedarraybuffer } else { // do something else } see also planned changes to shared memory which is starting to roll out to browsers (firefox 79, for example.) always use the new operator to create a sharedarraybuffer sharedarraybuffer constructors are required to be constructed with a new operator.
...And 2 more matches
TypedArray.from() - JavaScript
the typedarray.from() method creates a new typed array from an array-like or iterable object.
... description typedarray.from() lets you create typed arrays from: array-like objects (objects with a length property and indexed elements); or iterable objects (objects where you can get its elements, such as map and set).
... typedarray.from() has the optional parameter mapfn, which allows you to execute a map() function on each element of the typed array (or subclass object) that is being created.
...And 2 more matches
Uint32Array() constructor - JavaScript
the uint32array() typed array constructor creates an array of 32-bit unsigned integers in the platform byte order.
... syntax new uint32array(); // new in es2017 new uint32array(length); new uint32array(typedarray); new uint32array(object); new uint32array(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros.
... object when called with an object argument, a new typed array is created as if by the typedarray.from() method.
...And 2 more matches
Uint8Array() constructor - JavaScript
the uint8array() constructor creates a typed array of 8-bit unsigned integers.
... syntax new uint8array(); // new in es2017 new uint8array(length); new uint8array(typedarray); new uint8array(object); new uint8array(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros.
... object when called with an object argument, a new typed array is created as if by the typedarray.from() method.
...And 2 more matches
Uint8ClampedArray() constructor - JavaScript
the uint8clampedarray() constructor creates a typed array of 8-bit unsigned integers clamped to 0-255; if you specified a value that is out of the range of [0,255], 0 or 255 will be set instead; if you specify a non-integer, the nearest integer will be set.
... syntax new uint8clampedarray(); // new in es2017 new uint8clampedarray(length); new uint8clampedarray(typedarray); new uint8clampedarray(object); new uint8clampedarray(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros.
... object when called with an object argument, a new typed array is created as if by the typedarray.from() method.
...And 2 more matches
WebAssembly.Memory() constructor - JavaScript
the webassembly.memory() constructor creates a new memory object whose buffer property is a resizable arraybuffer or sharedarraybuffer that holds the raw bytes of memory accessed by a webassembly instance.
... a memory created by javascript or in webassembly code will be accessible and mutable from both javascript and webassembly.
...the following example creates a new webassembly memory instance with an initial size of 10 pages (640kib), and a maximum size of 100 pages (6.4mib).
...And 2 more matches
WebAssembly.Memory - JavaScript
a memory created by javascript or in webassembly code will be accessible and mutable from both javascript and webassembly.
... constructor webassembly.memory() creates a new memory object.
...the following example creates a new webassembly memory instance with an initial size of 10 pages (640kib), and a maximum size of 100 pages (6.4mib).
...And 2 more matches
delete operator - JavaScript
this includes properties of built-in objects like math, array, object and properties that are created as non-configurable with methods like object.defineproperty().
... var employee = {}; object.defineproperty(employee, 'name', {configurable: false}); console.log(delete employee.name); // returns false var, let, and const create non-configurable properties that cannot be deleted with the delete operator: var nameother = 'xyz'; // we can access this global property using: object.getownpropertydescriptor(window, 'nameother'); // output: object {value: "xyz", // writable: true, // enumerable: true, // configurable: false} // since "nameother" is added using with the // ...
... examples // creates the property adminname on the global scope.
...And 2 more matches
let - JavaScript
just like const the let does not create properties of the window object when declared globally (in the top-most scope).
... console.log(x); // 2 } console.log(x); // 2 } function lettest() { let x = 1; { let x = 2; // different variable console.log(x); // 2 } console.log(x); // 1 } at the top level of programs and functions, let, unlike var, does not create a property on the global object.
... = function() { return this.someproperty; }; thing.prototype.showprivate = function() { return privatescope.get(this).hidden; }; } console.log(typeof privatescope); // "undefined" var thing = new thing(); console.log(thing); // thing {someproperty: "foo"} thing.showpublic(); // "foo" thing.showprivate(); // 1 the same privacy pattern with closures over local variables can be created with var, but those need a function scope (typically an iife in the module pattern) instead of just a block scope like in the example above.
...And 2 more matches
Web video codec guide - Web media technologies
supported bit rates varies by level supported frame rates varies by level; up to 300 fps is possible compression lossy dct-based algorithm, though it's possible to create lossless macroblocks within the image supported frame sizes up to 8,192 x 4,320 pixels supported color modes some of the more common or interesting profiles: profile color depths chroma subsampling constrained baseline (cbp) 8 4:2:0 baseline (bp) 8 4:2:0 ...
...instead of having the luma samples (representing the image's pixels in grayscale) and the cb and cr samples (indicating how to alter the grays to create color pixels), the three channels are instead treated as three monochrome images, one for each color, which are then combined during rendering to produce a full-color image.
...unlike the later mpeg video standards, mpeg-1 was created solely by mpeg, without the itu's involvement.
...And 2 more matches
Filter effects - SVG: Scalable Vector Graphics
drop shadows, to provide a popular example, cannot be created reasonably with a combination of gradients.
... filters are svg's mechanism to create sophisticated effects.
...to apply your created filter on a graphic element, you set the filter attribute.
...And 2 more matches
Subdomain takeovers - Web security
you create a virtual host at the hosting provider.
... unless the hosting provider is very careful to verify that the entity who sets up the virtual host actually is the owner of the subdomain name, an attacker who is quicker than you could create a virtual host with the same hosting provider, using your subdomain name.
...however, if you don’t remove the dns entry that points to the hosting provider, an attacker can now create their own virtual host with that provider, claim your subdomain, and host their own content under that subdomain.
...And 2 more matches
Using shadow DOM - Web Components
if you are attaching a shadow dom to a custom element as part of its constructor (by far the most useful application of the shadow dom), you would use something like this: let shadow = this.attachshadow({mode: 'open'}); when you've attached a shadow dom to an element, manipulating it is a matter of just using the same dom apis as you use for the regular dom manipulation: let para = document.createelement('p'); shadow.appendchild(para); // etc.
... creating the shadow root we first attach a shadow root to the custom element: // create a shadow root let shadow = this.attachshadow({mode: 'open'}); creating the shadow dom structure next, we use some dom manipulation to create the element's internal shadow dom structure: // create spans let wrapper = document.createelement('span'); wrapper.setattribute('class', 'wrapper'); let icon = document.createelement('span'); icon.setattribute('class', 'icon'); icon.setattribute('tabindex...
...', 0); let info = document.createelement('span'); info.setattribute('class', 'info'); // take attribute content and put it inside the info span let text = this.getattribute('data-text'); info.textcontent = text; // insert icon let imgurl; if(this.hasattribute('img')) { imgurl = this.getattribute('img'); } else { imgurl = 'img/default.png'; } let img = document.createelement('img'); img.src = imgurl; icon.appendchild(img); styling the shadow dom after that we create a <style> element and populate it with some css to style it: // create some css to apply to the shadow dom let style = document.createelement('style'); style.textcontent = ` .wrapper { position: relative; } .info { font-size: 0.8rem; width: 200px; display: inline-block; border: 1px solid black; padding: 10px; ...
...And 2 more matches
Using the Mozilla JavaScript interface to XSL Transformations - XSLT: Extensible Stylesheet Language Transformations
creating an xsltprocessor to start, you need to create an xsltprocessor object: var processor = new xsltprocessor(); specifying the stylesheet before you can use it, you must import a stylesheet with the xsltprocessor.importstylesheet() method.
... var testtransform = document.implementation.createdocument("", "test", null); // just an example to get a transform into a script as a dom // xmldocument.load is asynchronous, so all processing happens in the // onload handler testtransform.addeventlistener("load", onload, false); testtransform.load("test-transform.xml"); function onload() { processor.importstylesheet(testtransform); } xsltprocessor.importstylesheet() requires one argument, a d...
... var ownerdocument = document.implementation.createdocument("", "test", null); var newfragment = processor.transformtofragment(domtobetransformed, ownerdocument); xsltprocessor.transformtofragment() will only produce html dom objects if the owner document is itself an htmldocument, or if the output method of the stylesheet is html.
...And 2 more matches
Compiling from Rust to WebAssembly - WebAssembly
building our webassembly npm package enough setup; let's create a new package in rust.
... navigate to wherever you keep your personal projects, and type this: $ cargo new --lib hello-wasm created library `hello-wasm` project this creates a new library in a subdirectory named hello-wasm with everything you need to get going: +-- cargo.toml +-- src +-- lib.rs first, we have cargo.toml; this is the file that we use to configure our build.
... creates a pkg directory and move that javascript file and your webassembly code into it.
...And 2 more matches
Compiling an Existing C Module to WebAssembly - WebAssembly
luckily, the canvas api has canvasrenderingcontext2d.getimagedata — that gives you an uint8clampedarray containing the image data in rgba: async function loadimage(src) { // load image const imgblob = await fetch(src).then(resp => resp.blob()); const img = await createimagebitmap(imgblob); // make canvas same size as image const canvas = document.createelement('canvas'); canvas.width = img.width; canvas.height = img.height; // draw image onto canvas const ctx = canvas.getcontext('2d'); ctx.drawimage(img, 0, 0); return ctx.getimagedata(0, 0, img.width, img.height); } now it's "only" a matter of copying the data from javascript into wasm.
... for that, you need to expose two additional functions — one that allocates memory for the image inside wasm and one that frees it up again: #include <stdlib.h> // required for malloc definition emscripten_keepalive uint8_t* create_buffer(int width, int height) { return malloc(width * height * 4 * sizeof(uint8_t)); } emscripten_keepalive void destroy_buffer(uint8_t* p) { free(p); } the create_buffer() function allocates a buffer for the rgba image — hence 4 bytes per pixel.
...after exposing the function to javascript using cwrap, you can use that number to find the start of our buffer and copy the image data: const api = { version: module.cwrap('version', 'number', []), create_buffer: module.cwrap('create_buffer', 'number', ['number', 'number']), destroy_buffer: module.cwrap('destroy_buffer', '', ['number']), }; const image = await loadimage('./image.jpg'); const p = api.create_buffer(image.width, image.height); module.heap8.set(image.data, p); // ...
...And 2 more matches
High-Level APIs - Archive of obsolete content
addon-page create a page that does not contain navigational elements.
... page-worker create a permanent, invisible page and access its dom.
... panel creates transient dialogs to implement part of an add-on's user interface.
... widget create a simple user interface for an add-on in firefox's add-on bar.
event/target - Archive of obsolete content
create objects that broadcast events.
...with this module you can create your own objects that emit events.
... instantiation it's easy to create event target objects, no special arguments are required.
...will be auto registered for associated 'message', 'myevent' events on the created instance.
io/byte-streams - Archive of obsolete content
ame, "rb"); if (!bytereader.closed) { data = bytereader.read(); bytereader.close(); } } return data; } function writebinarydatatofile(data, filename) { var fileio = require("sdk/io/file"); var bytewriter = fileio.open(filename, "wb"); if (!bytewriter.closed) { bytewriter.write(data); bytewriter.close(); } } globals constructors bytereader(inputstream) creates a binary input stream that reads bytes from a backing stream.
... you can also create bytereader objects using io/file's open() function.
... bytewriter(outputstream) creates a binary output stream that writes bytes to a backing stream.
... you can also create bytewriter objects using io/file's open() function.
io/file - Archive of obsolete content
any subdirectories that do not exist are also created.
... parameters path : string the path to create.
... apart from these options, this api always passes the following options: create_file, truncate (see //github.com/realityripple/uxp/blob/master/nsprpub/pr/include/prio.h#550).
... this means that: if the file does not exist it is created if the file exists, its length is truncated to zero it is not possible to open the file in append mode.
io/text-streams - Archive of obsolete content
ame, "r"); if (!textreader.closed) { text = textreader.read(); textreader.close(); } } return text; } function writetexttofile(text, filename) { var fileio = require("sdk/io/file"); var textwriter = fileio.open(filename, "w"); if (!textwriter.closed) { textwriter.write(text); textwriter.close(); } } globals constructors textreader(inputstream, charset) creates a buffered input stream that reads text from a backing stream using a given text encoding.
... you can also create textreader objects using io/file's open() function.
... textwriter(outputstream, charset) creates a buffered output stream that writes text to a backing stream using a given text encoding.
... you can also create textwriter objects using io/file's open() function.
ui/button/action - Archive of obsolete content
with this module you can create buttons that display icons and can respond to click events.
... usage creating buttons to create a button you must give it an id, an icon, and a label: var { actionbutton } = require("sdk/ui/button/action"); var button = actionbutton({ id: "my-button", label: "my button", icon: { "16": "./firefox-16.png", "32": "./firefox-32.png" }, onclick: function(state) { console.log("button '" + state.label + "' was clicked"); } }); by default, the button appears in the firefox toolbar: however, users can move it to the firefox menu panel using the toolbar customization feature: badged buttons new in firefox 36.
... globals constructors actionbutton(options) creates an action button.
...for example, this add-on: creates a button with a default label opens a new tab sets a new label only for the new tab logs the result of accessing the global label, the window-specific label, and each of the 2 tab-specific labels var { actionbutton } = require('sdk/ui/button/action'); var tabs = require("sdk/tabs"); var button = actionbutton({ id: "my-button", label: "default label", icon: "./firefox-16.png" }); tab...
ui/button/toggle - Archive of obsolete content
with this module you can create buttons that function like a check box, representing an on/off choice.
... usage creating buttons to create a button you must give it an id, an icon, and a label: var { togglebutton } = require("sdk/ui/button/toggle"); var button = togglebutton({ id: "my-button", label: "my button", icon: { "16": "./firefox-16.png", "32": "./firefox-32.png" }, onchange: function(state) { console.log(state.label + " checked state: " + state.checked); } }); by default, the b...
... globals constructors togglebutton(options) creates a toggle button.
...for example, this add-on: creates a button with a default label opens a new tab sets a new label only for the new tab logs the result of accessing the global label, the window-specific label, and each of the 2 tab-specific labels var { togglebutton } = require('sdk/ui/button/toggle'); var tabs = require("sdk/tabs"); var button = togglebutton({ id: "my-button", label: "default label", icon: "./firefox-16.png" }); tab...
Storing annotations - Archive of obsolete content
now we are able to create annotations, let's store them using the simple-storage module.
...nnotation); } 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, we create and store the new annotation: var annotationeditor = panels.panel({ width: 220, height: 220, contenturl: data.url('editor/annotation-editor.html'), contentscriptfile: data.url('editor/annotation-editor.js'), onmessage: function(annotationtext) { if (annotationtext) handlenewannotation(annotationtext, this.annotationanchor); annotationeditor.hide(); }, onshow: function...
... updating main.js here's the code to create the panel, which can go in the main function.
... now we can create and store annotations, the last piece is to display them when the user loads the page.
Add-on SDK - Archive of obsolete content
using the add-on sdk, you can create firefox add-ons.
... you can use various standard web technologies: javascript, html, and css, to create the add-ons.
... the sdk includes javascript apis, which you can use to create add-ons and tools for creating, running, testing, and packaging add-ons.
... create user interface components create user interface components such as toolbar buttons, context menus, menu items, and dialogs.
HTML to DOM - Archive of obsolete content
function htmlparser(ahtmlstring){ var html = document.implementation.createdocument("http://www.w3.org/1999/xhtml", "html", null), body = document.createelementns("http://www.w3.org/1999/xhtml", "body"); html.documentelement.appendchild(body); body.appendchild(components.classes["@mozilla.org/feed-unescapehtml;1"] .getservice(components.interfaces.nsiscriptableunescapehtml) .parsefragment(ahtmlstring, false, null, body)); return body; } it works by ...
...for that matter, we're going to load our html document first: var request = xmlhttprequest(); request.open("get", "http://example.org/file.html", false); request.send(null); our next step is to create the document object that will represent the dom into which we'll insert our newly-retrieved html: var doc = document.implementation.createhtmldocument("example"); doc.documentelement.innerhtml = request.responsetext; after this any manipulation that we might want to do will be something as simple as the following: doc.body.textcontent = "this is inside the body!"; using a hidden iframe el...
...create your own function using unique name, id, and so forth.
... var frame = document.getelementbyid("sample-frame"); if (!frame) { // create frame frame = document.createelement("iframe"); // iframe (or browser on older firefox) frame.setattribute("id", "sample-frame"); frame.setattribute("name", "sample-frame"); frame.setattribute("type", "content"); frame.setattribute("collapsed", "true"); document.getelementbyid("main-window").appendchild(frame); // or // document.documentelement.appendchild(frame); // set restrictions as needed frame.webnavigation.allowauth = false; frame.webnavigation.allowimages = false; frame.webnavigation.allowjavascript = false; frame.webnavigation.allowmetaredirects = true; frame.webnavigation.allowplugins = false; frame.webnavigation.allowsubframes = false; // listen for load frame.addeventlis...
JS XPCOM - Archive of obsolete content
they are used to create or access well-known objects in xpcom.
... accessing xpcom components from javascript xpcom objects are either created as new instances (each creation gives you a completely new com object) or as services (each access gives you the same com object, often called a singleton).
... whether you must create a new instance or access as a service depends on the contract.
...for example, var nsfile = components.constructor("@mozilla.org/file/local;1", "nsifile", "initwithpath"); var file = new nsfile(filepath); they can also be created and initialized manually: var file = components.classes["@mozilla.org/file/local;1"] .createinstance(components.interfaces.nsifile); file.initwithpath(filepath); this creates a new instance of the object with contract id @mozilla.org/file/local;1 and allows you to call methods from the nsifile interface on it.
JavaScript Debugger Service - Archive of obsolete content
jsd.scripthook = { onscriptcreated: function(script) { // your function here }, onscriptdestroyed: function(script) { // your function here } }; jsd.errorhook = { onerror: function(message, filename, lineno, colno, flags, errnum, exc) { // your function here } }; // triggered when jsd.errorhook[onerror] returns false jsd.debughook = { onexecute: function(frame, type, rv) { // your function here } }; jsd.enumer...
... we create a generic createfilter function that acts as a jsdifilter factory.
... function createfilter(pattern, pass) { var jsdifilter = components.interfaces.jsdifilter; var filter = { globalobject: null, flags: pass ?
... jsd.clearfilters(); // clear the list of filters // we exclude the scripts with the following filenames from being tracked jsd.appendfilter(createfilter("*/firefox/components/*")); jsd.appendfilter(createfilter("*/firefox/modules/*")); jsd.appendfilter(createfilter("xstringbundle")); jsd.appendfilter(createfilter("chrome://*")); jsd.appendfilter(createfilter("x-jsd:ppbuffer*")); jsd.appendfilter(createfilter("xpcsafejsobjectwrapper.cpp")); jsd.appendfilter(createfilter("file://*")); note that appendfilter adds the filter to the end of the list.
Migrating from Internal Linkage to Frozen Linkage - Archive of obsolete content
for errors about undeclared do_createinstance: #include "nscomponentmanagerutils.h" for errors about undeclared do_getservice: #include "nsservicemanagerutils.h" for errors about undeclared ns_getspecialdirectory: #include "nsdirectoryserviceutils.h" utility classes some utility classes could previously be created with ns_new* utility functions.
... these classes must now be created using xpcom: // nsisupportsarray is bad!
...(see xpcom:arrays.) nscomptr<nsisupportsarray> array; - rv = ns_newisupportsarray(getter_addrefs(array)); + array = do_createinstance(ns_supportsarray_contractid); - nscomptr<nsiinputstream> rawstream;- rv = ns_newbyteinputstream(getter_addrefs(rawstream),- (const char*)data, length); + nscomptr<nsistringinputstream> rawstream =+ do_createinstance(ns_stringinputstream_contractid, &rv);+ ns_ensure_success(rv, rv);++ rv = rawstream->setdata((const char*)data, length); ns_ensure_success(rv, rv); nsistringinputstream is not frozen (and thus, not available in the gecko sdk as currently published).
...#define compare(str1, str2, comp) (str1).compare(str2, comp) #define last() endreading()[-1] #define setcharat(c, i) replace(i, 1, ch) #define ns_newisupportsarray(result) callcreateinstance(ns_supportsarray_contractid, static_cast<nsisupportsarray**>(result)); ideally we would switch to nsimutablearray, but in the mean time there's no point changing the same code twice.
Tabbed browser - Archive of obsolete content
js: var myextension = { foo: function(event) { openuilink("http://www.example.com", event, false, true); } } opening a url in an on demand tab cu.import("resource://gre/modules/xpcomutils.jsm"); xpcomutils.definelazyservicegetter(this, "gsessionstore", "@mozilla.org/browser/sessionstore;1", "nsisessionstore"); // create new tab, but don't load the content.
...following this practice minimizes the proliferation of tabs and browsers created by your extension.
...if no such tab exists (perhaps the user closed it or we never opened it in the first place), we create a new tab with our custom attribute.
... var browserenumerator = wm.getenumerator("navigator:browser"); var tabbrowser = browserenumerator.getnext().gbrowser; // create tab var newtab = tabbrowser.addtab(url); newtab.setattribute(attrname, "xyz"); // focus tab tabbrowser.selectedtab = newtab; // focus *this* browser window in case another one is currently focused tabbrowser.ownerdocument.defaultview.focus(); } } the function can be called like so: openandreuseonetabperattribute("myextension-myattribute", "http://developer.mozilla.o...
Compiling The npruntime Sample Plugin in Visual Studio - Archive of obsolete content
build create a new project in visual studio for a win32 gui library (dll) (in .net 2003: win32 template, then switch to dll in application settings in the following dialog, export symbols too?)(in visual studio 2008, it is visualc++|win32|win32 project, then check dll in the wizard).
... if a wizard gives you a checkbox to create an empty project, then check it.
... again note that the resulting dll filename must start with "np", so either call your project like this or rename the file later delete the .cpp and .h and readme files from the project and disk (if you did not create an empty project) copy the npruntime sample plugin source code into the dir of the new vs project and add the files to the project using the vs gui (.cpp files to "source files", .h files to "header files", .rc file to "resource files").
... add the following preprocessor definitions to project properties|(all configurations)|c++|preprocessor|preprocessor definitions: win32;_windows;xp_win32;xp_win;_x86_;npsimple_exports disable precompiled headers using project properties|(all configurations)|c++|precompiled headers|create/use precompiled header.
Creating a Microsummary - Archive of obsolete content
in this tutorial we're going to create a microsummary generator for the spread firefox home page that displays the current firefox download count along with the label fx downloads; for example: 174475447 fx downloads.
... note: if you are a web site developer, and you want to create microsummaries for pages on your site, you can write generators to do so, but a simpler and more efficient approach is to create the microsummaries on the server-side using the same tools and languages you already use to generate pages.
...to begin building the generator, create a new empty text file and add an xml declaration and empty <generator> tag to it: <?xml version="1.0" encoding="utf-8"?> <generator xmlns="http://www.mozilla.org/microsummaries/0.1"> </generator> giving it a name generators should have name attributes which are arbitrary descriptions of the microsummaries the generator creates.
...to do so, we need to put it up on the web and then create a javascript link on some web page that calls firefox's window.sidebar.addmicrosummarygenerator() method to download and install the generator.
Creating a Release Tag - Archive of obsolete content
the mini-branch is created so you can check in the build scripts with the necessary changes without touching the original branch.
... cvs co -r netscape_6_2_release mozilla/client.mk cd mozilla gmake -f client.mk checkout create a mini branch for the pull scripts on all three platforms so we can change them without changing anything on the original branch.
...cvs tag -b mozilla_0_9_4_1_release_mini_branch mozilla/client.mk delete the existing build scripts and repull them from the mini-branch you just created.
... cvs ci mozilla/client.mk create the tag.
Creating regular expressions for a microsummary generator - Archive of obsolete content
by the end of the tutorial, you should know some basics about regular expressions and understand how to create expressions that match urls.
...to learn how to create a microsummary generator, see creating a microsummary.
...here's a url for the same item in that different style: http://cgi.ebay.com/mozilla-firefox-logo-1-inch-pin-badge-button-browser_w0qqitemz280018439106qqihz018qqcategoryz2036qqcmdzviewitem to accommodate these urls, we can create a second regular expression that matches them.
... for the regular expressions we have created in this tutorial, the only xml special character we have to escape is the ampersand.
Editor Embedding Guide - Archive of obsolete content
the first parameter is the nsidomwindow you just retrieved, the second is the editor type you want to create, and the third is whether you want the window editable immediately or when the document is done loading.
... in calling this method, the editor is created underneath and the event listeners are all prepa if (ns_failed(rv)) return ns_error_failure; // we are not setup??!!
... nsicommandparams creating how do you create an nsicommandparams?
... -saari writing once you have created an nsicommandparams you call the "set" methods.
Embedding Mozilla in a Java Application using JavaXPCOM - Archive of obsolete content
creator)appstartup.queryinterface(nsiwindowcreator.ns_iwindowcreator_iid); // get the window watcher service nsiwindowwatcher windowwatcher = (nsiwindowwatcher)servicemanager.getservicebycontractid("@mozilla.org/embedcomp/window-watcher;1", nsiwindowwatcher.ns_iwindowwatcher_iid); // set the window creator (from step 6) windowwatcher.setwindowcreator(windowcreator); // create the root xul window: nsidomwindow win = windowwatcher.openwindow(null, "chrome://your-app/content/window.xul", "mywindow", "chrome,resizable,centerscreen", null); // set this as the active window windowwatcher.setactivewindow(win); // hand over the application to xpcom/xul, this will block: appstartup.run(); here is an example of a locationprovider that works : ...
... following on from the above example, to create a new window, we would do the following: // first, get the event queue service.
... nsieventqueue eventqueue = eventqueueservive.getspecialeventqueue(nsieventqueueservice.ui_thread_event_queue); // now create a proxy for the proxy object manager.
... nsiproxyobjectmanager proxy = (nsiproxyobjectmanager)componentmanager.createinstancebycontractid("@mozilla.org/xpcomproxy;1",null,nsiproxyobjectmanager.ns_iproxyobjectmanager_iid); // and use the proxy object manager to create a proxy for the nsiwindowwatcher instance we created above.
Microsummary XML grammar reference - Archive of obsolete content
for an introduction to how to create a microsummary, read the article creating a microsummary.
... example the microsummary generator created in the creating a microsummary tutorial: <?xml version="1.0" encoding="utf-8"?> <generator xmlns="http://www.mozilla.org/microsummaries/0.1" name="firefox download count"> <template> <transform xmlns="http://www.w3.org/1999/xsl/transform" version="1.0"> <output method="text"/> <template match="/"> <value-of select="id('download-count')"/> <text> fx downloads</text> </template> </transform> </template> <pages> <include>http://(www\.)?spreadfirefox\.com/(index\.php)?</include> </pages> </generator> namespace the namespace uri for microsummary generator xml documents is: http://www.mozilla.org/microsummaries/0.1 all elements in a microsummary generator document should be in this namespace except the ...
...attributes: name (required) a descriptive, human-readable name for the microsummary created by the generator.
...only relevant for generators dynamically created by firefox code and extensions.
New Security Model for Web Services - Archive of obsolete content
more-complex access lists could be created to try to establish, with finer granularity, which domains are to be accessible or permitted from which other domains, but this requires extensive management which at best is quite error-prone for the end user and easily opens holes in a firewall that do not directly hurt the user who reconfigured his browser to try to access some external service but hurts the owners of other services behind th...
...it should be fairly easy for most providers of public resources to create.
...if an entry was not found in the cache creates one by loading the declaration file (web-scripts-access.xml) and extracting information from it (declaration file); requested type and subject princple's prefix are compared to the allowed type and prefix in order to determine access.
... an entry is created if and only if the declaration file is considered valid (validation based on the syntax described above); an invalid document will result in access denial.
Reading textual data - Archive of obsolete content
using utf-8 for this example: */ "utf-8"; const replacementchar = components.interfaces.nsiconverterinputstream.default_replacement_character; var is = components.classes["@mozilla.org/intl/converter-input-stream;1"] .createinstance(components.interfaces.nsiconverterinputstream); is.init(fis, charset, 1024, replacementchar); now you can read string from is: var str = {}; var numchars = is.readstring(4096, str); if (numchars != 0 /* eof */) var read_string = str.value; to read the entire stream and do something with the data: var str = {}; while (is.readstring(4096, str) != 0) { processdata(str.value); } d...
...using utf-8 for this example: */ "utf-8"; var is = components.classes["@mozilla.org/intl/converter-input-stream;1"] .createinstance(components.interfaces.nsiconverterinputstream); // this assumes that fis is the nsiinputstream you want to read from is.init(fis, charset, 1024, 0xfffd); is.queryinterface(components.interfaces.nsiunicharlineinputstream); if (is instanceof components.interfaces.nsiunicharlineinputstream) { var line = {}; var cont; do { cont = is.readline(line); // now you can do something ...
... for example: // first, get and initialize the converter var converter = components.classes["@mozilla.org/intl/scriptableunicodeconverter"] .createinstance(components.interfaces.nsiscriptableunicodeconverter); converter.charset = /* the character encoding you want, using utf-8 here */ "utf-8"; // now, read from the stream // this assumes istream is the stream you want to read from var scriptablestream = components.classes["@mozilla.org/scriptableinputstream;1"] .createinstance(components.interfaces.nsiscript...
...this code will not work for character encodings that contain embedded nulls such as utf-16 and utf-32 // first, get and initialize the converter var converter = components.classes["@mozilla.org/intl/scriptableunicodeconverter"] .createinstance(components.interfaces.nsiscriptableunicodeconverter); converter.charset = /* the character encoding you want, using utf-8 here */ "utf-8"; // this assumes that 'file' is a variable that contains the file you want to read, as an nsifile var fis = components.classes["@mozilla.org/network/file-input-stream;1"] .createinstance(components.interfaces.nsifileinputstream); fi...
Learn XPI Installer Scripting by Example - Archive of obsolete content
defaults\ icons\ plugins\ res\ note that this high-level structure parallels the directory structure of the installed browser very closely: as you will see in the installation script, the contents of the archive are installed onto the file system in much the same way that they are stored in the archive itself, though it's possible to rearrange things arbitrarily upon installation--to create new directories, to install files in system folders and other areas.
...the initinstall() method on the install object creates a new installation for the specified software and version.
... the files are added in lines 26-41: err = adddirectory("program", "6.0.0.2000110807", "bin", // jar source folder communicatorfolder, // target folder "", // target subdir true ); // force flag logcomment("adddirectory() returned: " + err); // create the plugins folder next to mozilla var pluginsfolder = getfolder("plugins"); if (!fileexists(pluginsfolder)) { var ignoreerr = dircreate(pluginsfolder); logcomment("dircreate() returned: " + ignoreerr); } else logcomment("plugins folder already exists"); in this case, the files are contained within a single directory, so calling the install object's adddirectory meth...
... the install log is created in the product directory by default (where the browser executable is).
Accessing Files - Archive of obsolete content
accessing files this section describes how to create a file reference.
...once one of these starting directories is determined, a file reference may be created relative to this.
...if the file does not exist, you may wish to create it.
... the file object has a nsifile.create() method which may be used to create an empty file, or you can open a writing stream and write to the file.
How to implement a custom XUL query processor component - Archive of obsolete content
xul supports templating to create a block of content from a datasource query.
... in this example, we will create a simple javascript xpcom component.
...it is used to create an instance of our xpcom object.
... // eventually we should read the <query> to create filters return this._data; }, generateresults: function(adatasource, aref, aquery) { // preform any query and pass the data to the result set return new templateresultset(this._data); }, addbinding: function(arulenode, avar, aref, aexpr) { // add a variable binding for a particular rule, which we aren't using yet }, translateref: function(adatasource, arefstring) { ...
MenuButtons - Archive of obsolete content
a button or toolbarbutton with a type attribute set to 'menu' creates a button that will open a menu when pressed.
... a button or toolbarbutton with a type attribute set to 'menu-button' creates a button that can be pressed normally.
...to create a button of this type, set the type attribute of the button to 'menu'.
...to create a button of this type, set the type attribute of the button to 'menu-button'.
Introduction - Archive of obsolete content
the template builder loads an rdf datasource using the rdf service in the same way as you would create a datasource through the rdf service directly.
...once some data starts arriving, the template builder scans its information to see if some results can be created.
...this file will be loaded and the resulting xml document will be used as the datasource when the template builder generates results and creates content.
...when multiple datasources are used, an nsirdfcompositedatasource is created to hold all of the datasources.
Special Condition Tests - Archive of obsolete content
for instance, if the container was a <vbox>, a rule could be created that would only match a <vbox> element.
... <groupbox uri="rdf:*"> <caption label="rdf:http://purl.org/dc/elements/1.1/title"/> </groupbox> </rule> <rule> <label uri="rdf:*" value="rdf:http://www.xulplanet.com/rdf/address"/> </rule> </template> </vbox> on the first pass, the container where generated content would be inserted is a <vbox>, so the first rule will match and a captioned <groupbox> will be created.
... on the next pass, the parent container will be the element with the uri attribute from the previous pass, in this case, the <groupbox> the first rule will not match in this case, but the second rule will match and a label will be created.
...you will commonly use the two attributes iscontainer and isempty together in different combinations to create the effect you need.
textbox (Toolkit autocomplete) - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] this element is created by setting the type attribute of the textbox to autocomplete.
... it is used to create a textbox with a popup containing a list of possible completions for what the user has started to type.
...the example below will create an autocomplete textbox that will search the user's history.
...the components are created using the name @mozilla.org/autocomplete/search;1?name= where name is listed in this attribute.
Textbox (XPFE autocomplete) - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] this element is created by setting the type attribute of a textbox to autocomplete.
... it is used to create a textbox with a popup containing a list of possible completions for what the user has started to type.
...the components are created using the name @mozilla.org/autocomplete/search;1?name= where name is listed in this attribute.
...this can be used to create a customized autocomplete results list.
Things I've tried to do with XUL - Archive of obsolete content
xbl in listboxes using xbl bindings in listboxes is not easy because there is a big bug there: if you create from js an element you want to bind, and if it is hidden when the listbox is first rendered, the listbox does not create a frame for it, and the xbl doesn't get attached...
... a workaround for that is to create the element, insert it in the document and set its style attribute with a -moz-binding property, all of that from c++ instead of js.
... multi-column listboxes when adding items to multi-column listboxes, you can't use the appenditem api: // auto-create and attach 1st cell var row = mylistbox.appenditem( label, value ); // create and attach 2nd cell var cell = document.createelement('listcell'); cell.setattribute('label', label2 ); cell.setattribute('value', value2 ); row.appendchild( cell ); // etc // ...
...instead, you must build up your own listitem full of listcells, and then add that listitem to the listbox, using generic dom calls: var row = document.createelement('listitem'); // create and attach 1st cell var cell = document.createelement('listcell'); cell.setattribute('label', label ); cell.setattribute('value', value ); row.appendchild( cell ); // create and attach 2nd cell cell = document.createelement('listcell'); cell.setattribute('label', label2 ); cell.setattribute('value', value2 ); row.appendchild( cell ); // etc // ...
Creating toolbar buttons (Customize Toolbar Window) - Archive of obsolete content
creating an overlay the first step is to create an overlay for the document containing the toolbar you wish to enhance.
...this is the code to create and add it in.
... let button = doc.createelement("toolbarbutton"); button.setattribute("id", button_id); button.setattribute("label", "replace bookmark"); button.setattribute("class", "toolbarbutton-1 chromeclass-toolbar-additional"); button.setattribute("tooltiptext", "replace an existing bookmark"); button.style.liststyleimage = "url(" + icon + ")"; button.addeventlistener("command", main.action, false); toolbox.palette.appendchild(button); this code is thanks to dgutov and is seen in full context at his repository here at github: dgutov / bmreplace / bootstrap.js.
... the stylesheet to set the image for your toolbar button, use the following css rules: /* skin/toolbar-button.css */ #myextension-button { list-style-image: url("chrome://myextension/skin/btn_large.png"); } toolbar[iconsize="small"] #myextension-button { list-style-image: url("chrome://myextension/skin/btn_small.png"); } applying the stylesheet remember to attach the stylesheet you created to both the overlay file and the customize toolbar window.
Adding Buttons - Archive of obsolete content
adding buttons to a window the window we've created so far has had nothing in it, so it isn't very interesting yet.
... like html, xul has a number of tags that can be used to create user interface elements.
...this element is used to create simple buttons.
... the findfile.xul example let's add this code to the file findfile.xul that we created in the previous section.
Box Objects - Archive of obsolete content
it's relatively simple to determine what kind of content tree node will be created for a given element.
...the layout objects that will be created are determined in a more complex manner.
...the layout object associated with an element can be removed and a completely different type of object created just by changing the css display property, among others.
... for example changing the display property of a button element to block will cause the button layout object to be deleted and a block object to be created instead.
Tabboxes - Archive of obsolete content
we'll find out how to create them here.
... xul provides a method to create such dialogs.
...we'll create an options tab (and select it by default) that will contain some options for searching.
... find files example so far : source view next, we'll look at how to create grids of content.
Tree View Details - Archive of obsolete content
creating a hierarchical custom view in the last section, we created a simple tree view that implemented only a minimum amount of functionality.
...here, we will examine how to create a hierarchical set of items using the view.
...the tree box object will be created by the tree for you and you can call its functions.
... complete example there are several other view functions we can implement but they don't need to do anything in this example, so we can create functions that do nothing for those.
Using the Editor from XUL - Archive of obsolete content
it passes two parameters; the first indicates whether we want a plain text or html editor (pass text or html here), and the second is the <iframe> element on which we wish to create the editor.
... the important stuff in editorstartup() begins where we get or create an editorshell.
... the <editor> tag actually creates an nseditorboxobject behind the scenes.
... the nseditorboxobject creates an nseditorshell, and holds the owning reference to it.
button - Archive of obsolete content
checkstate type: integer, values 0, 1, or 2 this attribute may be used to create three state buttons, numbered 0, 1 and 2.
...if this attribute is not present, a normal button is created.
... menu set the type attribute to the value menu to create a button with a menu popup.
... menu-button you can also use the value menu-button to create a button with a menu.
menu - Archive of obsolete content
ArchiveMozillaXULmenu
this element is also used to create submenus.
...qualnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata appenditem( label, value ) return type: element creates a new item and adds it to the end of the existing list of items.
...the function returns the newly created element.
... insertitemat( index, label, value ) return type: element this method creates a new item and inserts it at the specified position.
richlistbox - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] this element is used to create a list of listitems (richlistitems), similar to a listbox, but is designed to be used when the items do not contain simple text content.
... appenditem( label, value ) return type: element creates a new item and adds it to the end of the existing list of items.
...the function returns the newly created element.
... insertitemat( index, label, value ) return type: element this method creates a new item and inserts it at the specified position.
toolbar - Archive of obsolete content
the chromeclass-toolbar class may be used to create a toolbar where its visibility depends on the toolbar flag when opening the window with the window interface's open() method loads the specified resource into the browsing context (window, <iframe> or tab) with the specified name.
...in earlier versions, a copy of each item was created and placed on the toolbar.
...some special ids may also be used to create special spacing items: separator: a separator, which is drawn as a vertical bar.
... the method returns the dom element for the created item.
Using LDAP XPCOM with XULRunner - Archive of obsolete content
this will create two files in the components directory of the build package: mozldap.dll (or libmozldap.so or...) mozldap.xpt and two files in the root directory of the build package: on windows: nsldap32v50.dll nsldappr32v50.dll on linux: libldap50.so libprldap50.so those are the native ldap library.
...create a subdirectory extensions/ldapstub in the mozilla source code directory, containing two files, makefile.in and ldapstubloader.cpp: makefile.in: # copyright (c) 2005 benjamin smedberg <benjamin@smedbergs.us> depth = ../..
...this will create a new file in the components subdirectory of the built package, mozldap_stub.dll (on windows) or libmozldap_stub.so (on linux).
...create a libraries subdirectory in your xul app directory, and copy mozldap.dll (or libmozldap.so), and the native ldap binaries into it.
2006-10-20 - Archive of obsolete content
christopher would not like to learn how to create a build of firefox with custom extensions and not have those extensions appear in the addons window.
... nsis and my extension jan vávra is wondering how he could create a win32 installer of thunderbird that when executed, it would also install his extensions of choice.
... benjamin smedberg mentioned in his post that jan vávra needs to add the extension files to the packaging manifest, which is used to create the installer.
... robert kaiser also suggested replacing luna, a machine used to create gtk1 builds, with a machine thats sole responsibility is to only the tests on builds from the official nightly machines.
Extentsions FAQ - Archive of obsolete content
var newnode = document.createelement(" ...
... how to create a dynamic drop down menu that may have submenus using javascript for an extension?
... these are called "grippies" <https://addons.mozilla.org/firefox/2242/> this extension brings grippies back to firefox (and thunderbird!) is there any way to write a regular extension that returns a "dummy" object when an instance of "@mozilla.org/helperapplauncherdialog;1" is created?
... is it possible to create a sidebar on the top of the page?
NPN NewStream - Archive of obsolete content
stream stream to be created by the browser.
... description npn_newstream creates a new stream of data produced by the plug-in and consumed by the browser.
... the mime parameter is the mime type of the plug-in to create.
... a plug-in can create another instance of itself by specifying its own mime type and a new target name in a call to npn_newstream.
NPAPI plugin reference - Archive of obsolete content
npn_createobject allocates a new npobject.
... npn_geturl asks the browser to create a stream for the specified url.
... npp_new creates a new instance of a plug-in.
... npp_setwindow tells the plug-in when a window is created, moved, sized, or destroyed.
The First Install Problem - Archive of obsolete content
if the hkey_local_machine\software\mozillaplugins key doesn't exist, create it, and write the vendor-determined plid for each module that the vendor wishes to install.
... example: a piece of software called myapplication might create hkey_local_machine\software\mozillaplugins\@mycompany.com/myapplication,version=5.0.1/ where the plid is something the corporation that makes myapplication (mycompany inc.) determines.
... caveat emptor: if the key cannot be created under hkey_local_machine, create it as hkey_current_user\software\mozillaplugins\ under hkey_current_user.
... add the following values to the newly created key -- some are string values (reg_sz), and some are actually subkeys.
ActiveXObject - Archive of obsolete content
typename the type or class of the object to create.
... location optional the name of the network server where the object is to be created.
... to create an automation object, assign the new activexobject to an object variable: var excelapp = new activexobject("excel.application"); var excelsheet = new activexobject("excel.sheet"); this code starts the application creating the object (in this case, a microsoft excel worksheet).
... once an object is created, you refer to it in code using the object variable you defined.
GetObject - Archive of obsolete content
objectype type or class of object to create.
...for information on how to create this string, see the documentation for the application that created the object.
...for example: myobject.line(9, 90); myobject.inserttext(9, 100, "hello, world."); myobject.saveas("c:\\drawings\\sample.drw"); note: use the getobject function when there is a current instance of the object, or if you want to create the object with a file already loaded.
... if an object has registered itself as a single-instance object, only one instance of the object is created, no matter how many times activexobject is executed.
VBArray.lbound - Archive of obsolete content
the first part is vbscript code to create a visual basic safe array.
...since the safe array is created in vbscript rather than visual basic, the lower bound will always be zero.
... <head> <script type="text/vbscript"> <!-- function createvbarray() dim i, j, k dim a(2, 2) k = 1 for i = 0 to 2 for j = 0 to 2 a(j, i) = k k = k + 1 next next createvbarray = a end function --> </script> <script type="text/javascript"> <!-- function vbarraytest(vba){ var i; var a = new vbarray(vba); var s = ""; for (i = 1; i <= a.dimensions(); i++) { s += "the lower bound of dimension "; s += i + " is "; s += a.lbound(i); s += ".<br />"; } return (s); } --> </script> </head> <body> <script type="text/javascript"> document.write(vbarraytes...
...t(createvbarray())); </script> </body> requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, and internet explorer 10 standards.
VBArray - Archive of obsolete content
remarks vbarrays are read-only, and cannot be created directly.
...the first part is vbscript code to create a visual basic safe array.
... <head> <script type="text/vbscript"> <!-- function createvbarray() dim i, j, k dim a(2, 2) k = 1 for i = 0 to 2 for j = 0 to 2 a(j, i) = k document.writeln(k) k = k + 1 next document.writeln("<br />") next createvbarray = a end function --> </script> <script type="text/javascript"> <!-- function vbarraytest(vbarray){ var a = new vbarray(vbarray); var b = a.toarray(); var i; for (i = 0; i < 9; i++) { document.writeln(b[i]); } } --> </script> </head> ...
...<body> <script type="text/javascript"> <!-- vbarraytest(createvbarray()); --> </script> </body> properties the vbarray object has no properties.
Writing JavaScript for XHTML - Archive of obsolete content
solution: use dom methods many people avoided dom methods because of the typing to create one simple element, when document.write() worked.
...use dom methods to create all of your elements, attributes and other nodes.
... this is xml proof, as long as you keep the namespace problem in focus (e.g., there is a document.createelementns method).
... for completeness here is the accept field, that firefox 2.0.0.9 sends with its requests: accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5 further reading you will find several useful articles in the developer wiki: xml in mozilla dom xml introduction xml extras dom 2 methods you will need are: dom:document.createelementns dom:document.getelementsbytagnamens see also properly using css and javascript in xhtml documents ...
XForms Repeat Element - Archive of obsolete content
my:line[index('lineset')]/@name"/> <setvalue ref="/my:lines/my:line[index('lineset')]/price">0.00</setvalue> </action> </trigger> <trigger> <label>remove current item</label> <delete ev:event="domactivate" nodeset="/my:lines/my:line" at="index('lineset')"/> </trigger> attribute based repeat when using xforms within host languages like xhtml, it is often necessary to create repeating structures within constructs such as html:table.
... thus, one might wish to use element repeat within a table to create the rows of a table, where each row of the table binds to a distinct member of a homogeneous collection.
...similarly, the index function can be used with the repeating structures created via these repeat-attributes.
...here comes the output: <br/> <xf:output ref="@id"><xf:label>output: </xf:label></xf:output> <div xf:repeat-nodeset="nest"><xf:output ref="."><xf:label>nested output: </xf:label></xf:output></div> </div> repeat in anonymous content (usage in xbl) you can use repeat elements inside anonymous content to create powerful new widgets.
Using the DOM File API in chrome code - Extensions
in fact, you get one bonus feature: you can create file objects specifying the path of the file on the user's computer.
... in bootstrap scope, this must be imported in like so: cu.importglobalproperties( [ "file" ] ) accessing a file by hard-coded pathname to reference a file by its path, you can simply use a string literal: var file = file.createfromfilename("path/to/some/file"); cross platform note: however using hard-coded paths raises cross platform issues since it uses a platform-dependent path separator (here "/").
...you can do so like this: var dsfile = components.classes["@mozilla.org/file/directory_service;1"] .getservice(components.interfaces.nsiproperties) .get("profd", components.interfaces.nsifile); dsfile.append("myfilename.txt"); var file = file.createfromnsifile(dsfile); this uses the directory service to locate the profile directory (with the location key "profd", see below for more details), then appends the name of the file we want to work with by calling nsifile.append().
... finally, we instantiate the file object by calling file.createfromnsifile.
Examples - Game development
tanx a multiplayer tank battle game, created with playcanvas.
...again, created with playcanvas.
... browserquest a mmorpg created by the little workshop and mozilla.
...created using three.js.
Tiles and tilemaps overview - Game development
this set of articles covers the basics of creating tile maps using javascript and canvas (although the same high level techniques could be used in any programming language.) besides the performance gains, tilemaps can also be mapped to a logical grid, which can be used in other ways inside the game logic (for example creating a path-finding graph, or handling collisions) or to create a level editor.
... the logic grid since tilemaps are an actual grid of visual tiles, it is common to create a mapping between this visual grid and a logic grid.
... isometric tilemaps isometric tilemaps create the illusion of a 3d environment, and are extremely popular in 2d simulation, strategy or rpg games.
...a better way would be to create a canvas that is 2x2 tiles bigger than the visible area, so there is one tile of "bleeding" around the edges.
Physics - Game development
add the physics.startsystem() method at the beginning of the create function (make it the first line inside the function), as shown below: game.physics.startsystem(phaser.physics.arcade); next, we need to enable our ball for the physics system — phaser object physics is not enabled by default.
... add the following line at the bottom of the create() function: game.physics.enable(ball, phaser.physics.arcade); next, if we want to move our ball on the screen, we can set velocity on its body.
... add the following line, again at the bottom of create(): ball.body.velocity.set(150, 150); removing our previous update instructions remember to remove our old method of adding values to x and y from the update() function: function update() { ball.x += 1; ball.y += 1; } we are now handling this properly, with a physics engine.
... final code check the latest code should look like this: var ball; function preload() { game.scale.scalemode = phaser.scalemanager.show_all; game.scale.pagealignhorizontally = true; game.scale.pagealignvertically = true; game.stage.backgroundcolor = '#eee'; game.load.image('ball', 'img/ball.png'); } function create() { game.physics.startsystem(phaser.physics.arcade); ball = game.add.sprite(50, 50, 'ball'); game.physics.enable(ball, phaser.physics.arcade); ball.body.velocity.set(150, 150); } function update() { } try reloading index.html again — the ball should now be moving constantly in the given direction.
Grid Lines - MDN Web Docs Glossary: Definitions of Web-related terms
grid lines are created when you define tracks in the explicit grid using css grid layout.
... lines are also created in the implicit grid when implicit tracks are created to hold content positioned outside of the explicit grid, however these lines cannot be addressed by a number.
... placing items onto the grid by line number having created a grid, you can place items onto the grid by line number.
...ffa94d; border-radius: 5px; background-color: #ffd8a8; padding: 1em; color: #d9480f; } <div class="wrapper"> <div class="item">item</div> </div> .wrapper { display: grid; grid-template-columns: repeat(3, 1fr); grid-template-rows: 100px 100px; } .item { grid-column-start: 1; grid-column-end: 3; grid-row-start: 1; grid-row-end: 3; } naming lines the lines created in the explicit grid can be named, by adding the name in square brackets before or after the track sizing information.
Mutable - MDN Web Docs Glossary: Definitions of Web-related terms
hence the need for garbage collection.) a mutable object is an object whose state can be modified after it is created.
... immutables are the objects whose state cannot be changed once the object is created.
...lets understand this with an example: var immutablestring = "hello"; // in the above code, a new object with string value is created.
... on appending the "immutablestring" with a string value, following events occur: existing value of "immutablestring" is retrieved "world" is appended to the existing value of "immutablestring" the resultant value is then allocated to a new block of memory "immutablestring" object now points to the newly created memory space previously created memory space is now available for garbage collection.
Test your skills: HTML accessibility - Learn web development
try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
Creating fancy letterheaded paper - Learn web development
in this assessment we'll challenge you to create an online template to achieve such a look.
... project brief you have been given the files needed to create a letterheaded paper template.
... hints and tips remember that you can create a fallback for older browsers by putting the fallback version of a declaration first, followed by the version that works across newer browsers only.
... feel free to create your own graphics for the assessment if you wish.
The box model - Learn web development
previous overview: building blocks next everything in css has a box around it, and understanding these boxes is key to being able to create layouts with css, or to align items with other items.
...the model defines how the different parts of a box — margin, border, padding, and content — work together to create a box that you can see on the page.
...style, or color of a single side, you can use one of the most granular longhand properties: border-top-width border-top-style border-top-color border-right-width border-right-style border-right-color border-bottom-width border-bottom-style border-bottom-color border-left-width border-left-style border-left-color in the example below we have used various shorthands and longhands to create borders.
...some of the properties can apply to inline boxes too, such as those created by a <span> element.
Flexbox - Learn web development
prerequisites: html basics (study introduction to html), and an idea of how css works (study introduction to css.) objective: to learn how to use the flexbox layout system to create web layouts.
...we are going to use these to create a fairly standard three column layout.
...for example, you could make the "blush" button appear at the start of the main axis using the following rule: button:last-child { order: -1; } nested flex boxes it is possible to create some pretty complex layouts with flexbox.
...the buttons will take up as much space as they can and sit as many on the same line as they can, but when they can no longer fit comfortably on the same line, they'll drop down to create new lines.
Multiple-column layout - Learn web development
prerequisites: html basics (study introduction to html), and an idea of how css works (study introduction to css.) objective: to learn how to create multiple-column layout on webpages, such as you might find in a newspaper.
...the column-count property will create as many columns as the value you give it, so if you add the following css to your stylesheet and reload the page, you will get three columns: .container { column-count: 3; } the columns that you create have flexible widths — the browser works out how much space to assign each column.
...cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</p> </div> .container { column-width: 200px; } styling the columns the columns created by multicol cannot be styled individually.
...it lies across the gap you created with column-gap.
Positioning - Learn web development
or if you want to create a ui element that floats over the top of other parts of the page, and/or always sits in the same place inside the browser window no matter how much the page is scrolled?
...this is very useful: it means that we can create isolated ui features that don't interfere with the layout of other elements on the page.
...this means that you can create useful ui items that are fixed in place, like persisting navigation menus that are always visible no matter how much the page scrolls.
...ut id ornare felis, eget fermentum sapien.</p> body { width: 500px; margin: 0 auto; } .positioned { background: rgba(255,84,104,.3); border: 2px solid rgb(255,84,104); padding: 10px; margin: 10px; border-radius: 5px; } .positioned { position: sticky; top: 30px; left: 30px; } an interesting and common use of position: sticky is to create a scrolling index page where different headings stick to the top of the page as they reach it.
How CSS is structured - Learn web development
to create an internal stylesheet, you place css inside a <style> element contained inside the html <head>.
... playing with the css in this article for the exercise that follows, create a folder on your computer.
...inside the folder, copy the text below to create two files: index.html: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>my css experiments</title> <link rel="stylesheet" href="styles.css"> </head> <body> <p>create your test html here</p> </body> </html> styles.css: /* create your test css here */ p { color: red; } when you find css that you want to experiment with, replace the html <body> contents with some html to style, and then add your test css code to your css file.
...for example, @import imports a stylesheet into another css stylesheet: @import 'styles2.css'; one common @rule that you are likely to encounter is @media, which is used to create media queries.
How do you host your website on Google App Engine? - Learn web development
creating a google cloud platform project to use google's tools for your own site or app, you need to create a new project on google cloud platform.
... go to the app engine dashboard on the google cloud platform console and press the create button.
... if you've not created a project before, you'll need to select whether you want to receive email updates or not, agree to the terms of service, and then you should be able to continue.
...for this tutorial, the following values are used: project name: gae sample site project id: gaesamplesite click the create button to create your project.
Client-side form validation - Learn web development
this validation is completely customizable, but you need to create it all (or use a library).
... constraining the length of your entries you can constrain the character length of all text fields created by <input> or <textarea> by using the minlength and maxlength attributes.
...create a new copy of the fruit-start.html file.
...the difficult part is to make it generic enough to use both cross-platform and on any form you might create.
Other form controls - Learn web development
select box a simple select box is created with a <select> element with one or more <option> elements as its children, each of which specifies one of its possible values.
... the <option> elements can be nested inside <optgroup> elements to create visually associated groups of values: <select id="groups" name="groups"> <optgroup label="fruits"> <option>banana</option> <option selected>cherry</option> <option>lemon</option> </optgroup> <optgroup label="vegetables"> <option>carrot</option> <option>eggplant</option> <option>potato</option> </optgroup> </select> on the <optgroup> element, the value of the label attribute ...
...such a bar is created using a <progress> element.
... such a bar is created using a <meter> element.
Styling web forms - Learn web development
previous overview: forms next in the previous few articles we looked at all the html you'll need to create and structure your web forms.
... not all widgets are created equal when css is involved at present, some difficulties remain when using css with forms.
... if you want to thoroughly customize those widgets, you really have to create your own using html, css, and javascript.
...ff2'), url('fonts/veteran_typewriter-webfont.woff') format('woff'); font-weight: normal; font-style: normal; } body { font : 1.3rem sans-serif; padding : 0.5em; margin : 0; background : #222; } form { position : relative; width : 740px; height : 498px; margin : 0 auto; padding: 1em; box-sizing: border-box; background : #fff url(background.jpg); /* we create our grid */ display : grid; grid-gap : 20px; grid-template-columns : repeat(2, 1fr); grid-template-rows : 10em 1em 1em 1em; } notice that we've used some css grid and flexbox to lay out the form.
Define terms with HTML - Learn web development
prerequisites: you need to be familiar with how to create a basic html document.
... i'm feeling blue but we're constantly defining keywords informally, as here: firefox is the web browser created by the mozilla foundation.
...note that <dfn> tags go around the word to be defined, not the definition (the definition consists of the entire paragraph): <p><dfn>firefox</dfn> is the web browser created by the mozilla foundation.</p> another use for bold is to emphasize content.
...if you want a more formal relationship, or your definition consists of only one sentence rather than the whole paragraph, you can use the aria-describedby attribute to associate a term more formally with its definition: <p> <span id="ff"> <dfn aria-describedby="ff">firefox</dfn> is the web browser created by the mozilla foundation.
Use HTML to solve common problems - Learn web development
LearnHTMLHowto
how to create a basic html document how to divide a webpage into logical sections how to set up a proper structure of headings and paragraphs basic text-level semantics html specializes in providing semantic information for a document, so html answers many questions you might have about how to get your message across best in your document.
... how to create a list of items with html how to stress or emphasize content how to indicate that text is important how to display computer code with html how to annotate images and graphics how to mark abbreviations and make them understandable how to add quotations and citations to web pages how to define terms with html hyperlinks one of the main reasons for html is making navigation easy with hyperlinks, which can be used in many different ways: how to create a hyperlink how to create a table of contents with html images & multimedia how to add images to a webpage how to add video content to a webpage scripting & styling html only sets up document structure.
...here is where you should start: how to create a simple web form how to structure a web form tabular information some information, called tabular data, needs to be organized into tables with columns and rows.
... it's one of the most complex html structures, and mastering it is not easy: how to create a data table how to make html tables accessible data representation how to represent numeric and code values with html — see superscript and subscript, and representing computer code.
HTML text fundamentals - Learn web development
you just need to bear in mind a few best practices as you create such structures: preferably, you should use a single <h1> per page—this is the top level heading, and all others sit below this in the hierarchy.
... milk eggs bread hummus every unordered list starts off with a <ul> element—this wraps around all the list items: <ul> milk eggs bread hummus </ul> the last step is to wrap each list item in a <li> (list item) element: <ul> <li>milk</li> <li>eggs</li> <li>bread</li> <li>hummus</li> </ul> active learning: marking up an unordered list try editing the live sample below to create your very own html unordered list.
...ept that you have to wrap the list items in an <ol> element, rather than <ul>: <ol> <li>drive to the end of the road</li> <li>turn right</li> <li>go straight across the first two roundabouts</li> <li>turn left at the third roundabout</li> <li>the school is on your right, 300 meters up the road</li> </ol> active learning: marking up an ordered list try editing the live sample below to create your very own html ordered list.
...in the next article, we'll be looking in detail at how to create hyperlinks, possibly the most important element on the web.
Adding vector graphics to the Web - Learn web development
the svg format allows us to create powerful vector graphics for use on the web.
...more advanced svg features include <fecolormatrix> (transform colors using a transformation matrix,) <animate> (animate parts of your vector graphic,) and <mask> (apply a mask over the top of your image.) as a simple example, the following code creates a circle and a rectangle: <svg version="1.1" baseprofile="full" width="300" height="200" xmlns="http://www.w3.org/2000/svg"> <rect width="100%" height="100%" fill="black" /> <circle cx="150" cy="100" r="90" fill="blue" /> </svg> this creates the following output: from the example above, you may get the impression that svg is easy to handcode.
...these packages allow you to create a variety of illustrations using various graphics tools, and create approximations of photos (for example inkscape's trace bitmap feature.) svg has some additional advantages besides those described so far: text in vector images remains accessible (which also benefits your seo).
... svg can be harder to create than raster images, depending on what kind of image you are trying to create.
Looping code - Learn web development
for each iteration, create a new paragraph and append it to the output <div>, which we've selected using const output = document.queryselector('.output');.
... in comments, we've provided you with three code lines that need to be used somewhere inside the loop: const para = document.createelement('p'); — creates a new paragraph.
...ve output</h2> <div class="output" style="height: 410px;overflow: auto;"> </div> <h2>editable code</h2> <p class="a11y-label">press esc to move focus away from the code area (tab inserts a tab character).</p> <textarea id="code" class="playable-code" style="height: 300px;width: 95%"> let output = document.queryselector('.output'); output.innerhtml = ''; // let i = 10; // const para = document.createelement('p'); // para.textcontent = ; // output.appendchild(para); </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="reset"> <input id="solution" type="button" value="show solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10...
...er('click', function() { if(solution.value === 'show solution') { textarea.value = solutionentry; solution.value = 'hide solution'; } else { textarea.value = userentry; solution.value = 'show solution'; } updatecode(); }); let jssolution = 'const output = document.queryselector(\'.output\');\noutput.innerhtml = \'\';\n\nlet i = 10;\n\nwhile(i >= 0) {\n let para = document.createelement(\'p\');\n if(i === 10) {\n para.textcontent = \'countdown \' + i;\n } else if(i === 0) {\n para.textcontent = \'blast off!\';\n } else {\n para.textcontent = i;\n }\n\n output.appendchild(para);\n\n i--;\n}'; let solutionentry = jssolution; textarea.addeventlistener('input', updatecode); window.addeventlistener('load', updatecode); // stop tab key tabbing out of textarea and // make it ...
Test your skills: Events - Learn web development
events 1 in our first events-related task, you need to create a simple event handler that causes the text inside the button (btn) to change when it is clicked on, and change back when it is clicked again.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
Video and Audio APIs - Learn web development
here is a <a href="rabbit320.mp4">link to the video</a> instead.</p> </video> this creates a video player inside the browser like so: you can review what all the html features do in the article linked above; for our purposes here, the most interesting attribute is controls, which enables the default set of playback controls.
...just for fun, we are providing two reporting mechanisms — a <span> containing the elapsed time in minutes and seconds, and an extra <div> that we will use to create a horizontal indicator bar that gets longer as the time elapses.
... create a new javascript file in the same directory level as your index.html file.
...when invoked, setinterval() creates an active interval, meaning that it runs the function given as the first parameter every x milliseconds, where x is the value of the 2nd parameter.
Test your skills: Arrays - Learn web development
in this task we'd like you to create an array of three items, stored inside a variable called myarray.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
Test your skills: Strings - Learn web development
try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
Storing the information you need — Variables - Learn web development
declaring a variable to use a variable, you've first got to create it — more accurately, we call this declaring the variable.
...back when javascript was first created, there was only var.
...so, let was created in modern versions of javascript, a new keyword for creating variables that works somewhat differently to var, fixing its issues in the process.
... summary by now you should know a reasonable amount about javascript variables and how to create them.
Object building practice - Learn web development
type in the following to create a new ball instance: let testball = new ball(50, 100, 4, 4, 'blue', 10); try calling its members: testball.x testball.size testball.color testball.draw() when you enter the last line, you should see the ball draw itself somewhere on the canvas.
... first, we need to create somewhere to store all our balls and then populate it.
...andom(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.
... runs the function again using the requestanimationframe() method — when this method is repeatedly run and passed the same function name, it runs that function a set number of times per second to create a smooth animation.
Ember app structure and componentization - Learn web development
using the cli to create our components for us so to represent our app, we want to create 4 components: header list individual todo footer to create a component, we use the ember generate component command, followed by the name of the component.
... let’s create the header component first.
... enter the following command into your terminal: ember generate component header these will generate some new files, as shown in the resulting terminal output: installing component create app/components/header.hbs skip app/components/header.js tip to add a class, run `ember generate component-class header` installing component-test create tests/integration/components/header-test.js header.hbs is the template file where we’ll include the html structure for just that component.
... before we start adding any component code, let’s create the scaffolding for the other components.
Adding a new todo form: Vue events, methods, and models - Learn web development
let's create a new component that will allow us to add a new to-do item.
... in your components folder, create a new file called todoform.vue.
...the next thing we need to be able to do is pass the newly-created to-do item to our app component.
... export default { name: 'app', components: { todoitem, todoform }, data() { return { todoitems: [ { id:uniqueid('todo-'), label: 'learn vue', done: false }, { id:uniqueid('todo-'), label: 'create a vue project with the cli', done: true }, { id:uniqueid('todo-'), label: 'have fun', done: true }, { id:uniqueid('todo-'), label: 'create a to-do list', done: false } ] }; }, methods: { addtodo() { console.log('to-do added'); } } }; next, add an event listener for the todo-added event to the <to-do-form></to-do-form>, which calls the addtodo() ...
Focus management with Vue refs - Learn web development
for convenience, create a new method which takes no arguments called focusoneditbutton().
...this lifecycle spans from all the way before elements are created and added to the vdom (mounted), until they are removed from the vdom (destroyed).
... beforecreate() — runs before the instance of your component is created.
... created() — runs after your component is initialized but before the component is added to the vdom.
Handling common accessibility problems - Learn web development
you have a few options here: create custom controls using <button> elements (which we can tab to by default!) and javascript to wire up their functionality.
... create keyboard shortcuts via javascript, so functionality is activated when you press certain keys on the keyboard.
...we have already mentioned a couple of accessibility tips involving css: use the correct semantic elements to mark up different content in html; if you want to create a different visual effect, use css — don't abuse an html element to get the look you want.
... more complex javascript implementations can create issues with accessibility — you need to do what you can.
Simple Instantbird build
first, cd into the comm-central subdirectory (created automatically by the previous command): cd comm-central then run: python client.py checkout note: unless you have a very good network connection, "hg clone" might fail because it gets interrupted.
... build configuration by default, the build system creates a release build of instantbird roughly equivalent to the official instantbird release builds.
...for example, to create a debug build instead of a release build, that file would contain: ac_add_options --enable-debug for more on configuration options, see the page configuring build options.
... building instantbird what you need to do to build instantbird rather than firefox is: echo 'ac_add_options --enable-application=im' >> .mozconfig to start the build, cd into the comm-central subdirectory (created automatically by the hg clone command), and run: ./mozilla/mach build mach is our command-line tool to streamline common developer tasks.
Performance best practices for Firefox front-end engineers
if you need more elevated privileges than a standard worker allows, consider using a chromeworker, which is a firefox-only api which lets you create workers with more elevated privileges.
...the api is straightforward: create the documentfragment by calling document.createdocumentfragment().
... create each child element (by calling document.createelement() for example), and add each one to the fragment by calling documentfragment.appendchild().
... this example has been cribbed from davidwalsh’s blog post: // create the fragment var frag = document.createdocumentfragment(); // create numerous list items, add to fragment for(var x = 0; x < 10; x++) { var li = document.createelement("li"); li.innerhtml = "list item " + x; frag.appendchild(li); } // mass-add the fragment nodes to the list listnode.appendchild(frag); the above is strictly cheaper than individually adding each node to the dom.
Storage access policy: Block cookies from trackers
messaging and workers: broadcast channel: attempts to create a new broadcastchannel will throw a securityerror exception.
... shared worker: attempts to create a new sharedworker will throw a securityerror exception.
... service worker: attempts to create a new serviceworker will throw a securityerror exception.
... if the preference does not exist, click "string" and then "+" to create a new preference.
Getting from Content to Layout
frame construction regardless of whether content nodes are inserted/appended/deleted, frames can be created and destroyed, based on whatever is optimal for the changes in the content tree.
... these items are then examined in relation to the location in the content tree that is being modified and either the relevant frames are created/destroyed or the logic moves up to the parent frame.
... separate frames are created for the pre and post-div parts of the <span>.
... if the <div> is removed, the frame construction code merges those frames by examining the parent frame, destroying the two frames created for the <span>, and creating one unified frame for the text content.
How to get a process dump with Windows Task Manager
(to get a process dump for thunderbird or some other product, substitute the product name where ever you see firefox in these instructions.) caution the memory dump that will be created through this process is a complete snapshot of the state of firefox when you create the file, so it contains urls of active tabs, history information, and possibly even passwords depending on what you are doing when the snapshot is taken.
... it is advisable to create a new, blank profile to use when reproducing the hang and capturing the memory dump.
... right-click firefox.exe and select "create dump file".
... see also how to get a stacktrace for a bug report [en-us] how to create a user-mode process dump file in windows vista and in windows 7 (msdn) ...
Dict.jsm
to use it, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/dict.jsm"); creating a dictionary you can create a new, empty dictionary by simply calling the dict() constructor: var newdict = new dict(); if you wish, you may also pass in an object literal of key/value pairs with which to initialize the dictionary: var someobj = {}; var newdict = new dict({key1: "foo", key2: someobj}); note that values may be any javascript object type.
... constructor dict() creates and returns a new dictionary object.
... return value a newly created dictionary object implementing the methods described in this article.
... examples creating and populating a dictionary this example creates a new dictionary and adds some key/value pairs to it.
Profile Manager
firefox provides a built-in applet to manage these profiles, but it will eventually be going away (see bug 214675), so a new standalone profile manager application has been created, which works with any xulrunner application, and has many features not found in firefox's built-in version.
... creating a profile to create a new profile, just click the new button from profile manager's toolbar.
... to create a profile from a profile archive: select "restore from->archive" from the toolbar's backup menu.
... you'll be prompted for the location of the archive, and then for the name of the profile you'd like to create from the archive.
PR_AttachThread
description you use pr_attachthread when you want to use nss functions on the native thread that was not created with nspr.
... you don't need to call pr_attachthread unless you create your own native thread.
...a native thread not created by nspr is automatically attached the first time it calls an nspr function, and automatically detached when it exits.
... in nspr release 19980529b and earlier, it is necessary for a native thread not created by nspr to call pr_attachthread before it calls any nspr functions, and call pr_detachthread when it is done calling nspr functions.
PR_NewTCPSocket
creates a new ipv4 tcp socket.
... syntax #include <prio.h> prfiledesc* pr_newtcpsocket(void); returns the function returns one of the following values: upon successful completion, a pointer to the prfiledesc object created for the newly opened ipv4 tcp socket.
...pr_newtcpsocket creates a new ipv4 tcp socket.
... see also pr_newtcpsocket is deprecated because it is hardcoded to create an ipv4 tcp socket.
PR_NewUDPSocket
creates a new udp socket.
... syntax #include <prio.h> prfiledesc* pr_newudpsocket(void); returns the function returns one of the following values: upon successful completion, a pointer to the prfiledesc object created for the newly opened udp socket.
... pr_newudpsocket creates a new udp socket.
... see also pr_newudpsocket is deprecated because it is hardcoded to create an ipv4 udp socket.
NSS Sample Code sample3
ire a nss database to exist */ nss_nodb_init("."); /* get a slot to use for the crypto operations */ slot = pk11_getinternalkeyslot(); if (!slot) { cout << "getinternalkeyslot failed" << endl; status = 1; goto done; } /* * part 1 - simple hashing */ cout << "part 1 -- simple hashing" << endl; /* initialize data */ memset(data, 0xbc, sizeof data); /* create a context for hashing (digesting) */ context = pk11_createdigestcontext(sec_oid_md5); if (!context) { cout << "createdigestcontext failed" << endl; goto done; } s = pk11_digestbegin(context); if (s != secsuccess) { cout << "digestbegin failed" << endl; goto done; } s = pk11_digestop(context, data, sizeof data); if (s != secsuccess) { cout << "digestupdate failed" << endl; goto done;...
...est, &len, sizeof digest); if (s != secsuccess) { cout << "digestfinal failed" << endl; goto done; } /* print digest */ printdigest(digest, len); pk11_destroycontext(context, pr_true); context = 0; /* * part 2 - hashing with included secret key */ cout << "part 2 -- hashing with included secret key" << endl; /* initialize data */ memset(data, 0xbc, sizeof data); /* create a key */ key = pk11_keygen(slot, ckm_generic_secret_key_gen, 0, 128, 0); if (!key) { cout << "create key failed" << endl; goto done; } cout << (void *)key << endl; /* create parameters for crypto context */ /* note: params must be provided, but may be empty */ secitem noparams; noparams.type = sibuffer; noparams.data = 0; noparams.len = 0; /* create context using the same s...
...lot as the key */ // context = pk11_createdigestcontext(sec_oid_md5); context = pk11_createcontextbysymkey(ckm_md5, cka_digest, key, &noparams); if (!context) { cout << "createdigestcontext failed" << endl; goto done; } s = pk11_digestbegin(context); if (s != secsuccess) { cout << "digestbegin failed" << endl; goto done; } s = pk11_digestkey(context, key); if (s != secsuccess) { cout << "digestkey failed" << endl; goto done; } s = pk11_digestop(context, data, sizeof data); if (s != secsuccess) { cout << "digestupdate failed" << endl; goto done; } s = pk11_digestfinal(context, digest, &len, sizeof digest); if (s != secsuccess) { cout << "digestfinal failed" << endl; goto done; } /* print digest */ printdigest(digest, len); pk11_destroycontext(context, pr_true); ...
...context = 0; /* * part 3 - mac (with secret key) */ cout << "part 3 -- mac (with secret key)" << endl; /* initialize data */ memset(data, 0xbc, sizeof data); context = pk11_createcontextbysymkey(ckm_md5_hmac, cka_sign, key, &noparams); if (!context) { cout << "createcontextbysymkey failed" << endl; goto done; } s = pk11_digestbegin(context); if (s != secsuccess) { cout << "digestbegin failed" << endl; goto done; } s = pk11_digestop(context, data, sizeof data); if (s != secsuccess) { cout << "digestop failed" << endl; goto done; } s = pk11_digestfinal(context, digest, &len, sizeof digest); if (s != secsuccess) { cout << "digestfinal failed" << endl; goto done; } /* print digest */ printdigest(digest, len); pk11_destroycontext(context, pr_true); conte...
NSS sources building testing
create a new directory on your computer that you will use as your local work area, and run the following commands.
... nss/lib contains all the library code that is used to create the runtime libraries used by applications.
...several tools are general purpose and can be used to inspect and manipulate the storage files that software using the nss library creates and modifies.
...each test suite execution will create a new subdirectory; you should clean them up from time to time.
NSS tools : crlutil
name crlutil — list, generate, modify, or delete crls within the nss security database file(s) and list, create, modify or delete certificates entries in a particular crl.
...please contribute to the initial review in mozilla nss bug 836477[1] description the certificate revocation list (crl) management tool, crlutil, is a command-line utility that can list, generate, modify, or delete crls within the nss security database file(s) and list, create, modify or delete certificates entries in a particular crl.
...the options and arguments for the crlutil command are defined as follows: -g create new certificate revocation list(crl).- -d delete certificate revocation list from cert database.
...list of possible algorithms: md2 | md4 | md5 | sha1 | sha256 | sha384 | sha512 -n nickname specify the nickname of a certificate or key to list, create, add to a database, modify, or validate.
NSS_3.12.3_release_notes.html
num are not implemented on windows 32-bit bug 441321: tolerate incorrect encoding of dsa signatures in ssl 3.0 handshakes bug 444404: libpkix reports unknown issuer for nearly all certificate errors bug 452391: certutil -k incorrectly reports ec private key as an orphan bug 453234: support for seed cipher suites to tls rfc4010 bug 453364: improve pk11_cipherop error reporting (was: pk11_createcontextbysymkey returns null bug 456406: slot list leaks in symkeyutil bug 461085: rfe: export function cert_comparecerts bug 462293: crash on fork after softoken is dlclose'd on some unix platforms in nss 3.12 bug 463342: move some headers to freebl/softoken bug 463452: sql db creation does not set files protections to 0600 bug 463678: need to add rpath to 64-bit libraries on hp-ux ...
... bug 464406: fix signtool regressions bug 465270: uninitialised value in devutil.c::create_object() bug 465273: dead assignment in devutil.c::nssslotarray_clone() bug 465926: during import of pkcs #12 files bug 466180: ssl_configmpserversidcache with default parameters fails on {net bug 466194: cert_decodetruststring should take a const char * input trusts string.
...e of nss_use_64 in lib/libpkix/pkix_pl_nss/system/pkix_pl_object.c bug 466745: random number generator fails on windows ce bug 467298: sql db code uses local cache on local file system bug 468279: softoken crash importing email cert into newly upgraded db bug 468532: trusted ca trust flags not being honored in cert_verifycert bug 469583: coverity: uninitialized variable used in sec_pkcs5createalgorithmid bug 469944: when built with microsoft compilers bug 470351: crlutil build fails on windows because it calls undeclared isatty bug 471539: stop honoring digital signatures in certificates and crls based on weak hashes bug 471665: nss reports incorrect sizes for (aes) symmetric keys bug 471715: add cert to nssckbi to override rogue md5-collision ca cert bug 472291: crash in l...
... bug 472749: softoken permits aes keys of any length to be created bug 473147: pk11mode tests fails on aix when using shareable dbs.
NSS Tools crlutil
using the certificate revocation list management tool newsgroup: mozilla.dev.tech.crypto the certificate revocation list (crl) management tool is a command-line utility that can list, generate, modify, or delete crls within the nss security database file(s) and list, create, modify or delete certificates entries in a particular crl.
...certificate revocation list management tool command options and their arguments are defined as follows: options -g create new certificate revocation list(crl).
...list of possible algorithms: md2 | md4 | md5 | sha1 | sha256 | sha384 | sha512 -n nickname specify the nickname of a certificate or key to list, create, add to a database, modify, or validate.
...rl [-t crltype] [-u url] [-d keydir] [-p dbprefix] [-b] creating or modifying a crl: listing all crls or a named crl: deleting crl from db: erasing crls from db: import crl from file: examples creating a new crl listing crls in a database deleting crl from a database importing crl into a database modifiying crl in a database creating a new crl this example creates a new crl and importing it in to a database in the specified directory: crlutil -g -d certdir -n cert-nickname -c crl-script-file or crlutil -g -d certdir -n cert-nickname <<eof update=20050204153000z addcert 34-40 20050104153000z eof where cert-nickname is the name the new crl will be signed with.
NSS tools : crlutil
MozillaProjectsNSStoolscrlutil
name crlutil — list, generate, modify, or delete crls within the nss security database file(s) and list, create, modify or delete certificates entries in a particular crl.
... synopsis crlutil [options] arguments description the certificate revocation list (crl) management tool, crlutil, is a command-line utility that can list, generate, modify, or delete crls within the nss security database file(s) and list, create, modify or delete certificates entries in a particular crl.
...the options and arguments for the crlutil command are defined as follows: -g create new certificate revocation list(crl).
...list of possible algorithms: md2 | md4 | md5 | sha1 | sha256 | sha384 | sha512 -n nickname specify the nickname of a certificate or key to list, create, add to a database, modify, or validate.
Tutorial: Embedding Rhino
entering a context the code context cx = context.enter(); creates and enters a context.
...the null parameter tells initstandardobjects to create and return a scope object that we use in later calls.
...e java -jar option preempts the rest of the classpath, we can't use that and access the counter class.) $ java -cp "js.jar;examples" org.mozilla.javascript.tools.shell.main js> defineclass("counter") js> c = new counter(7) [object counter] js> c.count 7 js> c.count 8 js> c.count 9 js> c.resetcount() js> c.count 0 counter's constructors the zero-argument constructor is used by rhino runtime to create instances.
...the method scriptableobject.defineclass uses a java class to define the counter "class" in the top-level scope: scriptableobject.defineclass(scope, counter.class); now we can reference the counter object from our script: $ java runscript4 "c = new counter(3); c.count; c.count;" it also creates a new instance of the counter object from within our java code, constructing it with the value 7, and assigning it to the top-level variable mycounter: object[] arg = { new integer(7) }; scriptable mycounter = cx.newobject(scope, "counter", arg); scope.put("mycounter", scope, mycounter); now we can reference the mycounter object from our script: $ java runscript3 'runscript4 'mycounter.count...
Functions
when the function object is created, its parent is set to the first object on the scope chain.
...if the function does not assign to any closed-on vars/args, and it only reads closed-on local variables and arguments that never change value after the function is created, then the function can be implemented as a flat closure.
... when a flat closure is created, all the closed-on values are copied from the stack into reserved slots of the function object.
...this is fast if the global either doesn't exist before the script runs (the script creates it) or it's a non-configurable data property (which amounts to the same thing).
Property cache
non-adding cache entries {.kpc=pc, .kshape=kshape, .vshape()=vshape, .scopeindex()=scopeindex, .protoindex()=protoindex, .vword=vword} this type of entry is created for all instructions that use the property cache.
... adding cache entries {.kpc=pc, .kshape=kshape, .vshape()=vshape, .scopeindex()=0, .protoindex()=0, .vword=vword} where kshape != vshape this type of entry is only created for jsop_setprop and jsop_setname instructions that create a new property.
...sometimes the new property can be created simply by calling jsscope::extend, but there are many special cases and pitfalls to watch out for.
...when a property cache entry of this type is created, the scope of the object that contains the property is branded.
JSAPI Cookbook
*/ js::callargs args = js::callargsfromvp(argc, vp); args.rval().setint32(23); return true; returning a floating-point number // javascript return 3.14159; /* jsapi */ js::callargs args = js::callargsfromvp(argc, vp); args.rval().setdouble(3.14159); exception handling throw the most common idiom is to create a new error object and throw that.
... // javascript throw exc; /* jsapi */ js_setpendingexception(cx, exc); return false; when js_reporterror creates a new error object, it sets the filename and linenumber properties to the line of javascript code currently at the top of the stack.
... you can use this function to create a constant property, one that can't be overwritten or deleted.
... create global variable __dirname to retrieve the current javascript file name, like in nodejs ...
JS::HandleValueArray
lues); js::handlevaluearray(const js::callargs& args); js::handlevaluearray::frommarkedlocation(size_t len, const js::value *elements); js::handlevaluearray::subarray(const js::handlevaluearray& values, size_t startindex, size_t len); js::handlevaluearray::empty(); name type description value js::rootedvalue &amp; an element of newly created 1-length array.
... values js::autovaluevector &amp; elements of newly created array.
... values js::autovaluearray &amp; elements of newly created array.
... args js::callargs &amp; elements of newly created array.
JSObjectOps.newObjectMap
the jsobjectops.newobjectmap callback is called whenever a new object is created.
... it creates a jsobjectmap that completely controls the new object's behavior.
... syntax typedef jsobjectmap * (*jsnewobjectmapop)(jscontext *cx, jsrefcount nrefs, jsobjectops *ops, jsclass *clasp, jsobject *obj); name type description cx jscontext * pointer to the js context in which the new object is being created.
... create a new instance of (a concrete subclass of) jsobjectmap (see jsobj.h), with the nrefs and ops members initialized from the same-named parameters, and with the nslots and freeslot members initialized according to ops and clasp.
JS_CloneFunctionObject
create a new function object from an existing jsfunction.
... description js_clonefunctionobject creates a new function object from funobj.
...this can be helpful if funobj is an extant function that you wish to use as if it were enclosed by a newly-created global object.
...on success, js_clonefunctionobject returns a pointer to the newly created object.
JS_DefinePropertyWithTinyId
create a new object property with a tiny id.
... obj jsobject * object for which to create the new property.
... name const char * or const jschar * name for the property to create.
...if the property already exists or cannot be created, they return js_false.
JS_EnterLocalRootScope
by contrast, local root scopes protect newly-created objects, doubles, and strings.
...calling js_enterlocalrootscope and js_leavelocalrootscope around the body of the native hook protects each object, double, and string created using the same jscontext from gc.
... for example: jsbool my_getproperty(jscontext *cx, jsobject *obj, jsval id, jsval *vp) { jsbool ok; if (!js_enterlocalrootscope(cx)) return js_false; // this function doesn't need to bother rooting any new objects, // strings, or doubles it creates using cx.
...new // items created in this local root scope become subject to gc.
JS_NewDependentString
create a new javascript string containing a range of characters from an existing string.
... syntax jsstring * js_newdependentstring(jscontext *cx, js::handlestring str, size_t start, size_t length); name type description cx jscontext * the context in which to create the new string.
... description js_newdependentstring creates a new string as a substring of an existing javascript string, str.
... the new string contains the same characters as if it were created with the javascript method str.substr(start, length).
JS_SetContextCallback
specifies a callback function that is automatically called whenever a jscontext is created or destroyed.
...this is the context which was just created, or is about to be destroyed.
...added in spidermonkey 31 typedef enum jscontextop { jscontext_new, jscontext_destroy } jscontextop; enumeration meaning jscontext_new js_newcontext successfully created a new jscontext instance.
... description js_setcontextcallback specifies a callback function that is automatically called when jscontexts are created or destroyed.
A Web PKI x509 certificate primer
one issue that is not commonly known is that the x509 trust graph is not a forest (a bunch of trees where each root is a trusted root) but a cyclic graph, where the same key/issuer can be a root or an intermediate for another root in the browsers key store (when roots create intermediates for each other it is called cross-signing).
...generate csr using this command: openssl req -new -key key.pem -days 1096 -extensions v3_ca -batch -out example.csr -utf8 -subj '/cn=www.example.com' this creates a new certificate signing request (csr) that will be valid for 3 years.
... generate your intermediate cert the following steps create an intermediate cert that is valid for 8 years.
...for the end date of the root cert created following the instructions in this page (year 2017).
Bundling multiple binary components
since binary components are linked against a single gecko sdk, a dependency to a particular version of gecko is created.
...this can create a difficult situation for extension developers trying to support multiple gecko versions (firefox 2 and 3, for example).
...create small wrappers for calling the methods, as you may need to thunk parameters depending on how much has changed between gecko versions.
... this approach uses only one binary for each platform (win/mac/linux) but creates complexity in the binaries - loading the methods and creating the wrappers.
XPCOM changes in Gecko 2.0
the component is loaded only when the xpcom component manager needs to create a component.
...}; // the following line is what xpcom uses to create components.
... each component prototype // must have a .classid which is used to create it.
...if your add-on depends upon xbl bindings attached to content objects—for example, the ability to call functions or get and set properties created by the xbl binding—you will need to use the xpcnativewrapper property wrappedjsobject to access wrapped objects.
Component Internals
the component is an abstraction sitting between the actual module in which it is implemented and the objects that its factory code creates for use by clients.
...sometimes, applications use the nsicomponentregistrar interface and create their own code for watching a particular directory and registering new components that are added there, which is what's often referred to as autoregistration.
...following this initial, verbose demonstration of the apis, we will introduce a faster more generic way of implementing the module and factory code using macros, which can make components much easier to create.
...you shouldn't have to link to the xpcom library to create a xpcom component - in fact, if your component has to, then something is wrong.
Introduction to XPCOM for the DOM
as opposed to a concreate class, an interface is supposed to be more stable through time.
...the bad thing is that we have to find a way to improve those interfaces, and freezing them obliges implementers to create new interfaces.
... queryinterface() consider again the class nsfoo that implements two interfaces, nsifoo and nsifoo2: class nsfoo : public nsifoo, public nsifoo2 let's assume an instance of nsfoo was somehow created (this assertion is true most of the time).
...since we cannot re-use ifooptr, we create a new pointer to nsifoo2, ifooptr2.
Components.utils
please keep this list in sync with the components object page methods method description cloneinto() create a structured clone of an object in a different javascript context.
... createarrayin() removed in gecko 31 returns an array created in specified compartment.
... createobjectin() creates a new object, created in the scope of the specified object's compartment.
... properties property type description sandbox nsixpccomponents_utils_sandbox creates sandbox objects for use with evalinsandbox().
nsIAccessibilityService
last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) inherits from: nsiaccessibleretrieval method overview nsiaccessible createouterdocaccessible(in nsidomnode anode); nsiaccessible createrootaccessible(in nsipresshell ashell, in nsidocument adocument); nsiaccessible createhtml4buttonaccessible(in nsisupports aframe); nsiaccessible createhypertextaccessible(in nsisupports aframe); nsiaccessible createhtmlbraccessible(in nsisupports aframe); nsiaccessible createhtmlbuttonaccessible(in nsisupports aframe); nsiaccessible createhtmlaccessiblebymarkup(in nsiframe aframe, in nsiweakreference aweakshell, in nsidomnode adomnode); nsiaccessible cre...
...atehtmlliaccessible(in nsisupports aframe, in nsisupports abulletframe, in astring abullettext); nsiaccessible createhtmlcheckboxaccessible(in nsisupports aframe); nsiaccessible createhtmlcomboboxaccessible(in nsidomnode anode, in nsiweakreference apresshell); nsiaccessible createhtmlgenericaccessible(in nsisupports aframe); nsiaccessible createhtmlgenericaccessible(in nsisupports aframe); nsiaccessible createhtmlhraccessible(in nsisupports aframe); nsiaccessible createhtmlimageaccessible(in nsisupports aframe); nsiaccessible createhtmllabelaccessible(in nsisupports aframe); nsiaccessible createhtmllabelaccessible(in nsidomnode anode, in nsiweakreference apresshell); nsiaccessible createhtmlobjectframeaccessible(in nsobjectframe aframe); nsiaccessible createhtmlradi...
...obuttonaccessible(in nsisupports aframe); nsiaccessible createhtmlselectoptionaccessible(in nsidomnode anode, in nsiaccessible aaccparent, in nsiweakreference apresshell); nsiaccessible createhtmltableaccessible(in nsisupports aframe); nsiaccessible createhtmltablecellaccessible(in nsisupports aframe); nsiaccessible createhtmltableheadaccessible(in nsidomnode adomnode); nsiaccessible createhtmltextaccessible(in nsisupports aframe); nsiaccessible createhtmltextfieldaccessible(in nsisupports aframe); nsiaccessible createhtmlcaptionaccessible(in nsisupports aframe); nsiaccessible getaccessible(in nsidomnode anode, in nsipresshell apresshell, in nsiweakreference aweakshell, inout nsiframe framehint, out boolean aishidden); nsiaccessible addnativerootaccessible(in voidptr a...
...must be one of: event_reorder (change) event_show (make visible or create) or event_hide (destroy or hide) ...
nsIAppShell
inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview void create(inout int argc, inout string argv); obsolete since gecko 1.9 void dispatchnativeevent(in prbool arealevent, in voidptr aevent); obsolete since gecko 1.9 void exit(); void favorperformancehint(in boolean favorperfoverstarvation, in unsigned long starvationdelay); void getnativeevent(in prboolref arealevent, in voidptrref aevent); obsolete since gecko 1.9 void listentoeventqueue(in nsieventqueue aqueue, in prbool alisten); obsolete since gecko 1.9 void resumenative(); void run()...
... methods create() obsolete since gecko 1.9 (firefox 3) creates an application shell.
... void create( inout int argc, inout string argv ); parameters argc the number of parameters passed in on the command line.
... listentoeventqueue() obsolete since gecko 1.9 (firefox 3) an event queue has been created or destroyed.
nsIApplicationCacheService
1.0 66 introduced gecko 1.9.1 inherits from: nsisupports last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) method overview void cacheopportunistically(in nsiapplicationcache cache, in acstring key); nsiapplicationcache chooseapplicationcache(in acstring key); nsiapplicationcache createapplicationcache(in acstring group); void deactivategroup(in acstring group); nsiapplicationcache getactivecache(in acstring group); nsiapplicationcache getapplicationcache(in acstring clientid); void getgroups([optional] out unsigned long count, [array, size_is(count), retval] out string groupids); methods cacheopportunistically() flags the specified key as one that should be cached op...
...createapplicationcache() creates a new, empty application cache for the specified cache group.
... nsiapplicationcache createapplicationcache( in acstring group ); parameters group the cache group for which to create an application cache.
... return value the newly-created nsiapplicationcache.
nsICryptoHash
you will need to create an instance of nsicryptohash, open an input stream from a file, and then update the hash with the file.
... the following example shows how to compute the sha256 hash of a file: // hardcoded here for convenience var path = "c:\\windows\\notepad.exe"; var f = components.classes["@mozilla.org/file/local;1"] .createinstance(components.interfaces.nsilocalfile); f.initwithpath(path); var istream = components.classes["@mozilla.org/network/file-input-stream;1"] .createinstance(components.interfaces.nsifileinputstream); // open for reading istream.init(f, 0x01, 0444, 0); var ch = components.classes["@mozilla.org/security/hash;1"] .createinstance(components.interfaces.nsicryptohash); // we want to use the sha256 algorithm ch.init(ch.sha256); // this tells updatefromstream to read the entire file const pr_uint32_max = 0xffffffff; ch.updatefromstream...
... createinstance(components.interfaces.nsiscriptableunicodeconverter); // we use utf-8 here, you can choose other encodings.
... converter.charset = "utf-8"; // result is an out parameter, // result.value will contain the array length var result = {}; // data is an array of bytes var data = converter.converttobytearray(str, result); var ch = components.classes["@mozilla.org/security/hash;1"] .createinstance(components.interfaces.nsicryptohash); ch.init(ch.sha256); ch.update(data, data.length); var hash = ch.finish(false); // return the two-digit hexadecimal code for a byte function tohexstring(charcode) { return ("0" + charcode.tostring(16)).slice(-2); } // convert the binary hash data to a hex string.
nsIFactory
inherits from: nsisupports last changed in gecko 0.9.5 method overview void createinstance(in nsisupports aouter, in nsiidref iid, [retval, iid_is(iid)] out nsqiresult result); void lockfactory(in prbool lock); methods createinstance() creates an instance of the class associated with this factory.
...(see also nsicomponentmanager.createinstance.) void createinstance( in nsisupports aouter, in nsiidref iid, [retval, iid_is(iid)] out nsqiresult result ); parameters aouter pointer to a component that wishes to be aggregated in the resulting instance.
... iid the iid of the interface being requested in the component which is being currently created.
... result pointer to the newly created instance, if successful.
nsIFeedTextConstruct
1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 1.8.1 (firefox 2 / thunderbird 2 / seamonkey 1.1) implemented by: @mozilla.org/feed-textconstruct;1, but users usually don't need to create instances of this directly.
... method overview nsidomdocumentfragment createdocumentfragment(in nsidomelement element); astring plaintext(); attributes attribute type description base nsiuri if the text construct contains html or xhtml, relative references in the content should be resolved against this base uri.
... methods createdocumentfragment() creates a new document fragment on a given dom element, containing the text and (if the text construct contains html or xhtml) its markup.
... nsidomdocumentfragment createdocumentfragment( in nsidomelement element ); parameters element the element in which to create the new document fragment.
nsILocalFile
to create an instance, use: var localfile = components.classes["@mozilla.org/file/local;1"] .createinstance(components.interfaces.nsilocalfile); method overview void appendrelativenativepath(in acstring relativefilepath); native code only!
... pr_create_file if the file does not exist, the file is created.
... pr_excl with pr_create_file, if the file does not exist, the file is created.
... return value if the file is successfully opened, returns a pointer to the prfiledesc created for the newly opened file.
nsIMsgIncomingServer
cancreatefoldersonserver boolean candelete boolean can this server be removed from the account manager?
...exceptions thrown missing exception missing description cleartemporaryreturnreceiptsfilter() if sent folder pref is changed we need to clear the temporary return receipt filter so that the new return receipt filter can be recreated (by configuretemporaryreturnreceiptsfilter()).
...if we have set up to filter return receipts into our sent folder, this utility method creates a filter to do that, and adds it to our filterlist if it doesn't exist.
...void configuretemporaryfilters( in nsimsgfilterlist filterlist ); parameters filterlist missing description exceptions thrown missing exception missing description configuretemporaryreturnreceiptsfilter() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) if we have set up to filter return receipts into our sent folder, this utility method creates a filter to do that, and adds it to our filterlist if it doesn't exist.
nsIMsgSearchSession
the nsimsgsearchsession interface allows you to create and manipulate search sessions within thunderbird.
... to create an instance, use: var searchsession = components.classes["@mozilla.org/messenger/searchsession;1"] .createinstance(components.interfaces.nsimsgsearchsession); to use the instance append search terms, set the scope, and then call search().
... searchsession.addscopeterm(components.interfaces.nsmsgsearchscope.offlinemail, afolder); var searchterm = searchsession.createterm(); var value = searchterm.value; value.str = avalue; searchterm.value = value; searchterm.op = searchsession.booleanor; searchterm.booleanand = false; searchsession.appendterm(searchterm); searchsession.search(null); inherits from: nsisupports method overview void addsearchterm(in nsmsgsearchattribvalue attrib, in nsmsgsearchopvalue op, in nsimsgsearchvalue value, in boolean booleanand, in string arbitraryheader); nsimsgsearchterm createterm(); void appendterm(in nsimsgsearchterm term); void registerlistener(in nsimsgsearchnotify listener); void unregisterlistener(in nsimsgsearchnotify listener); void getnt...
... createterm() nsimsgsearchterm createterm(); appendterm() void appendterm(in nsimsgsearchterm term); parameters term registerlistener() adds a listener to the search session.
nsIProfile
method overview void cloneprofile(in wstring profilename); void createnewprofile(in wstring profilename, in wstring nativeprofiledir, in wstring langcode, in boolean useexistingdir); void deleteprofile(in wstring name, in boolean candeletefiles); void getprofilelist(out unsigned long length, [retval, array, size_is(length)] out wstring profilenames); boolean profileexists(in wstring profilename); void renameprofile(in wstring oldn...
... createnewprofile() creates a new profile.
...void createnewprofile( in wstring profilename, in wstring nativeprofiledir, in wstring langcode, in boolean useexistingdir ); parameters profilename the name to assign to the new profile.
... nativeprofiledir the pathname of the directory to use as the profile directory; if you specify null, a new folder will be created in the default profiles directory.
nsISmsRequestManager
to create an instance, use: var smsrequestmanager = components.classes["@mozilla.org/sms/smsrequestmanager;1"] .createinstance(components.interfaces.nsismsrequestmanager); method overview long addrequest(in nsidommozsmsrequest arequest); long createrequest(in nsidommozsmsmanager amanager, out nsidommozsmsrequest arequest); void notifycreatemessagelist(in long arequestid, in long alistid, in nsid...
...createrequest() create a new request object.
... long createrequest( in nsidommozsmsmanager amanager, out nsidommozsmsrequest arequest ); parameters amanager an smsmanager.
...notifycreatemessagelist() void notifycreatemessagelist( in long arequestid, in long alistid, in nsidommozsmsmessage amessage ); parameters arequestid a number representing the id of the request.
nsIThreadManager
the nsithreadmanager interface lets applications and extensions create and manage threads, each of which is represented by an nsithread.
...if the calling thread does not already have a nsithread associated with it, one is created and associate with the current prthread.
... newthread() create a new thread.
... return value the newly created nsithread.
nsITimer
to create an instance, use: var timer = components.classes["@mozilla.org/timer;1"] .createinstance(components.interfaces.nsitimer); users of instances of nsitimer should keep a reference to the timer until it is no longer needed in order to assure the timer is fired.
...var event = { notify: function(timer) { alert("fire!"); } } // now it is time to create the timer...
... var timer = components.classes["@mozilla.org/timer;1"].createinstance(components.interfaces.nsitimer); // ...
...timer.initwithcallback(event,10000, components.interfaces.nsitimer.type_one_shot); using init, we fire an event every 10 seconds: var event = { observe: function(subject, topic, data) { dump("hello world\n"); } } var timer = components.classes["@mozilla.org/timer;1"].createinstance(components.interfaces.nsitimer); const type_repeating_precise_can_skip = components.interfaces.nsitimer.type_repeating_precise_can_skip; timer.init(event, 10*1000, type_repeating_precise_can_skip); see also nstimercallbackfunc nsitimercallback ...
nsIWebBrowserPersist
to create an instance, use: var webbrowserpersist = components.classes["@mozilla.org/embedding/browser/nswebbrowserpersist;1"] .createinstance(components.interfaces.nsiwebbrowserpersist); method overview void cancelsave(); void savechannel(in nsichannel achannel, in nsisupports afile); void savedocument(in nsidomdocument adocument, in nsisupports afile, i...
... persist_flags_cleanup_on_failure 8192 automatically cleanup after a failed or cancelled operation, deleting all created files and directories.
...please use downloads.createdownload() instead.
... example function downloadfile(httploc, sourcewindow) { try { //new obj_uri object var obj_uri = components.classes["@mozilla.org/network/io-service;1"].getservice(components.interfaces.nsiioservice).newuri(httploc, null, null); //new file object var obj_targetfile = components.classes["@mozilla.org/file/local;1"].createinstance(components.interfaces.nsilocalfile); //set file with path obj_targetfile.initwithpath("c:\\temp\\test.pdf"); //if file doesn't exist, create if(!obj_targetfile.exists()) { obj_targetfile.create(0x00,0644); } //new persistence object var obj_persist = components.classes["@mozilla.org/embedding/browser/nswebbrowserpersist;1"].createinstance(components.int...
nsIXPCScriptable
last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) inherits from: nsisupports method overview void precreate(in nsisupports nativeobj, in jscontextptr cx, in jsobjectptr globalobj, out jsobjectptr parentobj); void create(in nsixpconnectwrappednative wrapper, in jscontextptr cx, in jsobjectptr obj); void postcreate(in nsixpconnectwrappednative wrapper, in jscontextptr cx, in jsobjectptr obj); prbool addproperty(in nsixpconnectwrappednative wrapper, in jscontextptr cx, in jsobjectptr obj, in jsval i...
...nectwrappednative wrapper, in jstracerptr trc, in jsobjectptr obj); prbool equality(in nsixpconnectwrappednative wrapper, in jscontextptr cx, in jsobjectptr obj, in jsval val); jsobjectptr outerobject(in nsixpconnectwrappednative wrapper, in jscontextptr cx, in jsobjectptr obj); jsobjectptr innerobject(in nsixpconnectwrappednative wrapper, in jscontextptr cx, in jsobjectptr obj); void postcreateprototype(in jscontextptr cx, in jsobjectptr proto); attributes attribute type description classname string scriptableflags pruint32 the bitwise or'd set of flags (define below) that indicate the behavior of this object.
... constants constant value description want_precreate 1 << 0 want_create 1 << 1 want_postcreate 1 << 2 want_addproperty 1 << 3 want_delproperty 1 << 4 want_getproperty 1 << 5 want_setproperty 1 << 6 want_enumerate 1 << 7 want_newenumerate 1 << 8 indicates that the object wants to have its newenumerate method called.
... methods precreate() void precreate( in nsisupports nativeobj, in jscontextptr cx, in jsobjectptr globalobj, out jsobjectptr parentobj ); parameters nativeobj cx globalobj parentobj create() void create( in nsixpconnectwrappednative wrapper, in jscontextptr cx, in jsobjectptr obj ); parameters wrapper cx obj postcreate() void postcreate( in nsixpconnectwrappednati...
Reference Manual
nscomptr<nsifoo> foo( getter_addrefs(createafoo()) ); // |getter_addrefs| is a synonym for |dont_addref| that may look better to // you when applied to functions that return |addref|ed pointers nscomptr<nsifoo> foo( dont_addref(createafoo()) ); // or, maybe you don't like it better...
...nscomptr<nsibar> bar( getter_addrefs(createbar()) ); // ...which i must query for the right type nscomptr<nsifoo> foo( do_queryinterface(bar) ); one unfortunate trap that people fall into in this case is forgetting that their getter function addrefed the result.
... which leads them to type in code that looks like this: nscomptr<nsifoo> foo( do_queryinterface(createbar()) ); // oops!
... the interface returned by |createbar| leaks.
XPCOM ownership guidelines
if you create a temporary object, obviously it's up to you to destroy it.
...if you create an object with a longer lifespan, you will own it until you give ownership away.
... such a function is the perfect example of something that creates an object with a longer lifespan that itself, and gives away ownership (by producing a pointer that is already addrefed) --- in this case, to the caller.
...this may not be appropriate; and it may be hard to remedy without knowing if the object in question was truly created in response to your query.
Address Book examples
use the nsiabcollection.readonly attribute to determine the read-only status of an address book adding contacts create a card and set its properties using the nsiabcard interface (see the interface documentation for property names supported by the application): let card = components.classes["@mozilla.org/addressbook/cardproperty;1"] .createinstance(components.interfaces.nsiabcard); card.setproperty("firstname", "john"); card.setproperty("lastname", "smith"); card.primaryemail = "john@inv...
... addressbook.modifycard(card); deleting contacts once you have obtained a card(s) from an nsiabdirectory (see above) you can delete one or more simply by calling the deletecards function: let cardstodelete = components.classes["@mozilla.org/array;1"] .createinstance(components.interfaces.nsimutablearray); cardstodelete.appendelement(card); // repeat append as necessary addressbook.deletecards(cardstodelete); how do i add and use my own properties?
... adding a mailing list first create a mailing list object and initialize it: var maillist = components.classes["@mozilla.org/addressbook/directoryproperty;1"] .createinstance(components.interfaces.nsiabdirectory); maillist.ismaillist = true; now fill in the details you want to store: maillist.dirname = "my mailing list"; maillist.listnickname = "nickname for list"; maillist.description = "list descripti...
...if you have it in its nsiabdirectory form, then you can delete it like this: var abmanager = components.classes["@mozilla.org/abmanager;1"] .createinstance(components.interfaces.nsiabmanager); abmanager.deleteaddressbook(maillist.uri); how do i display properties dialogs to the user?
Declaring and Using Callbacks
in the ordinary case, invoking the type object creates a regular cdata object containing a pointer to the data.
... however, if the first argument is a function, js-ctypes creates a special object (known internally as a cclosure) that wraps the javascript function within an ordinary c function.
... this can all be done in a single line of code, like so: var callback = ctypes.functiontype(...).ptr(function(...) {...}); note: the use of .ptr() here isn't a method call; we're accessing a property that dynamically creates a callable object, and then invoking the result.
...for arguments of complex types, temporary cdata objects will be created.
Debugger.Frame - Firefox Developer Tools
for a given debugger instance, spidermonkey creates only one debugger.frame instance for a given visible frame.
...pushing a "debugger" frame makes this continuation explicit, and makes it easier to find the extent of the stack created for the invocation.
... callee the function whose application created this frame, as a debuggee value, or null if this is not a "call" frame.
...on newly created frames, this property’s value is undefined.
Aggregate view - Firefox Developer Tools
this page simply runs a script that creates a large number of dom nodes (200 htmldivelement objects and 4000 htmlspanelement objects).
... let's get an allocation trace: open the memory tool check "record call stacks" load https://mdn.github.io/performance-scenarios/dom-allocs/alloc.html take a snapshot select "view/aggregate" select "group by/call stack" you should see something like this: this is telling us that 93% of the total heap snapshot was allocated in functions called from "alloc.js", line 35 (our initial createtoolbars() call).
... so in the example above, we can see that we made 4002 allocations, accounting for 89% of the total heap, in createtoolbarbutton(), at alloc.js line 9, position 23: that is, the exact point where we create the <span> elements.
... let's see what the example looks like when we select "inverted call stack": now at the top we can immediately see the createtoolbarbutton() call accounting for 89% of the heap usage in our page.
Migrating from Firebug - Firefox Developer Tools
the devtools also have a context menu option for that named add new rule and additionally have a + button within the rules panel's toolbar to create new rules.
...in addition to that it allows to create new style sheets and to import existing style sheets and apply them to the page.
...a profile can be created via console.profile() and console.profileend() like in firebug or via the "start recording performance" button in the performance tool.
... storage inspector the cookies panel in firebug displays information related to the cookies created by a page and allows to manipulate the information they store.
Examine and edit HTML - Firefox Developer Tools
the menu contains the following items — click on the links to find the description of each command in the context menu reference: edit as html create new node duplicate node delete node attributes add attribute copy attribute value edit attribute remove attribute break on ...
... create new node create a new empty <div> as the last child of the currently selected element.
... duplicate node create a copy of this element, and insert the copy immediately after this element.
... you can access the same functionality using the "create new node" popup menu item.
AddressErrors - Web APIs
console.error(`error from show(): ${err}`); }); } catch (e) { // catch any errors from trying to create the paymentrequest object.
... } } this code creates a new paymentrequest, providing the supported handlers and payment options we set up above, as well as additional options (in this case, that we want to ask for shipping information).
... then a paymentdetailsupdate object is created with its error set to a generic message about address errors and with the reset of the object's values taken from shippingaddresserrors, and, using "...defaultpaymentdetails" as the final entry in the object, the remeainder of the properties' values are taken from defaultpaymentdetails.
... setting up the donate now button this code creates a handler for the load event on the window which in turn adds the needed click event handler to the "donate now" button so that clicking it starts the payment process.
AnalyserNode.getFloatFrequencyData() - Web APIs
syntax var audioctx = new audiocontext(); var analyser = audioctx.createanalyser(); var dataarray = new float32array(analyser.frequencybincount); // float32array should be the same length as the frequencybincount void analyser.getfloatfrequencydata(dataarray); // fill the float32array with data returned from getfloatfrequencydata() parameters array the float32array that the frequency domain data will be copied to.
... example const audioctx = new audiocontext(); const analyser = audioctx.createanalyser(); // float32array should be the same length as the frequencybincount const mydataarray = new float32array(analyser.frequencybincount); // fill the float32array with data returned from getfloatfrequencydata() analyser.getfloatfrequencydata(mydataarray); drawing a spectrum the following example shows basic usage of an audiocontext to connect a mediaelementaudiosourcenode to an analysernode.
... <!doctype html> <body> <script> const audioctx = new audiocontext(); //create audio source //here, we use an audio file, but this could also be e.g.
... microphone input const audioele = new audio(); audioele.src = 'my-audio.mp3';//insert file name here audioele.autoplay = true; audioele.preload = 'auto'; const audiosourcenode = audioctx.createmediaelementsource(audioele); //create analyser node const analysernode = audioctx.createanalyser(); analysernode.fftsize = 256; const bufferlength = analysernode.frequencybincount; const dataarray = new float32array(bufferlength); //set up audio node network audiosourcenode.connect(analysernode); analysernode.connect(audioctx.destination); //create 2d canvas const canvas = document.createelement('canvas'); canvas.style.position = 'absolute'; canvas.style.top = 0; canvas.style.left = 0; canvas.width = window.innerwidth; canvas.height = window.innerheight; document.body.appendchild(canvas); const canvas...
AnalyserNode - Web APIs
it is an audionode that passes the audio stream unchanged from the input to the output, but allows you to take the generated data, process it, and create audio visualizations.
...ode" target="_top"><rect x="281" y="1" width="120" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="341" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">analysernode</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor analysernode() creates a new instance of an analysernode object.
... basic usage the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input.
... var audioctx = new(window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); // ...
AudioBuffer.getChannelData() - Web APIs
syntax var myarraybuffer = audioctx.createbuffer(2, framecount, audioctx.samplerate); var nowbuffering = myarraybuffer.getchanneldata(channel); parameters channel the channel property is an index representing the particular channel to get data for.
... example in the following example we create a two second buffer, fill it with white noise, and then play it via an audiobuffersourcenode.
... var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var button = document.queryselector('button'); var pre = document.queryselector('pre'); var myscript = document.queryselector('script'); pre.innerhtml = myscript.innerhtml; // stereo var channels = 2; // create an empty two second stereo buffer at the // sample rate of the audiocontext var framecount = audioctx.samplerate * 2.0; var myarraybuffer = audioctx.createbuffer(2, framecount, audioctx.samplerate); button.onclick = function() { // fill the buffer with white noise; //just random values between -1.0 and 1.0 for (var channel = 0; channel < channels; channel++) { // this gives us the actual arraybuffe...
... // this is the audionode to use when we want to play an audiobuffer var source = audioctx.createbuffersource(); // set the buffer in the audiobuffersourcenode source.buffer = myarraybuffer; // connect the audiobuffersourcenode to the // destination so we can hear the sound source.connect(audioctx.destination); // start the source playing source.start(); } specification specification status comment web audio apithe definition of 'getchanneldata' in that specific...
AudioNode.connect() - Web APIs
WebAPIAudioNodeconnect
notsupportederror the specified connection would create a cycle (in which the audio loops back through the same nodes repeatedly) and there are no delaynodes in the cycle to prevent the resulting waveform from getting stuck constructing the same audio frame indefinitely.
... this example creates an oscillator, then links it to a gain node, so that the gain node controls the volume of the oscillator node.
... var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var oscillator = audioctx.createoscillator(); var gainnode = audioctx.creategain(); oscillator.connect(gainnode); gainnode.connect(audioctx.destination); audioparam example in this example, we will be altering the gain value of a gainnode using an oscillatornode with a slow frequency value.
... var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); // create an normal oscillator to make sound var oscillator = audioctx.createoscillator(); // create a second oscillator that will be used as an lfo (low-frequency // oscillator), and will control a parameter var lfo = audioctx.createoscillator(); // set the frequency of the second oscillator to a low number lfo.frequency.value = 2.0; // 2hz: two oscillations par second // create a gain whose gain audioparam will be controlled by the lfo var gain = audioctx.creategain(); // connect the lfo to the gain audioparam.
AudioParamDescriptor - Web APIs
it is used to create custom audioparams on an audioworkletnode.
...there we've created a simple node which outputs white noise.
... here, additionally, we'll create a custom gain parameter, so we can directly change volume of the output (although you could use gainnode to achieve this as well).
... } }) return true } } registerprocessor('white-noise-processor', whitenoiseprocessor) next, in our main scripts file we'll load the processor, create an instance of audioworkletnode passing it the name of the processor, and connect the node to an audio graph.
AudioWorkletNode - Web APIs
constructor audioworkletnode() creates a new instance of an audioworkletnode object.
...if the audioworkletprocessor has a static parameterdescriptors getter, the audioparamdescriptor array returned from it is used to create audioparam objects on the audioworkletnode.
... examples in this example we create a custom audioworkletnode that outputs white noise.
...seprocessor extends audioworkletprocessor { process (inputs, outputs, parameters) { const output = outputs[0] output.foreach(channel => { for (let i = 0; i < channel.length; i++) { channel[i] = math.random() * 2 - 1 } }) return true } } registerprocessor('white-noise-processor', whitenoiseprocessor) next, in our main script file we'll load the processor, create an instance of audioworkletnode passing it the name of the processor, and connect the node to an audio graph.
AudioWorkletProcessor.parameterDescriptors (static getter) - Web APIs
the property is not a part of the audioworkletprocessor interface, but, if defined, it is called internally by the audioworkletprocessor constructor to create a list of custom audioparam objects in the parameters property of the associated audioworkletnode.
...there we've created a simple node which outputs white noise.
... here, additionally, we'll create a custom gain parameter, so we can directly change volume of the output (although you could use gainnode to achieve this as well).
... } }) return true } } registerprocessor('white-noise-processor', whitenoiseprocessor) next, in our main scripts file we'll load the processor, create an instance of audioworkletnode passing it the name of the processor, and connect the node to an audio graph.
BiquadFilterNode.getFrequencyResponse() - Web APIs
the two output arrays, magresponseoutput and phaseresponseoutput, must be created before calling this method; they must be the same size as the array of input frequency values (frequencyarray).
...we first create the float32arrays we need, one containing the input frequencies, and two to receive the output magnitude and phase values: var myfrequencyarray = new float32array(5); myfrequencyarray[0] = 1000; myfrequencyarray[1] = 2000; myfrequencyarray[2] = 3000; myfrequencyarray[3] = 4000; myfrequencyarray[4] = 5000; var magresponseoutput = new float32array(5); var phaseresponseoutput = new float32array(5)...
...; next we create a <ul> element in our html to contain our results, and grab a reference to it in our javascript: <p>biquad filter frequency response for: </p> <ul class="freq-response-output"> </ul> var freqresponseoutput = document.queryselector('.freq-response-output'); finally, after creating our biquad filter, we use getfrequencyresponse() to generate the response data and put it in our arrays, then loop through each data set and output them in a human-readable list at the bottom of the page: var biquadfilter = audioctx.createbiquadfilter(); biquadfilter.type = "lowshelf"; biquadfilter.frequency.value = 1000; biquadfilter.gain.value = range.value; ...
... function calcfrequencyresponse() { biquadfilter.getfrequencyresponse(myfrequencyarray,magresponseoutput,phaseresponseoutput); for(i = 0; i <= myfrequencyarray.length-1;i++){ var listitem = document.createelement('li'); listitem.innerhtml = '<strong>' + myfrequencyarray[i] + 'hz</strong>: magnitude ' + magresponseoutput[i] + ', phase ' + phaseresponseoutput[i] + ' radians.'; freqresponseoutput.appendchild(listitem); } } calcfrequencyresponse(); specifications specification status comment web audio apithe definition of 'getfrequencyresponse()' in that specification.
BiquadFilterNode - Web APIs
the biquadfilternode interface represents a simple low-order filter, and is created using the audiocontext.createbiquadfilter() method.
... number of inputs 1 number of outputs 1 channel count mode "max" channel count 2 (not used in the default count mode) channel interpretation "speakers" constructor biquadfilternode() creates a new instance of a biquadfilternode object.
... example the following example shows basic usage of an audiocontext to create a biquad filter node.
... var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); //set up the different audio nodes we will use for the app var analyser = audioctx.createanalyser(); var distortion = audioctx.createwaveshaper(); var gainnode = audioctx.creategain(); var biquadfilter = audioctx.createbiquadfilter(); var convolver = audioctx.createconvolver(); // connect the nodes together source = audioctx.createmediastreamsource(stream); source.connect(analyser); analyser.connect(distortion); distortion.connect(biquadfilter); biquadfilter.connect(convolver); convolver.connect(gainnode); gainnode.connect(audioctx.destination); // manipulate the biquad filter biquadfilter.type = "lowshelf"; biquadf...
Body.blob() - Web APIs
WebAPIBodyblob
note: if the response has a response.type of "opaque", the resulting blob will have a blob.size of 0 and a blob.type of empty string "", which renders it useless for methods like url.createobjecturl.
... example in our fetch request example (run fetch request live), we create a new request using the request() constructor, then use it to fetch a jpg.
... when the fetch is successful, we read a blob out of the response using blob(), put it into an object url using url.createobjecturl, and then set that url as the source of an <img> element to display the image.
... var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest) .then(response => response.blob()) .then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); specifications specification status comment fetchthe definition of 'blob()' in that specification.
CSS Typed Object Model API - Web APIs
cssunparsedvalue.cssunparsedvalue() constructor creates a new cssunparsedvalue object which represents property values that reference custom properties.
... csskeywordvalue serialization the csskeywordvalue interface of the the css typed object model api creates an object to represent css keywords and other identifiers.
... csskeywordvalue.csskeywordvalue() constructor constructor creates a new csskeywordvalue.csskeywordvalue() object which represents css keywords and other identifiers.
... csskeywordvalue an interface which creates an object to represent css keywords and other identifiers.
CanvasPattern.setTransform() - Web APIs
examples using the settransform method this is just a simple code snippet which uses the settransform method to create a canvaspattern with the specified pattern transformation from an svgmatrix.
... html <canvas id="canvas"></canvas> <svg id="svg1"></svg> javascript var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); var svg1 = document.getelementbyid('svg1'); var matrix = svg1.createsvgmatrix(); var img = new image(); img.src = 'https://mdn.mozillademos.org/files/222/canvas_createpattern.png'; img.onload = function() { var pattern = ctx.createpattern(img, 'repeat'); pattern.settransform(matrix.rotate(-45).scale(1.5)); ctx.fillstyle = pattern; ctx.fillrect(0, 0, 400, 400); }; note that newer browser versions started to support dommatrix as an input to settransform(), so for example you could replace th...
...vas id="canvas" width="400" height="200" class="playable-canvas"></canvas> <svg id="svg1" style="display:none"></svg> <div class="playable-buttons"> <input id="edit" type="button" value="edit" /> <input id="reset" type="button" value="reset" /> </div> <textarea id="code" class="playable-code" style="height:120px"> var img = new image(); img.src = 'https://mdn.mozillademos.org/files/222/canvas_createpattern.png'; img.onload = function() { var pattern = ctx.createpattern(img, 'repeat'); pattern.settransform(matrix.rotate(-45).scale(1.5)); ctx.fillstyle = pattern; ctx.fillrect(0, 0, 400, 400); };</textarea> var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); var textarea = document.getelementbyid('code'); var reset = document.getelementbyid('reset'); var...
... edit = document.getelementbyid('edit'); var code = textarea.value; var svg1 = document.getelementbyid('svg1'); var matrix = svg1.createsvgmatrix(); function drawcanvas() { ctx.clearrect(0, 0, canvas.width, canvas.height); eval(textarea.value); } reset.addeventlistener('click', function() { textarea.value = code; drawcanvas(); }); edit.addeventlistener('click', function() { textarea.focus(); }) textarea.addeventlistener('input', drawcanvas); window.addeventlistener('load', drawcanvas); specifications specification status comment html living standardthe definition of 'canvaspattern.settransform' in that specification.
CanvasRenderingContext2D.clip() - Web APIs
examples a simple clipping region this example uses the clip() method to create a clipping region according to the shape of a circular arc.
... const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // create circular clipping region ctx.beginpath(); ctx.arc(100, 75, 50, 0, math.pi * 2); ctx.clip(); // draw stuff that gets clipped ctx.fillstyle = 'blue'; ctx.fillrect(0, 0, canvas.width, canvas.height); ctx.fillstyle = 'orange'; ctx.fillrect(0, 0, 100, 100); result specifying a path and a fillrule this example saves two rectangles to a path2d object, which is then made the current clipping region using the clip() method.
... the "evenodd" rule creates a hole where the clipping rectangles intersect; by default (with the "nonzero" rule), there would be no hole.
... html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // create clipping path let region = new path2d(); region.rect(80, 10, 20, 130); region.rect(40, 50, 100, 50); ctx.clip(region, "evenodd"); // draw stuff that gets clipped ctx.fillstyle = 'blue'; ctx.fillrect(0, 0, canvas.width, canvas.height); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.clip' in that specification.
ChannelSplitterNode - Web APIs
if your channelsplitternode always has one single input, the amount of outputs is defined by a parameter on its constructor and the call to audiocontext.createchannelsplitter().
... channel interpretation "discrete" constructor channelsplitternode() creates a new channelsplitternode object instance.
... var ac = new audiocontext(); ac.decodeaudiodata(somestereobuffer, function(data) { var source = ac.createbuffersource(); source.buffer = data; var splitter = ac.createchannelsplitter(2); source.connect(splitter); var merger = ac.createchannelmerger(2); // reduce the volume of the left channel only var gainnode = ac.creategain(); gainnode.gain.setvalueattime(0.5, ac.currenttime); splitter.connect(gainnode, 0); // connect the splitter back to the second input of the merger: we // effectivel...
... gainnode.connect(merger, 0, 1); splitter.connect(merger, 1, 0); var dest = ac.createmediastreamdestination(); // because we have used a channelmergernode, we now have a stereo // mediastream we can use to pipe the web audio graph to webrtc, // mediarecorder, etc.
ChildNode.before() - Web APIs
WebAPIChildNodebefore
examples inserting an element var parent = document.createelement("div"); var child = document.createelement("p"); parent.appendchild(child); var span = document.createelement("span"); child.before(span); console.log(parent.outerhtml); // "<div><span></span><p></p></div>" inserting text var parent = document.createelement("div"); var child = document.createelement("p"); parent.appendchild(child); child.before("text"); console.log(parent.outerhtml)...
...; // "<div>text<p></p></div>" inserting an element and text var parent = document.createelement("div"); var child = document.createelement("p"); parent.appendchild(child); var span = document.createelement("span"); child.before(span, "text"); console.log(parent.outerhtml); // "<div><span></span>text<p></p></div>" childnode.before() is unscopable the before() method is not scoped into the with statement.
...ece/blob/master/dom/childnode/before()/before().md (function (arr) { arr.foreach(function (item) { if (item.hasownproperty('before')) { return; } object.defineproperty(item, 'before', { configurable: true, enumerable: true, writable: true, value: function before() { var argarr = array.prototype.slice.call(arguments), docfrag = document.createdocumentfragment(); argarr.foreach(function (argitem) { var isnode = argitem instanceof node; docfrag.appendchild(isnode ?
... argitem : document.createtextnode(string(argitem))); }); this.parentnode.insertbefore(docfrag, this); } }); }); })([element.prototype, characterdata.prototype, documenttype.prototype]); specification specification status comment domthe definition of 'childnode.before()' in that specification.
console - Web APIs
WebAPIConsole
console.group() creates a new inline group, indenting all following output by another level.
... console.groupcollapsed() creates a new inline group, indenting all following output by another level.
...to create a new nested block, call console.group().
... the console.groupcollapsed() method is similar but creates the new block collapsed, requiring the use of a disclosure button to open it for reading.
ConvolverNode.buffer - Web APIs
the buffer property of the convolvernode interface represents a mono, stereo, or 4-channel audiobuffer containing the (possibly multichannel) impulse response used by the convolvernode to create the reverb effect.
... syntax var audioctx = new audiocontext(); var convolver = audioctx.createconvolver(); convolver.buffer = myaudiobuffer; value an audiobuffer.
... example var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var convolver = audioctx.createconvolver(); ...
...dio track via xhr for convolver node var soundsource, concerthallbuffer; ajaxrequest = new xmlhttprequest(); ajaxrequest.open('get', 'concert-crowd.ogg', true); ajaxrequest.responsetype = 'arraybuffer'; ajaxrequest.onload = function() { var audiodata = ajaxrequest.response; audioctx.decodeaudiodata(audiodata, function(buffer) { concerthallbuffer = buffer; soundsource = audioctx.createbuffersource(); soundsource.buffer = concerthallbuffer; }, function(e){"error with decoding audio data" + e.err}); } ajaxrequest.send(); ...
DOMMatrix - Web APIs
WebAPIDOMMatrix
constructor dommatrix() creates and returns a new dommatrix object.
... fromfloat32array() creates a new mutable dommatrix object given an array of single-precision (32-bit) floating-point values.
... fromfloat64array() creates a new mutable dommatrix object given an array of double-precision (64-bit) floating-point values.
... frommatrix() creates a new mutable dommatrix object given an existing matrix or a dommatrixinit dictionary which provides the values for its properties.
DOMPointReadOnly - Web APIs
there are two ways to create a new dompointreadonly instance.
...the perspective: /* 2d */ const point = new dompointreadonly(50, 50); /* 3d */ const point = new dompointreadonly(50, 50, 25); /* 3d with perspective */ const point = new dompointreadonly(100, 100, 100, 1.0); the other option is to use the static dompointreadonly.frompoint() method: const point = dompointreadonly.frompoint({x: 100, y: 100, z: 50; w: 1.0}); constructor dompointreadonly() creates a new dompointreadonly object given the values of its coordinates and perspective.
... to create a point using adompointinit object, you can instead use dompointreadonly.frompoint().
... static methods dompointreadonly.frompoint() a static method that creates a new dompointreadonly object given the coordinates provided in the specified dompointinit object.
DocumentFragment - Web APIs
get="_top"><rect x="266" y="1" width="160" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="346" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">documentfragment</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor documentfragment() creates and returns a new documentfragment object.
... usage notes a common use for documentfragment is to create one, assemble a dom subtree within it, then append or insert the fragment into the dom using node interface methods such as appendchild() or insertbefore().
... an empty documentfragment can be created using the document.createdocumentfragment() method or the constructor.
... example html <ul id="list"></ul> javascript var list = document.queryselector('#list') var fruits = ['apple', 'orange', 'banana', 'melon'] var fragment = new documentfragment() fruits.foreach(function (fruit) { var li = document.createelement('li') li.innerhtml = fruit fragment.appendchild(li) }) list.appendchild(fragment) result specifications specification status comment domthe definition of 'documentfragment' in that specification.
DynamicsCompressorNode - Web APIs
dynamicscompressornode is an audionode that has exactly one input and one output; it is created using the audiocontext.createdynamicscompressor() method.
... number of inputs 1 number of outputs 1 channel count mode "clamped-max" channel count 2 channel interpretation "speakers" constructor dynamicscompressornode() creates a new instance of an dynamicscompressornode object.
... example the below code demonstrates a simple usage of createdynamicscompressor() to add compression to an audio track.
... // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a compressor node var compressor = audioctx.createdynamicscompressor(); compressor.threshold.setvalueattime(-50, audioctx.currenttime); compressor.knee.setvalueattime(40, audioctx.currenttime); compressor.ratio.setvalueattime(12, audioctx.currenttime); compressor.attack.setvalueattime(0, audioctx.currenttime); compressor.release.setvalueattime(0.25, audioctx.currenttime); // connect the audiobuffersourcenode to the destination source.connect(audioctx.destination); button.onclick = function() { var active = button.getattribute('data-active'); if(activ...
Element.getClientRects() - Web APIs
html example 1: this html creates three paragraphs with a <span> inside, each embedded in a <div> block.
...trong>original</strong> <p> <span>paragraph that spans multiple lines</span> </p> </div> <div> <strong>p's rect</strong> <p class="withclientrectsoverlay"> <span>paragraph that spans multiple lines</span> </p> </div> <div> <strong>span's rect</strong> <p> <span class="withclientrectsoverlay">paragraph that spans multiple lines</span> </p> </div> example 2: this html creates three ordered lists.
...ong>original</strong> <ol> <li>item 1</li> <li>item 2</li> </ol> </div> <div> <strong>ol's rect</strong> <ol class="withclientrectsoverlay"> <li>item 1</li> <li>item 2</li> </ol> </div> <div> <strong>each li's rect</strong> <ol> <li class="withclientrectsoverlay">item 1</li> <li class="withclientrectsoverlay">item 2</li> </ol> </div> example 3: this html creates two tables with captions.
...*/ var rects = elt.getclientrects(); for (var i = 0; i != rects.length; i++) { var rect = rects[i]; var tablerectdiv = document.createelement('div'); tablerectdiv.style.position = 'absolute'; tablerectdiv.style.border = '1px solid red'; var scrolltop = document.documentelement.scrolltop || document.body.scrolltop; var scrollleft = document.documentelement.scrollleft || document.body.scrollleft; tablerectdiv.style.margin = tablerectdiv.style.padding = '0'; tablerectdiv.style.top = (rect.top + scrolltop) + ...
Element - Web APIs
WebAPIElement
element.animate() a shortcut method to create and run an animation on an element.
... returns the created animation object instance.
... element.createshadowroot() creates a shadow dom on on the element, turning it into a shadow host.
... touch events touchcancel fired when one or more touch points have been disrupted in an implementation-specific manner (for example, too many touch points are created).
Event.initEvent() - Web APIs
WebAPIEventinitEvent
the event.initevent() method is used to initialize the value of an event created using document.createevent().
... events initialized in this way must have been created with the document.createevent() method.
... example // create the event.
... var event = document.createevent('event'); // create a click event that bubbles up and // cannot be canceled event.initevent('click', true, false); // listen for the event.
File and Directory Entries API support in Firefox - Web APIs
the original file system api was created to let browsers implement support for accessing a sandboxed virtual file system on the user's storage device.
...because of that, an attempt was made to create a spec offering the features of google's api which consensus could be reached on.
...in broad strokes, those limitations can be summarized as follows: content scripts can't create file systems or initiate access to a file system.
...in particular, the filesystemfileentry.createwriter() method, used to create a filewriter to handle writing to a file, is not implemented and will just treturn an error.
GainNode - Web APIs
WebAPIGainNode
number of inputs 1 number of outputs 1 channel count mode "max" channel count 2 (not used in the default count mode) channel interpretation "speakers" constructor gainnode() creates a new instance of a gainnode object.
... you shouldn't manually create a gain node; instead, use the method audiocontext.creategain().
... example the following example shows basic usage of an audiocontext to create a gainnode, which is then used to mute and unmute the audio when a mute button is clicked by changing the gain property value.
... the below snippet wouldn't work as is — for a complete working example, check out our voice-change-o-matic demo (view source.) <div> <button class="mute">mute button</button> </div> var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var gainnode = audioctx.creategain(); var mute = document.queryselector('.mute'); var source; if (navigator.mediadevices.getusermedia) { navigator.mediadevices.getusermedia ( // constraints - only audio needed for this app { audio: true }, // success callback function(stream) { source = audioctx.createmediastreamsource(stream); }, // error callback function(err) { console.log('the following gum error occured: ' + err); } ); } else { console.log('getusermedia not supported on your browse...
HTMLCanvasElement.getContext() - Web APIs
"webgl" (or "experimental-webgl") which will create a webglrenderingcontext object representing a three-dimensional rendering context.
... "webgl2" which will create a webgl2renderingcontext object representing a three-dimensional rendering context.
... "bitmaprenderer" which will create an imagebitmaprenderingcontext which only provides functionality to replace the content of the canvas with a given imagebitmap.
... failifmajorperformancecaveat: boolean that indicates if a context will be created if the system performance is low or if no hardware gpu is available.
HTMLCanvasElement.mozGetAsFile() - Web APIs
examples this example creates an image file from the <canvas> element on the page, then uses a filereader to read the image data from the file.
... html <canvas id="canvas" width="100" height="100"></canvas> <p><a href="#" id="link">click here to try out mozgetasfile()</a>.</p> javascript the following code uses mozgetasfile() to create a file object from the canvas and appends it as an image to the page by loading it as a data url using the readasdataurl() method.
... then a new <img> element is created using the new data url.
...0); ctx.fillstyle = 'rgba(0, 0, 200, 0.5)'; ctx.fillrect(30, 30, 55, 50); var link = document.getelementbyid('link'); link.addeventlistener('click', copy); } function copy() { var canvas = document.getelementbyid('canvas'); var f = canvas.mozgetasfile('test.png'); var reader = new filereader(); reader.readasdataurl(f); reader.onloadend = function() { var newimg = document.createelement('img'); newimg.src = reader.result; document.body.appendchild(newimg); } } window.addeventlistener('load', draw); specifications not part of any specification.
HTMLTableRowElement.insertCell() - Web APIs
the cell does not need to be appended separately with node.appendchild() as would be the case if document.createelement() had been used to create the new <td> element.
... you can not use insertcell() to create a new <th> element though.
...(to be valid html, a <tr> must have at least one <td> element.) finally, we add some text to the cell using document.createtextnode() and node.appendchild().
...row 2</td></tr> <tr><td>row 3</td></tr> </table> javascript function addrow(tableid) { // get a reference to the table let tableref = document.getelementbyid(tableid); // insert a row at the end of the table let newrow = tableref.insertrow(-1); // insert a cell in the row at index 0 let newcell = newrow.insertcell(0); // append a text node to the cell let newtext = document.createtextnode('new bottom row'); newcell.appendchild(newtext); } // call addrow() with the table's id addrow('my-table'); result specifications specification status comment html living standardthe definition of 'htmltablerowelement.insertcell()' in that specification.
The HTML DOM API - Web APIs
an element object instance represents a single element in a document created using either html or an xml vocabulary such as svg.
...this way, the structural features implemented by the node interface are also available to html elements, allowing them to be nested within each other, created and deleted, moved around, and so forth.
... barprop navigator window deprecated web app and browser integration interfaces external obsolete web app and browser integration interfaces applicationcache plugin pluginarray form support interfaces these interfaces provide structure and functionality required by the elements used to create and manage forms, including the <form> and <input> elements.
... beforeunloadevent hashchangeevent history location pagetransitionevent popstateevent web components interfaces these interfaces are used by the web components api to create and manage the available custom elements.
History.pushState() - Web APIs
WebAPIHistorypushState
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().
... description in a sense, calling pushstate() is similar to setting window.location = "#foo", in that both will also create and activate another history entry associated with the current document.
...in contrast, setting window.location = "#foo"; only creates a new history entry if the current hash isn't #foo.
... examples this creates a new browser history state setting the state, title, and url.
IDBCursor.update() - Web APIs
WebAPIIDBCursorupdate
if the cursor points to a record that has just been deleted, a new record is created.
... invalidstateerror the cursor was created using idbindex.openkeycursor, is currently being iterated, or has iterated past its end.
... example in this simple fragment we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store.
...ion(event) { const cursor = event.target.result; if (cursor) { if (cursor.value.albumtitle === 'a farewell to kings') { const updatedata = cursor.value; updatedata.year = 2050; const request = cursor.update(updatedata); request.onsuccess = function() { console.log('a better album year?'); }; }; const listitem = document.createelement('li'); listitem.innerhtml = '<strong>' + cursor.value.albumtitle + '</strong>, ' + cursor.value.year; list.appendchild(listitem); cursor.continue(); } else { console.log('entries displayed.'); } }; }; specifications specification status comment indexed database api 2.0the definition of 'update()' in that specification.
IDBDatabase.close() - Web APIs
WebAPIIDBDatabaseclose
the connection is not actually closed until all transactions created using this connection are complete.
... no new transactions can be created for this connection once this method is called.
... methods that create transactions throw an exception if a closing operation is pending.
... // create event handlers for both success and failure of dbopenrequest.onerror = function(event) { note.innerhtml += "<li>error loading database.</li>"; }; dbopenrequest.onsuccess = function(event) { note.innerhtml += "<li>database initialised.</li>"; // store the result of opening the database in the db variable.
IDBIndex - Web APIs
WebAPIIDBIndex
properties idbindex.isautolocale read only returns a boolean indicating whether the index had a locale value of auto specified upon its creation (see createindex()'s optionalparameters.) idbindex.locale read only returns the locale of the index (for example en-us, or pl) if it had a locale value specified upon its creation (see createindex()'s optionalparameters.) idbindex.name the name of this index.
... idbindex.opencursor() returns an idbrequest object, and, in a separate thread, creates a cursor over the specified key range.
... idbindex.openkeycursor() returns an idbrequest object, and, in a separate thread, creates a cursor over the specified key range, as arranged by this index.
...po (view the example live.) function displaydatabyindex() { tableentry.innerhtml = ''; var transaction = db.transaction(['contactslist'], 'readonly'); var objectstore = transaction.objectstore('contactslist'); var myindex = objectstore.index('lname'); myindex.opencursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var tablerow = document.createelement('tr'); tablerow.innerhtml = '<td>' + cursor.value.id + '</td>' + '<td>' + cursor.value.lname + '</td>' + '<td>' + cursor.value.fname + '</td>' + '<td>' + cursor.value.jtitle + '</td>' + '<td>' + cursor.value.company + '</td>' + '<td>' + cursor.value...
IDBRequest.transaction - Web APIs
['todolist'], "readwrite").objectstore('todolist'); // get the to-do list object that has this title as it's title var objectstoretitlerequest = objectstore.get(title); objectstoretitlerequest.onsuccess = function() { // grab the data object returned as the result var data = objectstoretitlerequest.result; // update the notified value in the object to "yes" data.notified = "yes"; // create another request that inserts the item back // into the database var updatetitlerequest = objectstore.put(data); // log the transaction that originated this request console.log("the transaction that originated this request is " + updatetitlerequest.transaction); // when this new request succeeds, run the displaydata() // function again to update the display updatetitlerequest.onsuc...
... var db = openrequest.result; if (event.oldversion < 1) { // new database, create "books" object store.
... db.createobjectstore('books'); } if (event.oldversion < 2) { // upgrading from v1 database: add index on "title" to "books" store.
... var bookstore = openrequest.transaction.objectstore('books'); bookstore.createindex('by_title', 'title'); } }; openrequest.onsuccess = function() { console.log(openrequest.transaction); // will log "null".
IDBTransaction - Web APIs
rect x="151" y="1" width="140" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="221" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">idbtransaction</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} transactions are started when the transaction is created, not when the first request is placed; for example consider this: var trans1 = db.transaction("foo", "readwrite"); var trans2 = db.transaction("foo", "readwrite"); var objectstore2 = trans2.objectstore("foo") var objectstore1 = trans1.objectstore("foo") objectstore2.put("2", "key"); objectstore1.put("1", "key"); after the code is executed the object store should contain the value "2", since t...
... version_change "versionchange" (2 in chrome) allows any operation to be performed, including ones that delete and create object stores and indexes.
...this is used a lot below db = dbopenrequest.result; // add the data to the database adddata(); }; function adddata() { // create a new object to insert into the idb var newitem = [ { tasktitle: "walk dog", hours: 19, minutes: 30, day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction, ready to add data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(event) { note.innerh...
...duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of the request (this does not mean the item // has been stored successfully in the db - for that you need transaction.oncomplete) note.innerhtml += '<li>request successful.</li>'; }; }; specifications specification status comment indexed database api 2...
IIRFilterNode.getFrequencyResponse() - Web APIs
the two output arrays, magresponseoutput and phaseresponseoutput, must be created before calling this method; they must be the same size as the array of input frequency values (frequencyarray).
...we first create the float32array objects we need, one containing the input frequencies, and two to receive the output magnitude and phase values: var myfrequencyarray = new float32array(5); myfrequencyarray[0] = 1000; myfrequencyarray[1] = 2000; myfrequencyarray[2] = 3000; myfrequencyarray[3] = 4000; myfrequencyarray[4] = 5000; var magresponseoutput = new float32array(5); var phaseresponseoutput = new float32a...
...rray(5); next we create a <ul> element in our html to contain our results, and grab a reference to it in our javascript: <p>iir filter frequency response for: </p> <ul class="freq-response-output"> </ul> var freqresponseoutput = document.queryselector('.freq-response-output'); finally, after creating our filter, we use getfrequencyresponse() to generate the response data and put it in our arrays, then loop through each data set and output them in a human-readable list at the bottom of the page: var feedforwardcoefficients = [0.1, 0.2, 0.3, 0.4, 0.5]; var feedbackcoefficients = [0.5, 0.4, 0.3, 0.2, 0.1]; var iirfilter = audioctx.createiirfilter(feedforwardcoefficients, feedbackcoefficients); ...
... function calcfrequencyresponse() { iirfilter.getfrequencyresponse(myfrequencyarray, magresponseoutput, phaseresponseoutput); for(i = 0; i <= myfrequencyarray.length-1;i++){ var listitem = document.createelement('li'); listitem.innerhtml = '<strong>' + myfrequencyarray[i] + 'hz</strong>: magnitude ' + magresponseoutput[i] + ', phase ' + phaseresponseoutput[i] + ' radians.'; freqresponseoutput.appendchild(listitem); } } calcfrequencyresponse(); specifications specification status comment web audio apithe definition of 'getfrequencyresponse()' in that specification.
IIRFilterNode - Web APIs
all even-ordered iir filters can be created using biquadfilternode.
... however, if you need to create an odd-ordered iir filter, you'll need to use iirfilternode.
... once the node has been created, you can't change its coefficients.
... constructor iirfilternode() creates a new instance of an iirfilternode object.
ImageData.data - Web APIs
WebAPIImageDatadata
syntax imagedata.data examples getting an imagedata object's pixel data this example creates an imagedata object that is 100 pixels wide and 100 pixels tall, making 10,000 pixels in all.
... let imagedata = new imagedata(100, 100); console.log(imagedata.data); // uint8clampedarray[40000] console.log(imagedata.data.length); // 40000 filling a blank imagedata object this example creates and fills a new imagedata object with colorful pixels.
... const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); const imagedata = ctx.createimagedata(100, 100); // iterate through every pixel for (let i = 0; i < imagedata.data.length; i += 4) { // percentage in the x direction, times 255 let x = (i % 400) / 400 * 255; // percentage in the y direction, times 255 let y = math.ceil(i / 400) / 100 * 255; // modify pixel data imagedata.data[i + 0] = x; // r value imagedata.data[i + 1] = y; // g value imagedata.data[i + 2] = 255 - x; /...
.../ b value imagedata.data[i + 3] = 255; // a value } // draw image data to the canvas ctx.putimagedata(imagedata, 20, 20); result more examples for more examples using imagedata.data, see pixel manipulation with canvas, canvasrenderingcontext2d.createimagedata(), and canvasrenderingcontext2d.putimagedata().
ImageData - Web APIs
WebAPIImageData
it is created using the imagedata() constructor or creator methods on the canvasrenderingcontext2d object associated with a canvas: createimagedata() and getimagedata().
... constructors imagedata() creates an imagedata object from a given uint8clampedarray and the size of the image it contains.
... if no array is given, it creates an image of a transparent black rectangle.
... note that this is the most common way to create such an object in workers as createimagedata() is not available there.
MSSiteModeEvent - Web APIs
dom information inheritance hierarchy event mssitemodeevent methods method description initevent initializes a new generic event that the createevent method created.
... *note that as of microsoft edge, the createevent()/initevent() constructor pattern for synthetic events is deprecated.
... istrusted gets a value that indicates whether a trusted event source created an event.
... although this event inherits from the event object, it cannot be created by using createevent.
MediaSource.addSourceBuffer() - Web APIs
the addsourcebuffer() method of the mediasource interface creates a new sourcebuffer of the given mime type and adds it to the mediasource's sourcebuffers list.
... syntax var sourcebuffer = mediasource.addsourcebuffer(mimetype); parameters mimetype a domstring specifying the mime type of the sourcebuffer to create and add to the mediasource.
... return value a sourcebuffer object representing the new source buffer that has been created and added to the media source.
...urce for further investigation.) var asseturl = 'frag_bunny.mp4'; // need to be specific for blink regarding codecs // ./mp4info frag_bunny.mp4 | grep codec var mimecodec = 'video/mp4; codecs="avc1.42e01e, mp4a.40.2"'; if ('mediasource' in window && mediasource.istypesupported(mimecodec)) { var mediasource = new mediasource; //console.log(mediasource.readystate); // closed video.src = url.createobjecturl(mediasource); mediasource.addeventlistener('sourceopen', sourceopen); } else { console.error('unsupported mime type or codec: ', mimecodec); } function sourceopen (_) { //console.log(this.readystate); // open var mediasource = this; var sourcebuffer = mediasource.addsourcebuffer(mimecodec); fetchab(asseturl, function (buf) { sourcebuffer.addeventlistener('updateend', fun...
MediaStream Recording API - Web APIs
create a mediarecorder object, specifying the source stream and any desired options (such as the container's mime type or the desired bit rates of its tracks).
... } } function download() { var blob = new blob(recordedchunks, { type: "video/webm" }); var url = url.createobjecturl(blob); var a = document.createelement("a"); document.body.appendchild(a); a.style = "display: none"; a.href = url; a.download = "test.webm"; a.click(); window.url.revokeobjecturl(url); } // demo: to download after 9sec settimeout(event => { console.log("stopping"); mediarecorder.stop(); }, 9000); examining and controlling the recorder status you can also use the pro...
... in this code snippet, enumeratedevices() is used to examine the available input devices, locate those which are audio input devices, and create <option> elements that are then added to a <select> element representing an input source picker.
... navigator.mediadevices.enumeratedevices() .then(function(devices) { devices.foreach(function(device) { let menu = document.getelementbyid("inputdevices"); if (device.kind == "audioinput") { let item = document.createelement("option"); item.innerhtml = device.label; item.value = device.deviceid; menu.appendchild(item); } }); }); code similar to this can be used to let the user restrict the set of devices they wish to use.
Capabilities, constraints, and settings - Web APIs
advanced constraints so-called advanced constraints are created by adding an advanced property to the constraint set; this property's value is an array of additional constraint sets which are considered optional.
... example: constraint exerciser in this example, we create an exerciser which lets you experiment with media constraints by editing the source code describing the constraint sets for audio and video tracks.
...udiotracks.length) { audiotrack = audiotracks[0]; } if (videotracks.length) { videotrack = videotracks[0]; } }).then(function() { return new promise(function(resolve) { videoelement.onloadedmetadata = resolve; }); }).then(function() { getcurrentsettings(); }).catch(handleerror); } there are several steps here: it calls buildconstraints() to create the mediatrackconstraints objects for the two tracks from the code in the edit boxes.
... let supportedconstraints = navigator.mediadevices.getsupportedconstraints(); for (let constraint in supportedconstraints) { if (supportedconstraints.hasownproperty(constraint)) { let elem = document.createelement("li"); elem.innerhtml = "<code><a href='/docs/web/api/mediatracksupportedconstraints/" .concat(constraint) + "' target='_blank'>" + constraint + "</a></code>"; supportedconstraintlist.appendchild(elem); } } error handling we also have some simple error handling code; handleerror() is called to handle promises which fail, and the log() function appends the error messag...
OfflineAudioContext - Web APIs
="1" width="190" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="406" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">offlineaudiocontext</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor offlineaudiocontext.offlineaudiocontext() creates a new offlineaudiocontext instance.
... at this point we create another audio context, create an audiobuffersourcenode inside it, and set its buffer to be equal to the promise audiobuffer.
... note: for a working example, see our offline-audio-context-promise github repo (see the source code too.) // define online and offline audio context var audioctx = new audiocontext(); var offlinectx = new offlineaudiocontext(2,44100*40,44100); source = offlinectx.createbuffersource(); // use xhr to load an audio track, and // decodeaudiodata to decode it and offlineaudiocontext to render it function getdata() { request = new xmlhttprequest(); request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; source.c...
...onnect(offlinectx.destination); source.start(); //source.loop = true; offlinectx.startrendering().then(function(renderedbuffer) { console.log('rendering completed successfully'); var song = audioctx.createbuffersource(); song.buffer = renderedbuffer; song.connect(audioctx.destination); play.onclick = function() { song.start(); } }).catch(function(err) { console.log('rendering failed: ' + err); // note: the promise should reject when startrendering is called a second time on an offlineaudiocontext }); }); } request.send(); } // run getdata to start the process off getdata(); specifications specification status comment web audio apithe definition of 'of...
OffscreenCanvas - Web APIs
creates a new offscreencanvas object.
... offscreencanvas.converttoblob() creates a blob object representing the image contained in the canvas.
... offscreencanvas.transfertoimagebitmap() creates an imagebitmap object from the most recently rendered image of the offscreencanvas.
... to display the imagebitmap, you can use a imagebitmaprenderingcontext context, which can be created by calling canvas.getcontext("bitmaprenderer") on a (visible) canvas element.
OscillatorNode.setPeriodicWave() - Web APIs
returns undefined example the following example illustrates simple usage of createperiodicwave(), recreating a sine wave from a periodic wave.
... var real = new float32array(2); var imag = new float32array(2); var ac = new audiocontext(); var osc = ac.createoscillator(); real[0] = 0; imag[0] = 0; real[1] = 1; imag[1] = 0; var wave = ac.createperiodicwave(real, imag); osc.setperiodicwave(wave); osc.connect(ac.destination); osc.start(); osc.stop(2); this works because a sound that contains only a fundamental tone is by definition a sine wave.
... here, we create a periodicwave with two values.
...here, with createperiodicwave(), you specify the frequencies, and the browser performs a an inverse fourier transform to get a time domain buffer for the frequency of the oscillator.
ParentNode.append() - Web APIs
WebAPIParentNodeappend
examples appending an element let parent = document.createelement("div") let p = document.createelement("p") parent.append(p) console.log(parent.childnodes) // nodelist [ <p> ] appending text let parent = document.createelement("div") parent.append("some text") console.log(parent.textcontent) // "some text" appending an element and text let parent = document.createelement("div") let p = document.createelement("p") parent.append("some text", p) co...
... let parent = document.createelement("div") with(parent) { append("foo") } // referenceerror: append is not defined polyfill you can polyfill the append() method in internet explorer 9 and higher with the following code: // source: https://github.com/jserz/js_piece/blob/master/dom/parentnode/append()/append().md (function (arr) { arr.foreach(function (item) { if (item.hasownproperty('append')) { return; } object.defineproperty(item, 'append', { configurable: true, enumerable: true, writable: true, value: function append() { var argar...
...r = array.prototype.slice.call(arguments), docfrag = document.createdocumentfragment(); argarr.foreach(function (argitem) { var isnode = argitem instanceof node; docfrag.appendchild(isnode ?
... argitem : document.createtextnode(string(argitem))); }); this.appendchild(docfrag); } }); }); })([element.prototype, document.prototype, documentfragment.prototype]); specification specification status comment domthe definition of 'parentnode.append()' in that specification.
ParentNode.prepend() - Web APIs
examples prepending an element var parent = document.createelement("div"); var p = document.createelement("p"); var span = document.createelement("span"); parent.append(p); parent.prepend(span); console.log(parent.childnodes); // nodelist [ <span>, <p> ] prepending text var parent = document.createelement("div"); parent.append("some text"); parent.prepend("headline: "); console.log(parent.textcontent); // "headline: some text" appending an element a...
...nd text var parent = document.createelement("div"); var p = document.createelement("p"); parent.prepend("some text", p); console.log(parent.childnodes); // nodelist [ #text "some text", <p> ] parentnode.prepend() is unscopable the prepend() method is not scoped into the with statement.
... var parent = document.createelement("div"); with(parent) { prepend("foo"); } // referenceerror: prepend is not defined polyfill you can polyfill the prepend() method if it's not available: // source: https://github.com/jserz/js_piece/blob/master/dom/parentnode/prepend()/prepend().md (function (arr) { arr.foreach(function (item) { if (item.hasownproperty('prepend')) { return; } object.defineproperty(item, 'prepend', { configurable: true, enumerable: true, writable: true, value: function prepend() { var argarr = array.prototype.slice.call(arguments), docfrag = document.createdocumentfragment(); argarr.foreach(function (argitem) { var isnode = argitem instanceof nod...
...argitem : document.createtextnode(string(argitem))); }); this.insertbefore(docfrag, this.firstchild); } }); }); })([element.prototype, document.prototype, documentfragment.prototype]); specification specification status comment domthe definition of 'parentnode.prepend()' in that specification.
PerformanceEntry.startTime - Web APIs
"mark" - returns the timestamp when the mark was created by a call to performance.mark().
... "measure" - returns the timestamp when the measure was created by a call to performance.measure().
... syntax entry.starttime; return value a domhighrestimestamp representing the first timestamp when the performance entry was created.
...performance.mark not supported"); return; } // create some performance entries via the mark() method performance.mark("begin"); do_work(50000); performance.mark("end"); // use getentries() to iterate through the each entry var p = performance.getentries(); for (var i=0; i < p.length; i++) { log("entry[" + i + "]"); check_performanceentry(p[i]); } } function check_performanceentry(obj) { var properties = ["name", "entrytype",...
PublicKeyCredential - Web APIs
it inherits from credential, and was created by the web authentication api extension to the credential management api.
...it is either of type authenticatorattestationresponse if the publickeycredential was the results of a navigator.credentials.create() call, or of type authenticatorassertionresponse if the publickeycredential was the result of a navigator.credentials.get() call.
... examples creating a new instance of publickeycredential here, we use navigator.credentials.create() to generate a new credential.
... var publickey = { challenge: /* from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(16), name: "jdoe@example.com", displayname: "john doe" }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { var response = newcredentialinfo.response; var clientextensionsresults = newcredentialinfo.getclientextensionresults(); }).catch(function (err) { console.error(err); }); getting an existing instance of publickeycredential here, we fetch an existing credential from an authenticator, using navigator.credentials.get().
RTCConfiguration - Web APIs
if the remote endpoint is bundle-aware, all media tracks and data channels are bundled onto a single transport at the completion of negotiation, regardless of policy used, and any superfluous transports that were created initially are closed at that point.
... constant description "balanced" the ice agent initially creates one rtcdtlstransport for each type of content added: audio, video, and data channels.
... "max-compat" the ice agent initially creates one rtcdtlstransport per media track and a separate one for data channels.
... "max-bundle" the ice agent initially creates only a single rtcdtlstransport to carry all of the rtcpeerconnection's data.
RTCDataChannel.label - Web APIs
a data channel's label is set when the channel is created by calling rtcpeerconnection.createdatachannel().
... syntax var name = adatachannel.label; value a string identifier assigned by the web site or app when the data channel was created, as specified when rtcpeerconnection.createdatachannel() was called to create the channel.
... example this sample creates a data channel on an rtcpeerconnection, then, some time later, sets the content of a ui element to display the channel's name.
... var pc = new rtcpeerconnection(); var dc = pc.createdatachannel("my channel"); /* ...
RTCDataChannel - Web APIs
to create a data channel and ask a remote peer to join you, call the rtcpeerconnection's createdatachannel() method.
...these labels are not required to be unique.maxpacketlifetime read only the read-only rtcdatachannel property maxpacketlifetime returns the amount of time, in milliseconds, the browser is allowed to take to attempt to transmit a message, as set when the data channel was created, or null.maxretransmits read only the read-only rtcdatachannel property maxretransmits returns the maximum number of times the browser should try to retransmit a message before giving up, as set when the data channel was created, or null, which indicates that there is no maximum.negotiated read only the read-only rtcdatachannel property negotiated indicates whether the rtcdatachannel's connect...
...if no protocol was specified when the data channel was created, then this property's value is "" (the empty string).readystate read only the read-only rtcdatachannel property readystate returns an enum of type rtcdatachannelstate which indicates the state of the data channel's underlying data connection.reliable read only the read-only rtcdatachannel property reliable indicates whether or not the data channel is reliable.stream read only the depre...
... example var pc = new rtcpeerconnection(); var dc = pc.createdatachannel("my channel"); dc.onmessage = function (event) { console.log("received: " + event.data); }; dc.onopen = function () { console.log("datachannel open"); }; dc.onclose = function () { console.log("datachannel close"); }; specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdatachannel'...
RTCIceServers.urls - Web APIs
WebAPIRTCIceServerurls
a single ice server this example creates a new rtcpeerconnection which will use a stun server at stunserver.example.org to negotiate connections.
... a single ice server with authentication the second example creates a new rtcpeerconnection which will use a turn server at turnserver.example.org to negotiate connections.
... mypeerconnection = new rtcpeerconnection({ iceservers: [ { urls: "turn:turnserver.example.org", username: "webrtc", credential: "turnpassword" } ] }); a single ice server with multiple urls the next example creates a new rtcpeerconnection which will use a single turn server which has multiple urls.
... mypeerconnection = new rtcpeerconnection({ iceservers: [ { urls: ["turns:turnserver.example.org", "turn:turnserver.example.org"], username: "webrtc", credential: "turnpassword" } ] }); multiple ice servers finally, this example creates a new rtcpeerconnection which will use one of two servers for ice negotiation.
RTCPeerConnection: negotiationneeded event - Web APIs
examples in this example, we use addeventlistener() to create an event handler for negotiationneeded.
... its role is to create an sdp offer and send it through the signaling channel to the remote peer.
... pc.addeventlistener("negotiationneeded", ev => { pc.createoffer() .then(offer => return pc.setlocaldescription(offer)) .then(() => sendsignalingmessage({ type: "video-offer", sdp: pc.localdescription })) .catch(err => { /* handle error */ ); }, false); after creating the offer, the local end is configured by calling rtcpeerconnection.setlocaldescription(); then a signaling message is created and sent to the remote peer through the signaling server, to share that offer with the other peer.
... you can also set an event handler for the negotiationneeded event by assigning the event handler function to the rtcpeerconnection.onnegotiationneeded property: pc.onnegotiationneeded = ev => { pc.createoffer() .then(offer => return pc.setlocaldescription(offer)) .then(() => sendsignalingmessage({ type: "video-offer", sdp: pc.localdescription })) .catch(err => { /* handle error */ ); }; for a more detailed example, see starting negotiation in signaling and video calling.
ReadableStream - Web APIs
constructor readablestream() creates and returns a readable stream object from the given handlers.
... readablestream.getiterator() creates a readablestream async iterator instance and locks the stream to it.
... readablestream.getreader() creates a reader and locks the stream to it.
... examples in the following example, an artificial response is created to stream html fragments fetched from another resource to the browser.
Request.mode - Web APIs
WebAPIRequestmode
a navigate request is created only while navigating between documents.
... for example, when a request object is created using the request.request constructor, the value of the mode property for that request is set to cors.
... however, for requests created other than by the request.request constructor, no-cors is typically used as the mode; for example, for embedded resources where the request is initiated from markup, unless the crossorigin attribute is present, the request is in most cases made using the no-cors mode — that is, for the <link> or <script> elements (except when used with modules), or <img>, <audio>, <video>, <object>, <embed>, or <iframe> elements.
... example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request mode in a variable: var myrequest = new request('flowers.jpg'); var mymode = myrequest.mode; // returns "cors" by default specifications specification status comment fetchthe definition of 'mode' in that specification.
Response.clone() - Web APIs
WebAPIResponseclone
the clone() method of the response interface creates a clone of a response object, identical in every way, but stored in a different variable.
... example in our fetch response clone example (see fetch response clone live) we create a new request object using the request() constructor, passing it a jpg path.
...when the fetch resolves successfully, we clone it, extract a blob from both responses using two body.blob calls, create object urls out of the blobs using url.createobjecturl, and display them in two separate <img> elements.
... var image1 = document.queryselector('.img1'); var image2 = document.queryselector('.img2'); var myrequest = new request('flowers.jpg'); fetch(myrequest).then(function(response) { var response2 = response.clone(); response.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); image1.src = objecturl; }); response2.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); image2.src = objecturl; }); }); specifications specification status comment fetchthe definition of 'clone()' in that specification.
SVGAnimationElement - Web APIs
svganimationelement.beginelement() creates a begin instance time for the current time.
... svganimationelement.beginelementat() creates a begin instance time for the current time plus the specified offset.
... svganimationelement.endelement() creates an end instance time for the current time.
... svganimationelement.endelementat() creates a end instance time for the current time plus the specified offset.
Using server-sent events - Web APIs
receiving events from the server the server-sent event api is contained in the eventsource interface; to open a connection to the server to begin receiving events from it, create a new eventsource object with the url of a script that generates the events.
... for example: const evtsource = new eventsource("ssedemo.php"); if the event generator script is hosted on a different origin, a new eventsource object should be created with both the url and an options dictionary.
... for example, assuming the client script is on example.com: const evtsource = new eventsource("//api.example.com/ssedemo.php", { withcredentials: true } ); once you've instantiated your event source, you can begin listening for messages from the server by attaching a handler for the message event: evtsource.onmessage = function(event) { const newelement = document.createelement("li"); const eventlist = document.getelementbyid("list"); newelement.innerhtml = "message: " + event.data; eventlist.appendchild(newelement); } this code listens for incoming messages (that is, notices from the server that do not have an event field on them) and appends the message text to a list in the document's html.
... you can also listen for events with addeventlistener(): evtsource.addeventlistener("ping", function(event) { const newelement = document.createelement("li"); const time = json.parse(event.data).time; newelement.innerhtml = "ping at " + time; eventlist.appendchild(newelement); }); this code is similar, except that it will be called automatically whenever the server sends a message with the event field set to "ping"; it then parses the json in the data field and outputs that information.
Using Touch Events - Web APIs
touchcancel - fired when a touch point has been disrupted in an implementation-specific manner (for example, too many touch points are created).
...another potential factor is time; for example, the time elapsed between the touch's start and the touch's end, or the time lapse between two consecutive taps intended to create a double-tap gesture.
... // create touchstart handler someelement.addeventlistener('touchstart', function(ev) { // iterate through the touch points that were activated // for this element and process each event 'target' for (var i=0; i < ev.targettouches.length; i++) { process_target(ev.targettouches[i].target); } }, false); prevent the browser from processing emulated mouse events.
...that is, the abstract pointer creates a unified input model that can represent a contact point for a finger, pen/stylus or mouse.
URL API - Web APIs
WebAPIURL API
let addr = new url("/docs/web/api/url_api"); let host = addr.host; let path = addr.pathname; the snippet above creates a url object for the article you're reading right now, then fetches the host and pathname properties.
...for example, to create a url and set its username: let myusername = "someguy"; let addr = new url("https://mysite.com/login"); addr.username = myusername; setting the value of username not only sets that property's value, but it updates the overall url.
... examples if you want to process the parameters included in a url, you could do it manually, but it's much easier to create a url object to do it for you.
... function filltablewithparameters(tbl) { let url = new url(document.location.href); url.searchparams.sort(); let keys = url.searchparams.keys(); for (let key of keys) { let val = url.searchparams.get(key); let row = document.createelement("tr"); let cell = document.createelement("td"); cell.innertext = key; row.appendchild(cell); cell = document.createelement("td"); cell.innertext = val; row.appendchild(cell); tbl.appendchild(row); }; } a working version of this example can be found on glitch.
WaveShaperNode.curve - Web APIs
syntax var audioctx = new audiocontext(); var distortion = audioctx.createwaveshaper(); distortion.curve = mycurvedataarray; // mycurvedataarray is a float32array value a float32array.
... example the following example shows basic usage of an audiocontext to create a wave shaper node.
...their s-shape, for instance, helps create a smoother sounding result.
... var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var distortion = audioctx.createwaveshaper(); ...
WaveShaperNode - Web APIs
number of inputs 1 number of outputs 1 channel count mode "max" channel count 2 (not used in the default count mode) channel interpretation "speakers" constructor waveshapernode() creates a new instance of an waveshapernode object.
... example the following example shows basic usage of an audiocontext to create a wave shaper node.
...their s-shape, for instance, helps create a smoother sounding result.
... var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var distortion = audioctx.createwaveshaper(); ...
WebGLRenderingContext.bufferData() - Web APIs
the webglrenderingcontext.bufferdata() method of the webgl api initializes and creates the buffer object's data store.
...if null, a data store is still created, but the content is uninitialized and undefined.
... exceptions a gl.out_of_memory error is thrown if the context is unable to create a data store with the given size.
... examples using bufferdata var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var buffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, buffer); gl.bufferdata(gl.array_buffer, 1024, gl.static_draw); getting buffer information to check the current buffer usage and buffer size, use the webglrenderingcontext.getbufferparameter() method.
WebGL constants - Web APIs
each set of three vertices creates a separate triangle.
... buffer_usage 0x8765 passed to getbufferparameter to get the hint for the buffer passed in when it was created.
...rgba 0x1908 luminance 0x1909 luminance_alpha 0x190a pixel types constant name value description unsigned_byte 0x1401 unsigned_short_4_4_4_4 0x8033 unsigned_short_5_5_5_1 0x8034 unsigned_short_5_6_5 0x8363 shaders constants passed to webglrenderingcontext.createshader() or webglrenderingcontext.getshaderparameter() constant name value description fragment_shader 0x8b30 passed to createshader to define a fragment shader.
... vertex_shader 0x8b31 passed to createshader to define a vertex shader compile_status 0x8b81 passed to getshaderparamter to get the status of the compilation.
Animating textures in WebGL - Web APIs
you'll need to include it if you create your own project based on this code.
... getting access to the video the first step is to create the <video> element that we'll use to retrieve the video frames: // will set to true when video can be copied to texture var copyvideo = false; function setupvideo(url) { const video = document.createelement('video'); var playing = false; var timeupdate = false; video.autoplay = true; video.muted = true; video.loop = true; // waiting for these 2 events ensures // there is data in the video video.addeventlistener('playing', function() { playing = true; checkready(); }, true); video.addeventlistener('timeupdate', function() { timeupdate = true; checkready(); }, true); video.src = url; video.play(); function checkready() { ...
... if (playing && timeupdate) { copyvideo = true; } } return video; } first we create a video element.
...instead, all it does is create an empty texture object, put a single pixel in it, and set its filtering for later use: function inittexture(gl) { const texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); // because video has to be download over the internet // they might take a moment until it's ready so // put a single pixel in the texture so we can // use it immediately.
Lighting in WebGL - Web APIs
you'll need to include it if you create your own project based on this code.
... const normalbuffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, normalbuffer); const vertexnormals = [ // front 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, // back 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, // top 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, // botto...
... return { position: positionbuffer, normal: normalbuffer, texturecoord: texturecoordbuffer, indices: indexbuffer, }; this should look pretty familiar by now; we create a new buffer, bind it to be the buffer we're working with, then send along our array of vertex normals into the buffer by calling bufferdata().
... stride, offset); gl.enablevertexattribarray( programinfo.attriblocations.vertexnormal); } finally, we need to update the code that builds the uniform matrices to generate and deliver to the shader a normal matrix, which is used to transform the normals when dealing with the current orientation of the cube in relation to the light source: const normalmatrix = mat4.create(); mat4.invert(normalmatrix, modelviewmatrix); mat4.transpose(normalmatrix, normalmatrix); ...
Using shaders to apply color in WebGL - Web APIs
« previousnext » having created a square plane in the previous demonstration, the next obvious step is to add a splash of color to it.
...you'll need to include it if you create your own project based on this code.
...to do this, we first need to create an array of vertex colors, then store it into a webgl buffer.
... const colors = [ 1.0, 1.0, 1.0, 1.0, // white 1.0, 0.0, 0.0, 1.0, // red 0.0, 1.0, 0.0, 1.0, // green 0.0, 0.0, 1.0, 1.0, // blue ]; const colorbuffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, colorbuffer); gl.bufferdata(gl.array_buffer, new float32array(colors), gl.static_draw); return { position: positionbuffer, color: colorbuffer, }; } this code starts by creating a javascript array containing four 4-value vectors, one for each vertex color.
WebRTC API - Web APIs
rtctrackevent the interface used to represent a track event, which indicates that an rtcrtpreceiver object was added to the rtcpeerconnection object, indicating that a new incoming mediastreamtrack was created and added to the rtcpeerconnection.
... negotiationneeded informs the rtcpeerconnection that it needs to perform session negotiation by calling createoffer() followed by setlocaldescription().
... rtcsessiondescriptioncallback the rtcsessiondescriptioncallback is passed into the rtcpeerconnection object when requesting it to create offers or answers.
... signaling and two-way video calling a tutorial and example which turns a websocket-based chat system created for a previous example and adds support for opening video calls among participants.
Attestation and Assertion - Web APIs
attestationobject - cryptographic attestation that a newly generated keypair was created by that authenticator.
... android safetynet -prior to android key attestation, the only option for android devices was to create android safetynet attestations fido u2f - security keys that implement the fido u2f standard use this format none - browsers may prompt users whether they want a site to be allowed to see their attestation data and/or may remove attestation data from the authenticator's response if the `attestation` parameter in `navigator.credentials.create()` is set to `none` the purpose of at...
...this creates an assertion.
... authenticatordata - data created and/or used by the authenticator signature - a signature over the clientdatajson and authenticatordata that can be verified with the public key that was created during registration.
Using the Web Storage API - Web APIs
these mechanisms are available via the window.sessionstorage and window.localstorage properties (to be more precise, in supporting browsers the window object implements the windowlocalstorage and windowsessionstorage objects, which the localstorage and sessionstorage properties are members of) — invoking one of these will create an instance of the storage object, through which data items can be set, retrieved, and removed.
... example to illustrate some typical web storage usage, we have created an example, imaginatively called web storage demo.
... setting values in storage storage.setitem() is used both to create new data items, and (if the data item already exists) update existing values.
... this takes two arguments — the key of the data item to create/modify, and the value to store in it.
WritableStreamDefaultWriter - Web APIs
the writablestreamdefaultwriter interface of the the streams api is the object returned by writablestream.getwriter() and once created locks the writer to the writablestream ensuring that no other streams can write to the underlying sink.
... constructor writablestreamdefaultwriter() creates a new writablestreamdefaultwriter object instance.
...it then calls a function called sendmessage(), passing the newly created stream and a string.
...new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) { return new promise((resolve, reject) => { var buffer = new arraybuffer(2); var view = new uint16array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listitem = document.createelement('li'); listitem.textcontent = "chunk decoded: " + decoded; list.appendchild(listitem); result += decoded; resolve(); }); }, close() { var listitem = document.createelement('li'); listitem.textcontent = "[message received] " + result; list.appendchild(listitem); }, abort(err) { console.log("sink error:", err); } }, queuing...
How to check the security state of an XMLHTTPRequest over SSL - Web APIs
by setting the mozbackgroundrequest property of the request object and modifying the example appropriately, you can create your own alert dialog to handle ssl exceptions in your firefox extension or xulrunner application.
... const {cc,ci} = require("chrome"); function createtcperrorfromfailedxhr(xhr) { let status = xhr.channel.queryinterface(ci.nsirequest).status; let errtype; if ((status & 0xff0000) === 0x5a0000) { // security module const nsinsserrorsservice = ci.nsinsserrorsservice; let nsserrorsservice = cc['@mozilla.org/nss_errors_service;1'].getservice(nsinsserrorsservice); let errorclass; // geterrorclass will throw a generic ns_error_failure if the error code is // somehow not in the set of covered errors.
... let error = cc["@mozilla.org/dom-error;1"].createinstance(ci.nsidomdomerror); error.wrappedjsobject.init(errname); return error; // xxx: errtype goes unused } function dumpsecurityinfo(xhr, error) { let channel = xhr.channel; try { dump("connection status:\n"); if (!error) { dump("\tsucceeded\n"); } else { dump("\tfailed: " + error.name + "\n"); } let secinfo = channel.securityinfo; // print...
...); dump("\tsha1 fingerprint = " + cert.sha1fingerprint + "\n"); var validity = cert.validity.queryinterface(ci.nsix509certvalidity); dump("\tvalid from " + validity.notbeforegmt + "\n"); dump("\tvalid until " + validity.notaftergmt + "\n"); } } catch(err) { alert(err); } } function test(url) { var req = cc["@mozilla.org/xmlextras/xmlhttprequest;1"].createinstance(); req.open('get', url, true); req.addeventlistener("error", function(e) { var error = createtcperrorfromfailedxhr(req); dumpsecurityinfo(req, error); }, false); req.onload = function(e) { dumpsecurityinfo(req); }; req.send(); } then test("https://addons.mozilla.org"); produced the following output in my console: connection status: succee...
Sending and Receiving Binary Data - Web APIs
this example reads an image as a binary file and creates an 8-bit unsigned integer array from the raw bytes.
... the following example creates a text file on-the-fly and uses the post method to send the "file" to the server.
...var stream = components.classes["@mozilla.org/network/file-input-stream;1"] .createinstance(components.interfaces.nsifileinputstream); stream.init(file, 0x04 | 0x08, 0644, 0x04); // file is an nsifile instance // try to determine the mime type of the file var mimetype = "text\/plain"; try { var mimeservice = components.classes["@mozilla.org/mime;1"] .getservice(components.interfaces.nsimimeservice); mimetype = mimeservice.gettypefromfile(file); // file is an nsifi...
...le instance } catch (oevent) { /* eat it; just use text/plain */ } // send var req = components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"] .createinstance(components.interfaces.nsixmlhttprequest); req.open('put', url, false); /* synchronous!
XRInputSourceEventInit.inputSource - Web APIs
the xrinputsourceeventinit dictionary's inputsource property is used when calling the xrinputsourceevent() constructor to specify the xrinputsource from which the newly-created event is being sent.
... of course, as a general rule, you won't need to create xrinputsourceeventinit objects yourself.
... syntax let xrinputsourceeventinit.inputsource = xrinputsource; let xrinputsourceeventinit = { inputsource: xrinputsource }; let xrinputsourceevent = new xrinputsourceevent(type, { inputsource: xrinputsource }); value an xrinputsource object indicating the source of the newly-created xrinputsourceevent to be created.
... examples this example creates a new select event and sends it to the xrsession.
XRInputSourcesChangeEvent() - Web APIs
the xrinputsourceschangeevent() constructor creates and returns a new xrinputsourceschangeevent object, representing an update to the list of available webxr input devices.
... you won't typically call this constructor yourself, as these events are created and sent to you by the webxr system.
... return value a newly-created xrinputsourceschangeevent object configured based upon the input parameters provided.
... example the following snippet of code creates a new xrinputsourceschangeevent object indicating that a single new input source, described by an xrinputsource object named newinputsource, has been added to the system.
XRReferenceSpace.getOffsetReferenceSpace() - Web APIs
these values are added to the position and orientation of the current reference space and then the result is used as the position and orientation of the newly created xrreferencespace.
... xrsession.requestreferencespace("local") .then((refspace) => { xrreferencespace = refspace; xrreferencespace = xrreferencespace.getoffsetreferencespace( new xrrigidtransform(startposition, {x:0, y:0, z:1.0, w: 1.0})); xrsession.requestanimationframe(drawframe); }); in this code, we obtain a local reference space, then use getoffsetreferencespace() to create a new space whose origin is adjusted to a position given by startposition and whose orientation is looking directly along the z azis.
... let mouseyaw = 0.0; let mousepitch = 0.0; const inverseorientation = quat.create(); const mouse_speed = 0.003; function rotateviewby(dx, dy) { mouseyaw += dx * mouse_speed; mousepitch += dy * mouse_speed; if (mousepitch < -math.pi * 0.5) { mousepitch = -math.pi * 0.5; } else if (mousepitch > math.pi * 0.5) { mousepitch = math.pi * 0.5; } } finally, we need code that actually applies the computed yaw and pitch to the viewer's orientation.
..., inverseorientation, -mousepitch); quat.rotatey(inverseorientation, inverseorientation, -mouseyaw); let newtransform = new xrrigidtransform({x: 0, y: 0, z: 0}, {x: inverseorientation[0], y: inverseorientation[1], z: inverseorientation[2], w: inverseorientation[3]}); return refspace.getoffsetreferencespace(newtransform); } this function creates an inverse orientation matrix—used to orient the viewer—from the current pitch and yaw values, then uses that matrix as the source of the orientation when calling new xrrigidtransform().
XRSessionEvent() - Web APIs
the webxr device api's xrsessionevent() constructor creates and returns a new xrsessionevent object.
... eventinitdict an object conforming to the xrsessioneventinit dictionary which contains values to be applied to the newly-created event object.
... return value a newly-created xrsessionevent object representing an object of the specfied type and configured as described by the eventinitdict parameter.
... examples this example creates a listiener that watches for the visibility state of the session to change.
ARIA: button role - Accessibility
this role can be used in combination with the aria-pressed attribute to create toggle buttons.
... <div id="savechanges" tabindex="0" role="button" aria-pressed="false">save</div> the above example creates a simple button which is first in the focus order, though <button> or <input> with type="button" should be used for buttons: <button id="savechanges">save</button> note: if using role="button" instead of the semantic <button> or <input type="button"> elements, you will need to make the element focusable and have to define event handlers for click and keydown events, including the enter and space keys, in order to process the user's input.
...but if another tag is used to create a button, the onclick event only fires when clicked by the mouse cursor, even if role="button" is used.
... if(name.length > 0) { listitem = document.createelement('li'); listitem.appendchild(document.createtextnode(name)); // add the new name to the list.
::after (:after) - CSS: Cascading Style Sheets
WebCSS::after
in css, ::after creates a pseudo-element that is the last child of the selected element.
... examples simple usage let's create two classes: one for boring paragraphs and one for exciting ones.
...</span> css .ribbon { background-color: #5bc8f7; } .ribbon::after { content: "this is a fancy orange box."; background-color: #ffba10; border-color: black; border-style: dotted; } result tooltips this example uses ::after, in conjunction with the attr() css expression and a data-descr custom data attribute, to create tooltips.
...this shows how flexible ::before and ::after can be, though for the most accessible experience a semantic disclosure widget created in some other way (such as with details and summary elements) is likely to be more appropriate.
Box alignment in Flexbox - CSS: Cascading Style Sheets
alignment and auto margins there is a specific use case in flexbox where we might think that a justify-self property is what we need, and this is when we want to split a set of flex items, perhaps to create a split navigation pattern.
... by setting a margin of auto on one item in a set of flex items all aligned to start, we can create a split navigation.
... the gap properties row-gap column-gap gap creating fixed size gaps between items on the main axis, the column-gap property will create fixed size gaps between adjacent items.
... on the cross axis the row-gap property will create spacing between adjacent flex lines, therefore flex-wrap must also be set to wrap for this to have any effect.
Basic Concepts of Multicol - CSS: Cascading Style Sheets
defining columns to create a multicol container you must use at least one of the column-* properties, these being column-count and column-width.
...the browser will then assign the correct amount of space to each column box to create the requested number of columns.
... in the below example we use the column-count property to create three columns on the .container element.
...this is because a multicol container creates a new block formatting context (bfc) which means margins on child elements do not collapse with any margin on the container.
Using feature queries - CSS: Cascading Style Sheets
feature queries are created using the css at-rule @supports, and are useful as they give web developers a way to test to see if a browser has support for a certain feature, and then provide css that will only run based on the result of that test.
...to do so, you can include a list of features to test for, separated by and keywords: @supports (property1: value) and (property2: value) { css rules to apply } for example, if the css you want to run requires that the browser supports css shapes and css grid, you could create a rule which checks for both of these things.
...we can't create a fallback by checking for browsers which do not have support, as ie11 doesn't support feature queries either!
... let's say we want to create a layout of three boxes in a row, and ideally we would like to use css grid layout.
Mastering Wrapping of Flex Items - CSS: Cascading Style Sheets
once the first row gets to a point where there is not enough space to place another 160 pixel item, a new flex line is created for the items and so on until all of the items are placed.
...the following live sample uses css grid layout to create a layout that has as many columns of at least 160 pixels as will fit, distributing the extra space between all columns.
... you can see from the live example below that in order to create gaps that do not also create a gap at the edges of the container, we need to use negative margins on the flex container itself.
... i have created this behaviour in the next live example.
Typical use cases of Flexbox - CSS: Cascading Style Sheets
space distributed within the items a different pattern for navigation would be to distribute the available space within the items themselves, rather than create space between them.
... also in this example we are using margins on the flex items to create a gap between items, and a negative margin on the container in order that the items still remain flush with the right and left edges.
... until the gap properties from the box alignment specification are implemented in flexbox, we have to use margins in this way if we want to create a gutter between items.
... patterns like this can make it much easier to create a library of form elements for your design, which easily accommodate additional elements being added.
Column layouts - CSS: Cascading Style Sheets
you will often need to create a layout which has a number of columns, and css provides several ways to do this.
... a continuous thread of content — multi-column layout if you create columns using multi-column layout your text will remain as a continuous stream filling each column in turn.
...therefore to create gaps between items use a margin.
... download this example flexbox can also be used to create layouts where the flex items wrap onto new rows, by setting the flex-wrap property on the container to wrap.
linear-gradient() - CSS: Cascading Style Sheets
the linear-gradient() css function creates an image consisting of a progressive transition between two or more colors along a straight line.
... to create a linear gradient that repeats so as to fill its container, use the repeating-linear-gradient() function instead.
...each point on the axis is a distinct color; to create a smooth gradient, the linear-gradient() function draws a series of colored lines perpendicular to the gradient line, each one matching the color of the point where it intersects the gradient line.
... customizing gradients by adding more color-stop points on the gradient line, you can create a highly customized transition between multiple colors.
repeating-conic-gradient() - CSS: Cascading Style Sheets
the repeating-conic-gradient() css function creates an image consisting of a repeating gradient (rather than a single gradient) with color transitions rotated around a center point (rather than radiating from the center).
... to create a conic gradient that doe not repeat, make the gradient a full 360 degree rotation, or use the conic-gradient() function instead.
... customizing gradients by adding more angled color-stop points on the gradient arc, you can create a highly customized transition between multiple colors.
...while it is possible to create pie charts, checkerboards, and other effects with conic gradients, css images provide no native way to assign alternative text, and therefore the image represented by the conic gradient will not be accessible to screen reader users.
Using HTML sections and outlines - Developer guides
next up, older ie versions do not allow styling of unsupported elements, unless you create an instance of them in the dom.
... you can add a specific script to allow this, as seen below: <!--[if lt ie 9]> <script> document.createelement("article"); document.createelement("aside"); document.createelement("footer"); document.createelement("header"); document.createelement("nav"); document.createelement("section"); document.createelement("time"); </script> <![endif]--> as a last precaution, you could also add an explicit <noscript> element inside the <head> element to warn any users that have javascript disabled that your page relies on javascript: <noscript> <p><strong>this web page requires javascript to be enabled.</strong></p> <p>javascript is an object-oriented computer programming language commonly used to create interactive effects within web browsers.</p> <p><a href="h...
...ttps://goo.gl/koeeaj">how to enable javascript?</a></p> </noscript> this leads to the following code to allow the support of the html5 sections and headings elements in non-html5 browsers, even for internet explorer (8 and older), with a proper fallback for the case where this latter browser is configured not to use scripting: <!--[if lt ie 9]> <script> document.createelement("article"); document.createelement("aside"); document.createelement("footer"); document.createelement("header"); document.createelement("nav"); document.createelement("section"); document.createelement("time"); </script> <![endif]--> <noscript> <p><strong>this web page requires javascript to be enabled.</strong></p> <p>javascript is an object-oriented computer programming language ...
...commonly used to create interactive effects within web browsers.</p> <p><a href="https://goo.gl/koeeaj">how to enable javascript?</a></p> </noscript> note: this code will also cause the html validator to return errors.
Developer guides
audio and video manipulation the beauty of the web is that you can combine technologies to create new forms.
... javascript javascript is the powerful scripting language used to create applications for the web.
... progressive web apps progressive web apps (pwas) use modern web apis along with traditional progressive enhancement strategy to create cross-platform web applications.
...this guide covers the algorithm in general and how it applies to content you create—especially when you build properly localized and internationalized content.
<a>: The Anchor element - HTML: Hypertext Markup Language
WebHTMLElementa
the html <a> element (or anchor element), with its href attribute, creates a hyperlink to web pages, files, email addresses, locations in the same page, or anything else a url can address.
... linking to an email address to create links that open in the user's email program to let them send a new message, use the mailto: scheme: <a href="mailto:nowhere@mozilla.org">send email to nowhere</a> for details about mailto: urls, such as including a subject or body, see email links or rfc 6068.
... using the download attribute to save a <canvas> as a png to save a <canvas> element’s contents as an image, you can create a link with a download attribute and the canvas data as a data: url: example painting app with save link html <p>paint by holding down the mouse button and moving it.
... spacing may be created using css properties like margin.
Global attributes - HTML: Hypertext Markup Language
it can have the following values: copy, which indicates that dropping will create a copy of the element that was dragged move, which indicates that the element that was dragged will be moved to this new location.
... link, will create a link to the dragged data.
...itemscope creates the item and defines the scope of the itemtype associated with it.
... slot assigns a slot in a shadow dom shadow tree to an element: an element with a slot attribute is assigned to the slot created by the <slot> element whose name attribute's value matches that slot attribute's value.
Evolution of HTTP - HTTP
instead of sending http over a basic tcp/ip stack, netscape communications created an additional encrypted transmission layer on top of it: ssl.
...around 1996, http has been extended to allow authoring, and a standard called webdav was created.
... 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 can no longer be read and created manually.
Using HTTP cookies - HTTP
WebHTTPCookies
note that this ensures that if a subdomain were to create a cookie with a prefix, it would either be confined to the subdomain or be ignored completely.
... javascript access using document.cookie new cookies can be created via javascript using the document.cookie property, and existing cookies can be accessed from javascript as well, if the httponly flag is not set.
... document.cookie = "yummy_cookie=choco"; document.cookie = "tasty_cookie=strawberry"; console.log(document.cookie); // logs "yummy_cookie=choco; tasty_cookie=strawberry" cookies created via javascript cannot include the httponly flag.
... other techniques have been created to cause cookies to be recreated after they are deleted, known as "zombie" cookies.
About JavaScript - JavaScript
objects are created programmatically in javascript, by attaching methods and properties to otherwise empty objects at run time, as opposed to the syntactic class definitions common in compiled languages like c++ and java.
...the first ever javascript was created by brendan eich at netscape, and has since been updated to conform to ecma-262 edition 5 and later versions.
...the rhino engine, created primarily by norris boyd (also at netscape) is a javascript implementation written in java.
...web browsers typically use the public api to create host objects responsible for reflecting the dom into javascript.
JavaScript data types and data structures - JavaScript
a bigint is created by appending n to the end of an integer or by calling the constructor.
...this means that once a string is created, it is not possible to modify it.
... however, it is still possible to create another string based on an operation on the original string.
...all of this requires conventions and creates an unnecessary maintenance burden.
Control flow and error handling - JavaScript
nevertheless, not all thrown objects are created equal.
... while it is common to throw numbers or strings as errors, it is frequently more effective to use one of the exception types specifically created for this purpose: ecmascript exceptions domexception and domerror throw statement use the throw statement to throw an exception.
... // create an object type userexception function userexception(message) { this.message = message; this.name = 'userexception'; } // make the exception convert to a pretty string when used as a string // (e.g., by the error console) userexception.prototype.tostring = function() { return `${this.name}: "${this.message}"`; } // create an instance of the object type and throw it throw new userexception(...
... javascript creates this identifier when the catch block is entered.
Meta programming - JavaScript
handler.has() property query foo in proxy inherited property query foo in object.create(proxy) reflect.has() a property cannot be reported as non-existent, if it exists as a non-configurable own property of target.
... handler.get() property access proxy[foo] proxy.bar inherited property access object.create(proxy)[foo] reflect.get() the value reported for a property must be the same as the value of the corresponding target property if target's property is a non-writable, non-configurable data property.
... handler.set() property assignment proxy[foo] = bar proxy.foo = bar inherited property assignment object.create(proxy)[foo] = bar {jsxref("reflect.set()")}} cannot change the value of a property to be different from the value of the corresponding target property if the corresponding target property is a non-writable, non-configurable data property.
... revocable proxy the proxy.revocable() method is used to create a revocable proxy object.
Text formatting - JavaScript
you can create strings using string literals or string objects.
... string literals you can create simple strings using either single or double quotes: 'foo' "bar" more advanced strings can be created using escape sequences: hexadecimal escape sequences the number after \x is interpreted as a hexadecimal number.
... const foo = new string('foo'); // creates a string object console.log(foo); // displays: [string: 'foo'] typeof foo; // returns 'object' you can call any of the methods of the string object on a string literal value—javascript automatically converts the string literal to a temporary string object, calls the method, then discards the temporary string object.
...for example: const firststring = '2 + 2'; // creates a string literal value const secondstring = new string('2 + 2'); // creates a string object eval(firststring); // returns the number 4 eval(secondstring); // returns the string "2 + 2" a string object has one property, length, that indicates the number of utf-16 code units in the string.
Memory Management - JavaScript
in contrast, javascript automatically allocates memory when objects are created and frees it when they are not used anymore (garbage collection).
... var d = new date(); // allocates a date object var e = document.createelement('div'); // allocates a dom element some methods allocate new values or objects: var s = 'azerty'; var s2 = s.substr(0, 3); // s2 is a new string // since strings are immutable values, // javascript may decide to not allocate memory, // but just store the [0, 3] range.
... example var x = { a: { b: 2 } }; // 2 objects are created.
...in the following example, two objects are created with properties that reference one another, thus creating a cycle.
Classes - JavaScript
constructor the constructor method is a special method for creating and initializing an object created with a class.
...static methods are often used to create utility functions for an application.
... private fields cannot be created later through assigning to them, the way that normal properties can.
... sub classing with extends the extends keyword is used in class declarations or class expressions to create a class as a child of another class.
TypeError: can't assign to property "x" on "y": not an object - JavaScript
the javascript strict mode exception "can't assign to property" occurs when attempting to create a property on primitive value such as a symbol, a string, a number or a boolean.
... message typeerror: can't assign to property "x" on {y}: not an object (firefox) typeerror: cannot create property 'x' on {y} (chrome) error type typeerror.
... in strict_mode, a typeerror is raised when attempting to create a property on primitive value such as a symbol, a string, a number or a boolean.
...foo.bar = {}; // typeerror: can't assign to property "bar" on "my string": not an object fixing the issue either fix the code to prevent the primitive from being used in such places, or fix the issue is to create the object equivalent object.
TypeError: can't redefine non-configurable property "x" - JavaScript
usually, properties in an object created by an object initializer are configurable.
... examples non-configurable properties created by object.defineproperty the object.defineproperty() creates non-configurable properties if you haven't specified them as configurable.
... var obj = object.create({}); object.defineproperty(obj, "foo", {value: "bar"}); object.defineproperty(obj, "foo", {value: "baz"}); // typeerror: can't redefine non-configurable property "foo" you will need to set the "foo" property to configurable, if you intend to redefine it later in the code.
... var obj = object.create({}); object.defineproperty(obj, "foo", {value: "bar", configurable: true}); object.defineproperty(obj, "foo", {value: "baz", configurable: true}); ...
SyntaxError: missing : after property id - JavaScript
the javascript exception "missing : after property id" occurs when objects are created using the object initializer syntax.
... var obj = { propertykey = 'value' }; // syntaxerror: missing : after property id correct would be to use a colon, or to use square brackets to assign a new property after the object has been created already.
... var obj = { propertykey: 'value' }; // or alternatively var obj = { }; obj['propertykey'] = 'value'; empty properties you can't create empty properties like this: var obj = { propertykey; }; // syntaxerror: missing : after property id if you need to define a property without a value, you might use null as a value.
... var obj = { propertykey: null }; computed properties if you create a property key from an expression, you need to use square brackets.
Default parameters - JavaScript
so, unlike (for example) python, a new object is created each time the function is called.
... g = this.value; default: } return [a, b, c, d, e, f, g]; } withdefaults.call({value: '=^_^='}); // [undefined, 5, 5, ":p", {value:"=^_^="}, arguments, "=^_^="] withoutdefaults.call({value: '=^_^='}); // [undefined, 5, 5, ":p", {value:"=^_^="}, arguments, "=^_^="] scope effects if default parameters are defined for one or more parameter, then a second scope (environment record) is created, specifically for the identifiers within the parameter list.
... this scope is a parent of the scope created for the function body.
... function go() { return ':p' } } ...and this function will print undefined because variable var a is hoisted only to the top of the scope created for the function body (and not the parent scope created for the parameter list): function f(a, b = () => console.log(a)) { var a = 1 b() // prints `undefined`, because default parameter values exist in their own scope } parameters without defaults after default parameters parameters are still set left-to-right, overwriting default parameters even if there are later parameters without def...
arguments.callee - JavaScript
1 : factorial(n - 1)*n; }); this has numerous benefits: the function can be called like any other from inside your code it does not create a variable in the outer scope (except for ie 8 and below) it has better performance than accessing the arguments object another feature that was deprecated was arguments.callee.caller, or more specifically function.caller.
...however, an anonymous function (which can be created by a function expression or the function constructor) does not have a name.
... function create() { return function(n) { if (n <= 1) return 1; return n * arguments.callee(n - 1); }; } var result = create()(5); // returns 120 (5 * 4 * 3 * 2 * 1) a use of arguments.callee with no good alternative however, in a case like the following, there are not alternatives to arguments.callee, so its deprecation could be a bug (see bug 725398): function createperson(sidentity) { var ope...
...rson = new function('alert(arguments.callee.identity);'); operson.identity = sidentity; return operson; } var john = createperson('john smith'); john(); specifications specification ecmascript (ecma-262)the definition of 'arguments exotic objects' in that specification.
Array() constructor - JavaScript
the array() constructor is used to create array objects.
...note that this special case only applies to javascript arrays created with the array constructor, not array literals created with the bracket syntax.
... examples array literal notation arrays can be created using the literal notation: let fruits = ['apple', 'banana']; console.log(fruits.length); // 2 console.log(fruits[0]); // "apple" array constructor with a single parameter arrays can be created using a constructor with a single number parameter.
... let fruits = new array(2); console.log(fruits.length); // 2 console.log(fruits[0]); // undefined array constructor with multiple parameters if more than one argument is passed to the constructor, a new array with the given elements is created.
Array.prototype.map() - JavaScript
the map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
...let a be a new array created as if by the expression new array(len) // where array is the standard built-in constructor with that name and // len is the value of len.
...return a return a; }; } examples mapping an array of numbers to an array of square roots the following code takes an array of numbers and creates a new array containing the square roots of the numbers in the first array.
... let numbers = [1, 4, 9] let roots = numbers.map(function(num) { return math.sqrt(num) }) // roots is now [1, 2, 3] // numbers is still [1, 4, 9] using map to reformat objects in an array the following code takes an array of objects and creates a new array containing the newly reformatted objects.
Array.of() - JavaScript
the array.of() method creates a new array instance from a variable number of arguments, regardless of number or type of the arguments.
... the difference between array.of() and the array constructor is in the handling of integer arguments: array.of(7) creates an array with a single element, 7, whereas array(7) creates an empty array with a length property of 7 (note: this implies an array of 7 empty slots, not slots with actual undefined values).
... array.of(7); // [7] array.of(1, 2, 3); // [1, 2, 3] array(7); // array of 7 empty slots array(1, 2, 3); // [1, 2, 3] syntax array.of(element0[, element1[, ...[, elementn]]]) parameters elementn elements used to create the array.
... for more information, see: array.of() array.from() proposal array.of() polyfill polyfill running the following code before any other code will create array.of() if it's not natively available.
AsyncFunction - JavaScript
the asyncfunction constructor creates a new async function object.
... description async function objects created with the asyncfunction constructor are parsed when the function is created.
... all arguments passed to the function are treated as the names of the identifiers of the parameters in the function to be created, in the order in which they are passed.
... note: async functions created with the asyncfunction constructor do not create closures to their creation contexts; they are always created in the global scope.
Error() constructor - JavaScript
the error constructor creates an error object.
... filename optional the value for the filename property on the created error object.
... linenumber optional the value for the linenumber property on the created error object.
...const x = error('i was created using a function call!') ​​​​// ...has the same functionality as this.
GeneratorFunction - JavaScript
the generatorfunction constructor creates a new generator function object.
... description generator function objects created with the generatorfunction constructor are parsed when the function is created.
... all arguments passed to the function are treated as the names of the identifiers of the parameters in the function to be created, in the order in which they are passed.
... note: generator function created with the generatorfunction constructor do not create closures to their creation contexts; they are always created in the global scope.
Intl.RelativeTimeFormat() constructor - JavaScript
the intl.relativetimeformat() constructor creates intl.relativetimeformat objects.
... examples basic format usage the following example shows how to create a relative time formatter using the english language.
... // create a relative time formatter in your locale // with default values explicitly passed in.
... // create a relative time formatter in your locale // with numeric: "auto" option value passed in.
Proxy() constructor - JavaScript
the proxy() constructor is used to create proxy objects.
... description use the proxy() constructor to create a new proxy object.
... this constructor takes two mandatory arguments: target is the object for which you want to create the proxy handler is the object that defines the custom behavior of the proxy.
... an empty handler will create a proxy that behaves, in almost all respects, exactly like the target.
Reflect.construct() - JavaScript
(this would also be possible by using the spread syntax combined with the new operator.) let obj = new foo(...args) let obj = reflect.construct(foo, args) reflect.construct() vs object.create() prior to the introduction of reflect, objects could be constructed using an arbitrary combination of constructor and prototype by using object.create().
... function oneclass() { this.name = 'one' } function otherclass() { this.name = 'other' } // calling this: let obj1 = reflect.construct(oneclass, args, otherclass) // ...has the same result as this: let obj2 = object.create(otherclass.prototype) oneclass.apply(obj2, args) console.log(obj1.name) // 'one' console.log(obj2.name) // 'one' console.log(obj1 instanceof oneclass) // false console.log(obj2 instanceof oneclass) // false console.log(obj1 instanceof otherclass) // true console.log(obj2 instanceof otherclass) // true //another example to demonstrate below: function func1(a, b, c, d) { console.log(arguments[3]); } function func2(d, e, f, g) { consol.log(arguments[3]); } let obj1 = reflect.construct(func1, ['i', 'love', 'my', 'india']) obj1 however, while the end...
...when using object.create() and function.prototype.apply(), the new.target operator will point to undefined within the function used as the constructor, since the new keyword is not being used to create the object.
...} let obj3 = object.create(otherclass.prototype); oneclass.apply(obj3, args) // output: // oneclass // undefined examples using reflect.construct() let d = reflect.construct(date, [1776, 6, 4]) d instanceof date // true d.getfullyear() // 1776 specifications specification ecmascript (ecma-262)the definition of 'reflect.construct' in that specification.
WebAssembly.Table - JavaScript
a table created by javascript or in webassembly code will be accessible and mutable from both javascript and webassembly.
... constructor webassembly.table() creates a new table object.
... examples creating a new webassembly table instance the following example (see table2.html source code and live version) creates a new webassembly table instance with an initial size of 2 elements.
... var tbl = new webassembly.table({initial:2, element:"anyfunc"}); console.log(tbl.length); // "2" console.log(tbl.get(0)); // "null" console.log(tbl.get(1)); // "null" we then create an import object that contains the table: var importobj = { js: { tbl:tbl } }; finally, we load and instantiate a wasm module (table2.wasm) using the webassembly.instantiatestreaming() method.
Property accessors - JavaScript
const variable = object.property_name; object.property_name = value; const object = {}; object.$1 = 'foo'; console.log(object.$1); // 'foo' object.1 = 'bar'; // syntaxerror console.log(object.1); // syntaxerror here, the method named createelement is retrieved from document and is called.
... document.createelement('pre') if you use a method for a numeric literal, and the numeric literal has no exponent and no decimal point, you should leave white-space(s) before the dot preceding the method call, so that the dot is not interpreted as a decimal point.
... document['createelement']('pre') a space before bracket notation is allowed.
... document ['createelement']('pre') property names property names are string or symbol.
Function expression - JavaScript
the main difference between a function expression and a function declaration is the function name, which can be omitted in function expressions to create anonymous functions.
...you can't use function expressions before you create them: console.log(nothoisted) // undefined // even though the variable name is hoisted, the definition isn't.
...nothoisted(); // typeerror: nothoisted is not a function var nothoisted = function() { console.log('bar'); }; named function expression if you want to refer to the current function inside the function body, you need to create a named function expression.
...the function returns the square of its argument: var x = function(y) { return y * y; }; using a function as a callback more commonly it is used as a callback: button.addeventlistener('click', function(event) { console.log('button is clicked!') }) using an immediately executed function expression an anonymous function is created and called: (function() { console.log('code runs!') })(); specifications specification ecmascript (ecma-262)the definition of 'function definitions' in that specification.
Performance fundamentals - Web Performance
(strobe lights are fun because they turn that upside down, starving your brain of inputs to create the illusion of discrete reality).
...an ideal system would maintain 100% of user state at all times: all applications in the system would run simultaneously, and all applications would retain the state created by the user the last time the user interacted with the application (application state is stored in computer memory, which is why the approximation is close).
...this is done by avoiding intermediate surfaces where they would create overhead (such as per-application "back buffers" in many other operating systems), and by using special memory for graphics buffers that can be directly accessed by the compositor hardware.
... if you want to create animations on the fly or modify them in javascript, james long has written a simple library for that called css-animations.js.
How to make PWAs re-engageable using Notifications and Push - Progressive web apps (PWAs)
create a notification the example app creates a notification out of the available data — a game is picked at random, and the chosen one feeds the notification with the content: it sets the game's name as the title, mentioning the author in the body, and showing the image as an icon: function randomnotification() { var randomitem = math.floor(math.random()*games.length); var notiftitle = game...
...s[randomitem].name; var notifbody = 'created by '+games[randomitem].author+'.'; var notifimg = 'data/img/'+games[randomitem].slug+'.jpg'; var options = { body: notifbody, icon: notifimg } var notif = new notification(notiftitle, options); settimeout(randomnotification, 30000); } a new random notification is created every 30 seconds until it becomes too annoying and is disabled by the user.
...inside the service worker, a push service subscription mechanism is created.
...event.data.text() : 'no payload'; event.waituntil( self.registration.shownotification('serviceworker cookbook', { body: payload, }) ); }); all it does is add a listener for the push event, create the payload variable consisting of the text taken from the data (or create a string to use if data is empty), and then wait until the notification is shown to the user.
Structural overview of progressive web apps - Progressive web apps (PWAs)
the file and folder hierarchy looks like this: app.js data/ games.js img/ favicon.ico fonts/ icons/ img/ bg.png js13kgames.png index.html js13kpwa.webmanifest style.css sw.js the html the html in the file index.html creates the structure of the app.
...you can <a href="https://github.com/mdn/pwa-examples/blob/master/js13kpwa"> fork js13kpwa on github</a> to check its source code.</p> <button id="notifications">request dummy notifications</button> <section id="content"> // content inserted in here </section> </main> <footer> <p>© js13kgames 2012-2018, created and maintained by <a href="http://end3r.com"> andrzej mazur</a> from <a href="http://enclavegames.com">enclave games</a>.</p> </footer> </body> </html> the <head> section contains basic information about the app, including its title, description, and the needed references to its css file, web manifest, the main application javascript file (app.js, in which the app is initialized) as wel...
...ck', function(e) { notification.requestpermission().then(function(result) { if (result === 'granted') { randomnotification(); } }); }); the randomnotification() function follows, rounding out the last of the code in the file: function randomnotification() { var randomitem = math.floor(math.random()*games.length); var notiftitle = games[randomitem].name; var notifbody = 'created by '+games[randomitem].author+'.'; var notifimg = 'data/img/'+games[randomitem].slug+'.jpg'; var options = { body: notifbody, icon: notifimg } var notif = new notification(notiftitle, options); settimeout(randomnotification, 30000); } the service worker the last file we'll briefly look at here is the service worker, which is found in the file sw.js.
... this script begins by importing data from the file games.js in the data directory: self.importscripts("data/games.js"); then it creates a list of all the files that the service worker needs to cache.
textLength - SVG: Scalable Vector Graphics
example let's create a simple example that presents text you can resize using an <input> element of type "range".
... </text> </svg> first, a <rect> element is used to create and stroke a rectangle to contain the text.
... then <text> is used to create the text element itself, with an id of "hello".
... html the html is also simple, with only two displayed elements contained inside a grouping <div>: <div class="controls"> <input type="range" id="widthslider" min="80" max="978"> <span id="widthdisplay"></span> </div> the <input> element, of type "range", is used to create the slider control the user will manipulate to change the width of the text.
Tutorials
these resources are created by forward-thinking companies and web developers who have embraced open standards and best practices for web development and that provide or allow translations, through an open content license such as creative commons.
... html tutorials introductory level introduction to html this module sets the stage, getting you used to important concepts and syntax, looking at applying html to text, how to create hyperlinks, and how to use html to structure a webpage.
...you can even create your own objects to encapsulate related functions and variables into efficient packages.
...here we teach object theory and syntax in detail, look at how to create your own objects, and explain what json data is and how to work with it.
WebAssembly Concepts - WebAssembly
what’s more, you don’t even have to know how to create webassembly code to take advantage of it.
... webassembly goals webassembly is being created as an open standard inside the w3c webassembly community group with the following goals: be fast, efficient, and portable — webassembly code can be executed at near-native speed across different platforms by taking advantage of common hardware capabilities.
... the javascript api provides developers with the ability to create modules, memories, tables, and instances.
...emscripten therefore creates the html and javascript glue code needed to achieve this.
Cross-domain Content Scripts - Archive of obsolete content
cross-domain iframes the following "main.js" creates a page-worker which loads a local html file called "page.html", attaches a content script called "page.js" to the page, waits for messages from the script, and logs the payload.
... cross-domain xmlhttprequest the following add-on creates a panel whose content is the summary weather forecast for shetland.
... the "main.js": creates a panel whose content is supplied by "panel.html" and adds a content script "panel-script.js" to it sends the panel a "show" message when it is shown adds a button which shows the panel when it is clicked // main.js var data = require("sdk/self").data; var forecast_panel = require("sdk/panel").panel({ height: 50, contenturl: data.url("panel.html"), contentscriptfile: data.url("panel-script.js") }); forecast_panel.on("show", function(){ forecast_panel.port.emit("show"); }); require("sdk/ui/button/action").actionbutton({ id: "get-forecast", label: "get the forecast", icon: "./icon-16.png", onclick: function() { forecast_panel.show(); } }); the "panel.html" just includes...
hotkeys - Archive of obsolete content
usage to define a hotkey combination, create a hotkey object, passing it the combination and a function to be called when the user presses that combination.
... globals constructors hotkey(options) creates a hotkey whose onpress listener method is invoked when key combination defined by hotkey is pressed.
... if more than one hotkey is created for the same key combination, the listener is executed only on the last one created.
indexed-db - Archive of obsolete content
the database created will be unique and private per add-on, and is not linked to any website database.
...b'); var database = {}; database.onerror = function(e) { console.error(e.value) } function open(version) { var request = indexeddb.open("stuff", version); request.onupgradeneeded = function(e) { var db = e.target.result; e.target.transaction.onerror = database.onerror; if(db.objectstorenames.contains("items")) { db.deleteobjectstore("items"); } var store = db.createobjectstore("items", {keypath: "time"}); }; request.onsuccess = function(e) { database.db = e.target.result; }; request.onerror = database.onerror; }; function additem(name) { var db = database.db; var trans = db.transaction(["items"], "readwrite"); var store = trans.objectstore("items"); var time = new date().gettime(); var request = store.put({ "name": name, ...
... globals properties indexeddb enables you to create, open, and delete databases.
content/symbiont - Archive of obsolete content
you map optionally pass a frame into the symbiont's constructor: if you don't, then a new hidden frame will be created to host the content.
... globals constructors symbiont(options) creates a content symbiont.
...if frame is not provided hidden one will be created.
core/namespace - Archive of obsolete content
let { ns } = require('sdk/core/namespace'); let anamespace = ns(); anamespace(publicapi).secret = secret; one namespace may be used with multiple objects: let { ns } = require('sdk/core/namespace'); let dom = ns(); function view(element) { let view = object.create(view.prototype); dom(view).element = element; // ....
... let sandboxes = ns(); function widget(options) { let { element, contentscript } = options; let widget = object.create(widget.prototype); view.call(widget, options.element); sandboxes(widget).sandbox = cu.sandbox(element.ownerdocument.defaultview); // ...
... } widget.prototype = object.create(view.prototype); widget.prototype.postmessage = function postmessage(message) { let { sandbox } = sandboxes(this); sandbox.postmessage(json.stringify(json.parse(message))); ...
frame/hidden-frame - Archive of obsolete content
experimental creates firefox frames (i.e.
... the following code creates a hidden frame, loads a web page into it, and then logs its title: var hiddenframes = require("sdk/frame/hidden-frame"); let hiddenframe = hiddenframes.add(hiddenframes.hiddenframe({ onready: function() { this.element.contentwindow.location = "http://www.mozilla.org/"; let self = this; this.element.addeventlistener("domcontentloaded", function() { console.log(self.element.co...
... globals constructors hiddenframe(options) creates a hidden frame.
lang/type - Archive of obsolete content
uses typeof operator to check type, and will only properly detect string primitives: for example, a string created with new string() will always return false.
...uses typeof operator to check type, and will only properly detect number primitives: for example, a number created with new number() will always return false.
... } }, { // [object object] // writable configurable enumerable id: 101, // writable configurable enumerable text: "javascript dubstep generator", "__proto__": { // [object object] } } ], "__proto__": { // [object object] } } */ parameters value : mixed the source object to create a textual representation of.
cfx to jpm - Archive of obsolete content
add-on incompatibilities in most respects, add-ons created with cfx will work fine with jpm.
... you can edit this file to create your own id, but if you don't, cfx will generate one for you, which will look something like "jid1-f3boogbjqje67a".
... id handling with jpm when you create an xpi with jpm xpi: if the package.json does not include an id field, then the id written into the install.rdf is the value of the name field prepended with "@".
Adding a Button to the Toolbar - Archive of obsolete content
create a new directory, navigate to it, and execute jpm init, accepting all the defaults.
... create a directory called "data", mkdir data and save these three icon files to the "data" directory: icon-16.png icon-32.png icon-64.png then open the file called "index.js" in the root of your addon directory and add the following code to it: var buttons = require('sdk/ui/button/action'); var tabs = require("sdk/tabs"); var button = buttons.actionbutton({ id: "mozilla-link", label: "visit mozilla", icon: { "16": "./icon-16.png", "32": "./icon-32.png", "64": "./icon-64.png" }, onclick: handleclick }); function handleclick(state) { tabs.open("https://www.mozilla.org/"); } now run the add-on with jpm run.
... displaying richer content to create more complex user interface content than is possible with just a button, use the toolbar api.
Displaying annotations - Archive of obsolete content
matcher page-mod matcher content script the content script for the matcher page-mod is initialized with a list of all the annotations that the user has created.
... the complete content script is here: self.on('message', function onmessage(annotations) { annotations.foreach( function(annotation) { if(annotation.url == document.location.tostring()) { createanchor(annotation); } }); $('.annotated').css('border', 'solid 3px yellow'); $('.annotated').bind('mouseenter', function(event) { self.port.emit('show', $(this).attr('annotation')); event.stoppropagation(); event.preventdefault(); }); $('.annotated').bind('mouseleave', function() { self.port.emit('hide'); }); }); function createanchor(annotation) { annotatio...
... updating main.js first, initialize an array to hold workers associated with the matcher's content scripts: var matchers = []; in the main function, add the code to create the matcher: var matcher = pagemod.pagemod({ include: ['*'], contentscriptwhen: 'ready', contentscriptfile: [data.url('jquery-1.4.2.min.js'), data.url('matcher.js')], onattach: function(worker) { if(simplestorage.storage.annotations) { worker.postmessage(simplestorage.storage.annotations); } worker.port.on('show', function(data) { annotation.
Display a Popup - Archive of obsolete content
in this tutorial we'll create an add-on that adds an action button to the toolbar that displays a panel when clicked.
... the add-on consists of seven files: package.json: created when you run jpm init index.js: the main add-on code, that creates the button and panel get-text.js: the content script that interacts with the panel content text-entry.html: the panel content itself, specified as html icon-16.png, icon-32.png, and icon-64.png: icons for the button in three different sizes the "index.js" looks like this: var data = require("sdk/self").data; // construct a panel, loading its content from the "text-entry.html" // file in the "data" directory, and loading the "get-text.js" script // into it.
... var text_entry = require("sdk/panel").panel({ contenturl: data.url("text-entry.html"), contentscriptfile: data.url("get-text.js") }); // create a button require("sdk/ui/button/action").actionbutton({ id: "show-panel", label: "show panel", icon: { "16": "./icon-16.png", "32": "./icon-32.png", "64": "./icon-64.png" }, onclick: handleclick }); // show the panel when the user clicks the button.
Tutorials - Archive of obsolete content
create user interfaces add a toolbar button attach a button to the firefox add-on toolbar.
... modify web pages modify web pages based on url create filters for web pages based on their url: whenever a web page whose url matches the filter is loaded, execute a specified script in it.
...create reusable packages containing your modules, so other add-on developers can use them too.
Post data to window - Archive of obsolete content
preprocessing post data the apostdata argument of the (global) loaduri(), opendialog(), and (tab)browser.loaduriwithflags() methods expects the post data in the form of an nsiinputstream (because they eventually call nsiwebnavigation.loaduri()) while post data can be created using nsimimeinputstream.
... createinstance(ci.nsistringinputstream); if ("data" in stringstream) // gecko 1.9 or newer stringstream.data = datastring; else // 1.8 or older stringstream.setdata(datastring, datastring.length); var postdata = cc["@mozilla.org/network/mime-input-stream;1"].
... createinstance(ci.nsimimeinputstream); postdata.addheader("content-type", "application/x-www-form-urlencoded"); postdata.addcontentlength = true; postdata.setdata(stringstream); // postdata is ready to be used as apostdata argument ...
Preferences - Archive of obsolete content
example: // prefs is an nsiprefbranch // example 1: getting unicode value var value = prefs.getcomplexvalue("preference.with.non.ascii.value", components.interfaces.nsisupportsstring).data; // example 2: setting unicode value var str = components.classes["@mozilla.org/supports-string;1"] .createinstance(components.interfaces.nsisupportsstring); str.data = "some non-ascii text"; prefs.setcomplexvalue("preference.with.non.ascii.value", components.interfaces.nsisupportsstring, str); nsipreflocalizedstring another complex type supported by mozilla is nsipreflocalizedstring.
... setting nsipreflocalizedstring preferences is similar to setting nsisupportsstring: var pls = components.classes["@mozilla.org/pref-localizedstring;1"] .createinstance(components.interfaces.nsipreflocalizedstring); pls.data = val; prefs.setcomplexvalue("preference.with.non.ascii.value", components.interfaces.nsipreflocalizedstring, pls); nsilocalfile and nsirelativefilepref please see the file io article for details on nsilocalfile and nsirelativefilepref.
...ferences api a brief guide to mozilla preferences — describes preferences system from user's/administrator's pov mozilla xpcom interfaces of the preferences system most used interfaces (these are frozen and will not change): nsiprefbranch and nsiprefservice nsiprefbranch2 interface (before gecko 1.8 it was called nsiprefbranchinternal) preferences system - an easy way to create a xul options window for your extension or application syncing preferences across clients using sync lxr pages for libpref, the source code module that implements the preferences system a javascript wrapper for preferences api adding preferences to an extension — a simple tutorial with a working extension that illustrates the use of preference observers inline options - how to use the new ...
Common Pitfalls - Archive of obsolete content
it's important to create the uri correctly, and then check that it's secure to load.
... how to create a uri object in almost all cases, when creating a uri object you want to use the newuri method on the nsiioservice interface, like so: javascript: try { var ioserv = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); var uriobj = ioserv.newuri(uristring, uricharset, baseuri); } catch (e) { // may want to catch ns_error_malformed_uri for some applications } c++: nsresult rv; nscomptr<nsiioservice> ioserv = do_getservice("@mozilla.org/network/io-service;1"); ns_ensure_success(rv, rv); nscomptr<nsiuri> uriobj; rv = ioserv->newuri(uristring, uricharset, baseuri, getter_addref...
...the one exception to all of the above, that is the one case in which creating a specific uri class via createinstance is acceptable, is when one is implementing a protocol handler's newuri method.
Extension Versioning, Update and Compatibility - Archive of obsolete content
simply create the boolean preference extensions.checkcompatibility and set it to false.
... the technical details of the signing mechanism are beyond the scope of this document however the basics are as follows: step 1 - done once, before you publish your add-on the target: adding updatekey in install.rdf the add-on author creates a public/private rsa cryptographic key pair.
... step 2 - done every time you change your "update.rdf" file the target: setting value to signature in update.rdf when the author creates the update rdf file a tool is used to sign it using the private part of the key.
Listening to events in Firefox extensions - Archive of obsolete content
first it creates a browser-status-filter and adds it as a web progress listener for the browser.
... next it creates an internal object to receive all web progress events from the browser.
... this is created by the method mtabprogresslistener().
Migrating raw components to add-ons - Archive of obsolete content
simple migration if your goal is just to get your raw component working properly as an extension, you can do this in three steps: create a new add-on using the instructions here.
...create a components/ directory in the root of your add-on's directory.
...javascript c-types some add-on authors create binary components not because they want to interact with firefox at the c++ level, but strictly so that they can make use of third party dlls.
Chapter 1: Introduction to Extensions - Archive of obsolete content
but we didn't set out to create an all-in-one browser that can satisfy everyone.
... this lowers the threshold both to using and to developing extensions; that fact, combined with firefox's rapidly growing popularity, has created a positive feedback loop, with the number of extension users and extension developers growing explosively—there are now more than 7000 extensions and themes published at the firefox add-ons site (https://addons.mozilla.org).
... in order to create an extension, you need an idea and just a little programming ability.
Chapter 3: Introduction to XUL—How to build a more intuitive UI - Archive of obsolete content
insert menu elements into a menubar element to create multiple menus.
... you can easily create hierarchical menus by inserting menupopup and menu elements.
... menu list use the menulist element to create a control for making selections from a drop-down list.
Chapter 2: Technologies used in developing extensions - Archive of obsolete content
listing 2: css code sample body { color: black; background-color: white; } p { margin-bottom: 1em; text-indent: 1em; } javascript: the world's most misunderstood language javascript is a scripting language first developed in the 1990s, at which time it was created as a way to add dynamic features to web pages.
... nevertheless, the rise of web services like google maps, which used javascript and asynchronous communications, created an awareness of a set of technologies nicknamed ajax (asynchronous javascript and xml); that plus the advent of a number of libraries that paper over implementation differences between different web browsers has more recently led to a re-evaluation of javascript as a programming language.
... listing 4: an example manipulation using the dom var bar = document.getelementbyid('toolbar'); bar.removechild(bar.childnodes[1]); bar.appendchild(document.createelement('button')); bar.lastchild.setattribute('label', 'hello!'); « previousnext » ...
Adding windows and dialogs - Archive of obsolete content
common dialogs and the prompt service there are several types of dialogs that are fairly common, so there are ways to create them easily without having to reinvent the wheel and write all their xul and js code all over again.
... using the prompt service is the recommended way to create common dialogs in an extension.
... the dialog element when the prompt service is not enough, you'll have to create you own xul dialogs.
Appendix C: Avoiding using eval in Add-ons - Archive of obsolete content
alternative: use (anonymous) functions you can always create a small anonymous function to pass around instead.
...mptions might not longer be true, for example the function signature may change (auri from above becomes aurl) or the function is replaced by a short-hand/arrow function: function addtab(auri) tabbrowser.addtab(auri); var addtab = (auri) => tabbrowser.addtab(auri); same as with "passing functions/code as strings" above, patching a function to with fragments of externally retrieved data will create security vulnerabilities.
... // fake a command event var event = document.createevent("events"); event.initevent("command", true, true); document.getelementbyid("mymenu").dispatchevent(event); // fake a mouse click var mouseevent = document.createevent("mouseevents"); event.initmouseevent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); document.getelementbyid("mylabel").dispatchevent(mouseevent); please see the corresponding documentation ...
Appendix F: Monitoring DOM changes - Archive of obsolete content
for instance, rather than watching for the creation of <a> elements and adding event listeners to them as they are created, an event listener can be added to the root <html> element, and when the event fires, the event.target and its parents can be searched for a matching element.
... */ if ('mozcsskeyframerule' in window || 'csskeyframerule' in window) { var watchnodes = function watchnodes(selector, callback, doc) { const event = watchnodes.prefix + (watchnodes._i++); const xhtml = 'http://www.w3.org/1999/xhtml'; doc = doc || document; let style = doc.createelementns(xhtml, 'style'); style.setattribute('type', 'text/css'); let preamble = ' @-moz-keyframes ' + event + ' { \n\ from { clip: rect(1px, auto, auto, auto); } to { clip: rect(0px, auto, auto, auto); } \n\ }\n'; let properties = [ 'animation-duration: 0.0001s;', 'animation-name: ' + event + ' !important;' ]; ...
...bindings are attached to dom nodes via css and are given the opportunity to run code via their constructors when new matching dom nodes are created.
Getting Started with Firefox Extensions - Archive of obsolete content
these are very advanced and complex extensions, and you'll learn most of what it takes to create extensions like these.
...if you're only getting started developing add-ons, the add-ons sdk provides a great way to quickly create simple ones and build on them.
... this tutorial focuses on traditional extensions, which are created differently.
The Essentials of an Extension - Archive of obsolete content
for example, if you create a firefox extension, it would normally take little effort to port it to seamonkey, which has very similar features and ui.
...this division allows other developers to create themes that replace skins, and translators to create localizations in different languages, all of this without having to change your extension or your code.
...xul allows you to create richer and more interactive interfaces than the ones you can create with html, or at least xul makes it easier.
Performance best practices in extensions - Archive of obsolete content
use javascript code modules you can create your own javascript code modules incorporating sets of features that are only needed under specific circumstances.
... lazily load services the xpcomutils javascript module provides two methods for lazily loading things: definelazygetter() defines a function on a specified object that acts as a getter which will be created the first time it's used.
...these events happen with high frequency, so their listeners can trivially create very high cpu overhead.
Creating a status bar extension - Archive of obsolete content
next » this is the first in a series of articles that will demonstrate how to create increasingly intricate extensions for the firefox browser.
... note: the extension created by this tutorial won't work in firefox that don't have a static status bar (that is, firefox 4 and up).
...although this sample extension only works in firefox, it's entirely possible to create extensions that work in multiple xul-based applications.
MMgc - Archive of obsolete content
strings are created very frequently, and are often temporary objects with very short lifetimes.
...finalizers may not perform any of the following actions: fire any write barriers dereference a pointer to any gc object, including member variables (except see below about rcobject references) allocate any gc memory (gc::alloc), explicitly free gc memory (gc::free) change the set of gc roots (create a gcroot object or derivative) cause itself to become reachable if a finalized object holds a reference to an rcobject, it may safely call decrementref on the rcobject.
... threading the gc routines are not currently thread safe, we're operating under the assumption that none of the player spawned threads create gc'd things.
Source Navigator - Archive of obsolete content
this triggers a splash screen, followed by a "source-navigator projects" dialog as the following: i've already created a new project bin.proj before documenting this.
...this shows the "auto-create project" dialog: which allows you to decide your filename of the project file (which ends in .proj) and your source directory/directories that you want to import into the project.
...choose the project file that you've just created and then click "open...".
Automated testing tips and tricks - Archive of obsolete content
window does not quit the application on mac http://people.mozilla.com/~davel/scripts/ - look at quit.js and quit.xul install manifest file in appdir/chrome to map chrome://tests/content to directory containing quit.js and quit.xul example: content tests file:///users/davel/work/tests/ start app with command line flag -chrome chrome://tests/content/quit.xul how to create a new profile from the command line first, use the -createprofile command line flag to add a profile entry to profiles.ini and populate the new profile directory with a prefs.js file firefox-bin -createprofile "testprofile ${profile_dir}/testprofile" next, start firefox to populate the new profile directory with the rest of the default settings firefox-bin -p...
... testprofile -chrome chrome://tests/content/quit.xul<code> the above process may exit before the profile is completely created.
... in test scripts, <code>sleep 5 after the above command should ensure the profile is created before the next command in the test script is run how to enable dump in a new profile add user_pref("browser.dom.window.dump.enabled", true); to profiledir/user.js how to execute test code with chrome privileges using a chrome doc - see sbtests.xul in http://people.mozilla.com/~davel/scripts/ for an example firefox-bin -p sbtestprofile -chrome chrome://sbtests/content/ above code calls the quit function in quit.js to exit after test is finished how to detect content onload event from chrome use the domcontentloaded event chromewindow.addeventlistener('domcontentloaded',callbackfunction,false); ...
Getting Started - Archive of obsolete content
so create a new directory called my_theme.
... create a directory called chrome inside it.
...more after i get done with some tests repackaging jar now all you need to do is repackage a jar file with the following directory structure, using your favorite archive manager to create a zip archive: /chrome/my_theme.jar!/communicator/* /chrome/my_theme.jar!/editor/* /chrome/my_theme.jar!/global/* /chrome/my_theme.jar!/help/* /chrome/my_theme.jar!/messenger/* /chrome/my_theme.jar!/messenger-newsblog/* /chrome/my_theme.jar!/mozapps/* /chrome/my_theme.jar!/navigator/* /chrome.manifest /install.rdf /icon.png /preview.png make sure not to just zip up the my_theme parent director...
Getting Started - Archive of obsolete content
this is what we're going to create now.
... take a screenshot of mozilla running your theme and create an image that is 438x89 pixels in size.
...once the zip is created, rename it to myskin.jar contents of myskin.jar contents.rdf preview.png \navigator\...
Repackaging Firefox - Archive of obsolete content
we call this extension a "distro extension" (sometimes abbreviated as "dex"), because it is used to create a new "distribution" of firefox, with different branding, etc.
... the reason is that if you create and ship a dex that supports 2 locales (for example), and later decide to ship on a 3rd locale, you will need to re-create the dex to support it.
... on the other hand, if you create a dex which supports all locales, you can only ship on a few, and later expand your set without any upgrade hassles.
Mozilla Crypto FAQ - Archive of obsolete content
if you create and distribute modifications to the original psm and nss code, we ask that you in turn make such modifications available under both the mpl and gpl.
...based on statements made in various internet forums it appears that the developers of gnu privacy guard may create a plugin module to support invocation of gnupg functionality from mozilla; network associates may also create a commercial pgp plugin for mozilla.
...("cfr" stands for "code of federal regulations.") the export administration regulations were created by the bureau of export administration (bxa) and were designed primarily to implement the requirements of the export administration act of 1979 (as amended), also known as 50 usc appendices 2401-2420.
Build - Archive of obsolete content
change directory into mozilla/ and checkout the latest prism code : cd mozilla/ svn co http://svn.mozilla.org/projects/webrunner/trunk prism create a file called .mozconfig make sure it is in the mozilla/ directory.
...go into the prism/ directory and create a .mozconfig file mk_add_options moz_objdir=@topsrcdir@/mozilla-obj/prism ac_add_options --with-libxul-sdk=../dist ac_add_options --enable-application=prism you need to define an environment variable to point the build to the new .mozconfig.
...if you want to create a package, go to mozilla-obj/prism and call make package you will find the package in dist/ ...
Using Breakpoints in Venkman - Archive of obsolete content
once you've created a script that will be executed when the associated breakpoint is hit, you can select a number of different options from the future breakpoint properties dialog that determine how venkman will deal with the output of the associated script.
...when you add a meta comment, a normal breakpoint is created.
... you can change or delete this breakpoint just as you would a breakpoint created by hand.
Writing textual data - Archive of obsolete content
writing to a stream in gecko 1.8 (seamonkey 1.0, firefox 1.5), you can use nsiconverteroutputstream: var charset = "utf-8"; // can be any character encoding name that mozilla supports var os = components.classes["@mozilla.org/intl/converter-output-stream;1"] .createinstance(components.interfaces.nsiconverteroutputstream); // this assumes that fos is the nsioutputstream you want to write to os.init(fos, charset, 0, 0x0000); os.writestring("umlaute: \u00fc \u00e4\n"); os.writestring("hebrew: \u05d0 \u05d1\n"); // etc.
... here's an example: // first, get and initialize the converter var converter = components.classes["@mozilla.org/intl/scriptableunicodeconverter"] .createinstance(components.interfaces.nsiscriptableunicodeconverter); converter.charset = /* the character encoding you want, using utf-8 for this example */ "utf-8"; now you can convert and write to the stream: // this code assumes that os is your nsioutputstream // your_string here is the string you want to write.
... nsiscriptableunicodeconverter has a simple method to do that: // first, get and initialize the converter var converter = components.classes["@mozilla.org/intl/scriptableunicodeconverter"] .createinstance(components.interfaces.nsiscriptableunicodeconverter); converter.charset = /* the charset you want to use.
Windows Install - Archive of obsolete content
winreg.setrootkey(winreg.hkey_current_user) ;// current_user subkey = "software\\microsoft\\windows\\currentversion\\runonce" ; winreg.createkey(subkey,""); valname = "ren8dot3"; value = fprogram + "ren8dot3.exe " + ftemp + "ren8dot3.ini"; err = winreg.setvaluestring(subkey, valname, value); } } function prepareren8dot3(listlongfilepaths) { var ftemp = getfolder("temporary"); var fprogram = getfolder("program"); var fren8dot3ini = getwinprofile(ftemp, "ren8dot3.ini"); var binicreated = false; va...
...r flongfilepath; var sshortfilepath; if(fren8dot3ini != null) { for(i = 0; i < listlongfilepaths.length; i++) { flongfilepath = getfolder(fprogram, listlongfilepaths[i]); sshortfilepath = file.windowsgetshortname(flongfilepath); if(sshortfilepath) { fren8dot3ini.writestring("rename", sshortfilepath, flongfilepath); binicreated = true; } } if(binicreated) updatewinreg4ren8dot3() ; } return(0); } // main var srdest; var err; var fprogram; srdest = 449; err = initinstall(prettyname, regname, "6.0.0.2000110801"); logcomment("initinstall: " + err); fprogram = getfolder("program"); logcomment("fprogram: " + fprogram); if(verifydiskspace(fprogram, srdest)) { setpackagefolder(fprogram); err = adddirect...
...ory("", "6.0.0.2000110801", "bin", // dir name in jar to extract fprogram, // where to put this file // (returned from getfolder) "", // subdir name to create relative to fprogram true); // force flag logcomment("adddirectory() returned: " + err); // check return value if(err == success) { err = performinstall(); logcomment("performinstall() returned: " + err); } else cancelinstall(err); } else cancelinstall(insufficient_disk_space); // end main ...
windowsShortcut - Archive of obsolete content
summary creates a windows shortcut to the installed software.
... object syntax int windowsshortcut( folderobject atarget, folderobject ashortcutpath, string adescription, folderobject aworkingpath, string aparams, folderobject aicon, number aiconid); parameters the windowsshortcut method has the following parameters: atarget a filespecobject representing the absolute path (including filename) to file that the shortcut will be created for.
... ashortcutpath a filespecobject representing the absolute path (not including filename) to where the shortcut is to be created.
Methods - Archive of obsolete content
methods dircreate creates a new directory.
... windowsshortcut creates a windows shortcut for a file.
... macalias creates a macintosh alias for a file.
getWinProfile - Archive of obsolete content
you create this object by passing a string representing the directory to the getfolder method.
...description the getwinprofile method creates an object for manipulating the contents of a windows .ini file.
...example to edit the win.ini file, you would create a winprofile object with this call: var mywinprofileobj = getwinprofile (getfolder("windows"), "win.ini"); ...
Installer Script - Archive of obsolete content
// create the plugins folder next to mozilla 34.
... var ignoreerr = dircreate(pluginsfolder); 38.
... logcomment("dircreate() returned: " + ignoreerr); 39.
XPJS Components Proposal - Archive of obsolete content
so, at some future point some chunk of code will ask the component manager to create an object instance for some clsid (or progid).
...the component manager (and anyone else with a reference to that factory) can then call the factory's createinstance method at will.
...in c if a module gets unloaded when there are still references to objects created by the module then a crash is likely to happen soon after.
button.type - Archive of obsolete content
if this attribute is not present, a normal button is created.
... menu set the type attribute to the value menu to create a button with a menu popup.
... menu-button you can also use the value menu-button to create a button with a menu.
insertItemAt - Archive of obsolete content
« xul reference home insertitemat( index, label, value ) return type: element this method creates a new item and inserts it at the specified position.
... note: you cannot insert an item to an index that does not exist, eg: trying to insert an item at the end with element.getrowcount() + 1 example <!-- this example inserts at the selected item or appends, then selects the newly created item --> <script language="javascript"> function insertitemtolist(){ var mylistbox = document.getelementbyid('mylistbox'); // create a date to get some labels and values var somedate = new date(); if(mylistbox.selectedindex == -1){ // no item was selected in list so append to the end mylistbox.appenditem( somedate.tolocaletimestring(), somedate.gettime() ); var newindex = mylistbox.getrowcount() -1 }else{ // item was selected so insert a...
...t the selected item var newindex = mylistbox.selectedindex; mylistbox.insertitemat(newindex, somedate.tolocaletimestring(), somedate.gettime()); } // select the newly created item mylistbox.selectedindex = newindex; } </script> <button label="insert item at selected" oncommand="insertitemtolist()"/> <listbox id="mylistbox"> <listitem label="foo"/> </listbox> see also appenditem() removeitemat() ...
Floating Panels - Archive of obsolete content
a floating panel can be created using the panel element with at least two additional attributes as in the following example: <panel id="tools-panel" noautohide="true" titlebar="normal"> <label control="name" value="name:"/> <textbox id="name"/> </panel> the noautohide attribute is used to indicate that the panel is not temporary.
...the titlebar attribute creates a panel with a titlebar.
... currently, only the value normal is supported, which creates a default titlebar.
MenuItems - Archive of obsolete content
a shortcut key can be created using the key element.
... this type of menuitem can be created by using the type attribute and setting it to the value "checkbox".
... to create a menuitem that acts like a radio button, set the type attribute to "radio".
Actions - Archive of obsolete content
in this case, a button will be created for each result.
... there are three results, so three buttons will be created.
...the toolbar is created just before the content for the first result is generated.
Filtering - Archive of obsolete content
function applyfilter(country) { var cond = document.getelementbyid("cond"); var triple = document.getelementbyid("filtertriple"); if (country) { if (!triple) { triple = document.createelement("triple"); triple.id = "filtertriple"; triple.setattribute("subject", "?photo"); triple.setattribute("predicate", "http://www.xulplanet.com/rdf/country"); } triple.setattribute("object", country); cond.appendchild(triple); } else if (triple) { cond.removechild(triple); } document.getelementbyid("photoslist").builder.rebuild(); } the 'country' arg...
...a new <triple> element is created and the object attribute is set to the value to filter by.
...the syntax is the same regardless of what type of content is being created.
RDF Modifications - Archive of obsolete content
or, you might think that it creates a fresh datasource with the new data.
...now, the potential result so far is: (?photo = http://www.xulplanet.com/ndeakin/images/t/obelisk.jpg, ?description = 'one of the thirty or so egyptian obelisks', ?start = http://www.xulplanet.com/rdf/myphotos, ?title = 'obelisk') as you can see, the result looks to have all the information necessary to create a new item in the output.
... rdf changes that affect a binding often, a new rdf triple is created in the datasource which would only affect a template rule's bindings.
Recursive Generation - Archive of obsolete content
this extra arrow which neither b or d have causes an extra set of buttons to be created.
...however, for item c, the triple does match an item, so the data will be added to the potential result: (?start = http://www.xulplanet.com/rdf/c, ?relateditem = http://www.xulplanet.com/rdf/d) a match has occured, so the content within the action body will be created and added inside item c.
... since the ?start variable points to item c and the ?relateditem variable points to d, the buttons will be created with these labels.
Tree Widget Changes - Archive of obsolete content
the column objects are created automatically, so you don't have to write any extra code.
...you can create a checkbox column by setting the type attribute of a column to checkbox.
... treechildren::-moz-tree-cell-text { cursor: pointer; } this allows you to create separate cursors for cells.
Adding Event Handlers - Archive of obsolete content
we haven't cleaned it up much but we have created a simple user interface easily.
... <script src="findfile.js"/> we'll create the script file later when we know what we want to put in it.
...when an action occurs that would trigger an event, such as the user moving the mouse, an event object is created corresponding to that event type.
Cross Package Overlays - Archive of obsolete content
once you have created an overlay, you can add it to the contents.rdf file.
... our find files example first, let's create a simple overlay.
...the following example shows how: <rdf:seq about="urn:mozilla:stylesheets"> <rdf:li resource="chrome://messenger/content/messenger.xul"/> </rdf:seq> <rdf:seq about="chrome://messenger/content/messenger.xul"> <rdf:li>chrome://blueswayedshoes/skin/myskinfile.css</rdf:li> </rdf:seq> next, we'll see how to create an installer for a xul application.
Custom Tree Views - Archive of obsolete content
to implement a custom view, you will need to create an object which implements the nsitreeview interface.
... you can create these objects in javascript, but you will need a separate object for each tree.
...the following example shows this: <tree id="my-tree" flex="1"> <treecols> <treecol id="namecol" label="name" flex="1"/> <treecol id="datecol" label="date" flex="1"/> </treecols> <treechildren/> </tree> to assign data to be displayed in the tree, the view object needs to be created which is used to indicate the value of each cell, the total number of rows plus other optional information.
Element Positioning - Archive of obsolete content
by setting either of the two properties, the element will be created with that width and height.
...because the box is larger, more extra space will be created inside it, and the flexible button inside it will grow to fit the available space.
... cropping text and buttons you could potentially create a button element that contains a label that is larger than the maximum width of the button.
Introduction to XBL - Archive of obsolete content
you can also create new skins by changing the styles.
... binding example the box is generic enough that you can use it to create custom widgets (although you can use any element, even one you make up yourself).
... -moz-binding: url('chrome://example/skin/example.xml#okcancel'); } xbl (example.xml): <?xml version="1.0"?> <bindings xmlns="http://www.mozilla.org/xbl" xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <binding id="okcancel"> <content> <xul:button label="ok"/> <xul:button label="cancel"/> </content> </binding> </bindings> this example creates a window with a single box.
Open and Save Dialogs - Archive of obsolete content
creating a file picker to begin, you need to create a file picker component and initialize it.
... var nsifilepicker = components.interfaces.nsifilepicker; var fp = components.classes["@mozilla.org/filepicker;1"].createinstance(nsifilepicker); fp.init(window, "select a file", nsifilepicker.modeopen); first, a new file picker object is created and stored in the variable 'fp'.
... var res = fp.show(); if (res != nsifilepicker.returncancel){ var thefile = fp.file; // --- do something with the file here --- } next, we'll see how to create a wizard.
Scrolling Menus - Archive of obsolete content
creating a large menu you might wonder what happens if you create a menu with a lot of commands on it, such that all the items won't fit on the screen at once.
...this element can be used to create a scrolling box with arrows.
...example - scrolling list of buttons the following example shows how to create a scrolling list of buttons (you will need to resize the window to see the arrow buttons): example 1 : source view <arrowscrollbox orient="vertical" flex="1"> <button label="red"/> <button label="blue"/> <button label="green"/> <button label="yellow"/> <button label="orange"/> <button label="silver"/> <button label="lavender"/> <button label="gold"/> <button label="turquoise"/> <button label="peach"/> <button label="maroon"/> <button label="black"/> ...
Styling a Tree - Archive of obsolete content
you can create a progressmeter column by setting the type attribute on the column to progressmeter.
...we create them using the xpcom interface nsiatomservice and add them to the array using the appendelement() function.
... here, we create an atom 'makeitblue'.
The Box Model - Archive of obsolete content
box elements the basic syntax of a box is as follows: <hbox> <!-- horizontal elements --> </hbox> <vbox> <!-- vertical elements --> </vbox> the hbox element is used to create a horizontally oriented box.
...the vbox element is used to create a vertically oriented box.
...you can set this attribute to the value horizontal to create a horizontal box and vertical to create a vertical box.
Using Spacers - Archive of obsolete content
« previousnext » in this section, we will find out how to add some spacing in between the elements we have created.
...as we'll see, you can use a series of spacers to create a number of layout effects.
...if you create a button with a very long label, the button's default size will be large enough to hold the entire label.
XPCOM Examples - Archive of obsolete content
this allows you to create a window menu with a list of the currently open windows in the application.
...g example: example 1 : source <toolbox> <menubar id="windowlist-menubar"> <menu label="window"> <menupopup id="window-menu" datasources="rdf:window-mediator" ref="nc:windowmediatorroot"> <template> <rule> <menuitem uri="rdf:*" label="rdf:http://home.netscape.com/nc-rdf#name"/> </rule> </template> </menupopup> </menu> </menubar> </toolbox> a window menu will be created with a list of all the open windows.
... code snippets http://kb.mozillazine.org/category:xpcom_example_code next, we'll look at how to create trees.
Using Remote XUL - Archive of obsolete content
after completing the tutorial you should understand how to: create xul documents; serve them from a web server; use cascading style sheets (css) to change their appearance; use javascript to define their behavior.
... <?php header('content-type: application/vnd.mozilla.xul+xml'); ?> <!-- xul markup starts here --> note that you don't need a web server for this tutorial; you can load the document you create on your computer via a "file" url or the "open file" function of your browser.
... step 1: a basic xul document the first thing we need to do is create a basic xul document.
XUL Changes for Firefox 1.5 - Archive of obsolete content
<scrollcorner> a <scrollcorner> element is added which is used to create the small box in the intersection of the horizontal and vertical scrollbars.
...the <richlistbox> supports much of the same api as the <listbox> and single items, created with the <richlistitem> element may be selected.
...for instance <button icon="help"> will create a button with a help icon.
menulist - Archive of obsolete content
to create the drop-down, put a menupopup inside the menulist containing the choices as menuitem elements.
..., isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata appenditem( label, value, description ) return type: element creates a new menuitem element and adds it to the end of the menulist.
... insertitemat( index, label, value ) return type: element this method creates a new item and inserts it at the specified position.
radiogroup - Archive of obsolete content
ualnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata appenditem( label, value ) return type: element creates a new item and adds it to the end of the existing list of items.
...the function returns the newly created element.
... insertitemat( index, label, value ) return type: element this method creates a new item and inserts it at the specified position.
tabs - Archive of obsolete content
ArchiveMozillaXULtabs
appenditem( label, value ) return type: element creates a new item and adds it to the end of the existing list of items.
...the function returns the newly created element.
... insertitemat( index, label, value ) return type: element this method creates a new item and inserts it at the specified position.
titlebar - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] boxes created with the titlebar element behave just like a normal window titlebar: when the element is clicked and dragged, the window moves with it.
... this element can't be used to change the platform-native titlebar of normal windows; instead, it's used to create custom titlebars for chromeless windows.
... examples this xul file will create a hud-style window that can be moved with the mouse.
tree - Archive of obsolete content
ArchiveMozillaXULtree
dom treeitems are not created.
... even though the template uses treeitem elements to define the content, dom nodes for these elements are not created.
...dom treeitems are created, so you can access the data using rdf functions or dom functions.
CommandLine - Archive of obsolete content
however, if you'd like to retrieve the latest command line arguments (to open a file for example), a possible solution is to create your own command line handler.
...ndlinehandler */ handle : function clh_handle(acmdline) { var observerservice = components.classes["@mozilla.org/observer-service;1"] .getservice(components.interfaces.nsiobserverservice); observerservice.notifyobservers(acmdline, "commandline-args-changed", null); }, helpinfo : " -test <value> a test attribute\n", /* nsifactory */ createinstance : function mdh_ci(aouter, aiid) { if (aouter != null) { throw components.results.ns_error_no_aggregation; } return this.queryinterface(aiid); }, lockfactory : function mdh_lock(alock) { /* no-op */ } }; var apphandlermodule = { /* nsisupports */ queryinterface : function mod_qi(aiid) { if (aiid.equals(nsimodule) || aiid.equals(nsisuppor...
...ompreg.unregisterfactorylocation(class_id, alocation); var catman = components.classes["@mozilla.org/categorymanager;1"] .getservice(nsicategorymanager); catman.deletecategoryentry("command-line-handler", cld_category); }, canunload : function (acompmgr) { return true; } }; function nsgetmodule(acompmgr, afilespec) { return apphandlermodule; } create an observer that will get notified when arguments change: chrome/content/cmdline.js function commandlineobserver() { this.register(); } commandlineobserver.prototype = { observe: function(asubject, atopic, adata) { var cmdline = asubject.queryinterface(components.interfaces.nsicommandline); var test = cmdline.handleflagwithparam("test", false); alert("test = " + test); }, ...
Debugging a XULRunner Application - Archive of obsolete content
to output dump calls instead to a file, set browser.dom.window.dump.file to the file destination where the log should be created and restart the application.
...eractors("myxulrunnerappwindowtype"); } debuggerserver.openlistener(6000); for xulrunner version 37+ the code to enable the debugger has changed: components.utils.import('resource://gre/modules/devtools/dbg-server.jsm'); if (!debuggerserver.initialized) { debuggerserver.init(); debuggerserver.addbrowseractors(); debuggerserver.allowchromeprocess = true; } let dbglistener=debuggerserver.createlistener(); dbglistener.portorpath=6000; dbglistener.open(); add the following to your prefs.js: (in recent ffox, edit about:config instead) pref("devtools.debugger.remote-enabled", true); in firefox, go to tools > web developer > connect...
... create a directory <application>/distribution/bundles/venkman.
xulauncher - Archive of obsolete content
#!/bin/bash -e # a simple bash script to create a minimal xulrunner dir structure and # needed meta files in /tmp, copy the xul-file over and start it # usage: # xulauncher xulfile.xul [options] ############################################################################## # check if theres atleast one parameter ############################################################################## if [ $# -lt 1 ] then echo "you need to give the xul file as first parameter" exit fi # check if 1st parameter is a file ############################################################################## if [ !
...file%$ext} xuldir="$wd/$xulname/chrome/$xulname/" xulprefdir="$wd/$xulname/defaults/preferences" xulappini="$wd/$xulname/application.ini" xulmanifest="$wd/$xulname/chrome/chrome.manifest" xulprefs="$wd/$xulname/defaults/preferences/prefs.js" # make minimal directory structure ############################################################################## mkdir -p $xuldir mkdir -p $xulprefdir # create application.ini file ############################################################################## echo " [app] vendor=xulauncher.sh name=$xulname version=0.0.1 buildid=`date +%y%m%d` [gecko] minversion=1.8 maxversion=1.9 ">$xulappini # create chrome.manifest file ############################################################################## echo " content $xulname file:$xulname/ ">$xulmanifes...
...t # create prefs.js file ############################################################################## echo " pref(\"toolkit.defaultchromeuri\", \"chrome://$xulname/content/$xulfile\"); /* debugging prefs */ pref(\"browser.dom.window.dump.enabled\", true); pref(\"javascript.options.showinconsole\", true); pref(\"javascript.options.strict\", true); pref(\"nglayout.debug.disable_xul_cache\", true); pref(\"nglayout.debug.disable_xul_fastload\", true); ">$xulprefs # copy xul file to right location and run it ############################################################################## cp $xulfile $xuldir xulrunner $xulappini $@ ...
Mozprofile - Archive of obsolete content
command line usage mozprofile may be used to create profiles, set preferences in profiles, or install addons into profiles.
...if a profile is not specified, one will be created in a temporary directory which will be echoed to the terminal: (mozmill)> mozprofile /tmp/tmp4q1ieu.mozrunner (mozmill)> ls /tmp/tmp4q1ieu.mozrunner user.js to run mozprofile from the command line enter: mozprofile --help for a list of options.
...example: from mozprofile import firefoxprofile # create new profile to pass to mozmill/mozrunner profile = firefoxprofile(addons=["adblock.xpi"]) setting preferences preferences can be set in several ways: using the api: you can pass preferences in to the profile class's constructor: obj = firefoxprofile(preferences=[("accessibility.typeaheadfind.flashbar", 0)]) using a json blob file: mozprofile --preferences myprefs.json using a .ini file: mozpr...
2006-11-03 - Archive of obsolete content
he has also created a bug entry on bugzilla with the bug id of opened bug #344854.
... he told gery to create a bug for this problem in bugzilla.
...he has created the following bug entry https://bugzilla.mozilla.org/show_bug.cgi?id=331404.
External resources for plugin creation - Archive of obsolete content
plugins created with firebreath work on all major browsers, including firefox 3.0 and later.
... it contains pretty much everything you're likely to need to create most applications, and is particularly good for creating highly-specialised uis and for handling graphics and sound.
...e, qtwebkit and any other web browser that supports the "netscape plugin api", npapi articles, information, and tutorials npapi has been around a very long time, and there have been many attempts to distill down useful information on creating them: colonelpanic.net building a firefox plugin - part one: discusses the difference between npapi and npruntime and summarizes the basic apis needed to create a plugin building a firefox plugin - part two: discusses the basic lifecycle of a npapi plugin building a firefox plugin - part three: discusses npobjects and how to use them memory management in npapi: discusses how memory is managed in a npapi plugin browser plugins vs extensions (add-ons) -- the difference: discusses the oft-misunderstood difference between a plugin and an extension wikipedia...
NPN_GetValue - Archive of obsolete content
you can use npnvnetscapewindow to obtain the appropriate window for the wm_transient_for property of a dialog box created from the plug-in.
... microsoft windows you can use this method to help create a menu or dialog box for a windowless plug-in.
...in many cases, a plug-in may still have to create its own window (a transparent child window of the browser window) to act as the owner window for popup menus and modal dialogs.
Introduction to Public-Key Cryptography - Archive of obsolete content
the digital signature can be created only with that private key and can be validated with the corresponding public key against the signed data, which is unique to the ssl session.
... certificate data formats certificate requests and certificates can be created, stored, and installed in multiple formats: binary and text.
... the signature section includes the following information: the cryptographic algorithm, or cipher, used by the issuing ca to create its own digital signature.
Theme changes in Firefox 4 - Archive of obsolete content
for add-on buttons in the bookmarks toolbar when the related user preference is set: #navigator-toolbox[iconsize="large"] > #personaltoolbar { counter-reset: largeicons; } to use large icons everywhere, including the menu bar, regardless of the user preference: #navigator-toolbox > toolbar, #addon-bar { counter-reset: largeicons; } creating a theme that works for firefox 4 on mac os x create a new directory (for example, my_theme).
... inside that, create another new directory chrome.
...finally, you need to create a chrome.manifest file with the contents: skin browser classic/1.0 chrome/browser/ skin communicator classic/1.0 chrome/communicator/ skin global classic/1.0 chrome/global/ skin mozapps classic/1.0 chrome/mozapps/ this results in the following structure : /my_theme/chrome/browser/* /my_theme/chrome/communicator/* /my_theme/chrome/global/* /my_theme/chrome/mozapps/* /my_theme/chrome.manifest /my_theme/icon.png /my_theme/install.rdf /my_theme/preview.png note: for more information (and how to package into a jar) consult creating a ski...
Updating an extension to support multiple Mozilla applications - Archive of obsolete content
we'll build upon the stock watcher extension created in earlier articles in this series, updating it so it can also be used in thunderbird and sunbird (previous versions worked only in firefox).
... if you haven't already created an extension, or would like to refresh your memory, take a look at the previous articles in this series: creating a status bar extension creating a dynamic status bar extension adding preferences to an extension localizing an extension download the sample you can download this article's sample code so you can look at it side-by-side with the article, or to use it as a basis for your own extension.
...update the chrome manifest remember way back in the first article in this series when we created our chrome manifest, which we haven't touched since?
-ms-text-autospace - Archive of obsolete content
ideograph-alpha creates extra spacing between runs of ideographic and non-ideographic text, such as latin-based, cyrillic, greek, arabic, or hebrew text.
... ideograph-numeric creates extra spacing between runs of ideographic text and numeric characters.
... ideograph-parenthesis creates extra spacing between a normal (non-wide) parenthesis and an ideograph.
CSS - Archive of obsolete content
ArchiveWebCSS
however, those elements' ancestors have this pseudo-class applied to them.:-moz-system-metric()this page was auto-generated because a user created a sub-page to this page.::-ms-browsethe ::-ms-browse css pseudo-element is a microsoft extension that represents the button that opens the file picker of <input type="file">.::-ms-checkthe ::-ms-check css pseudo-element is a microsoft extension that represents checkboxes and radio button groups created by <input type="checkbox"> and <input type="radio">.::-ms-clearthe ::-ms-clear css pseudo-ele...
...ment creates a clear button at the edge of an <input type="text"> text control that clears the current value.
...a slider control is one possible representation of <input type="range">.::-ms-revealthe ::-ms-reveal css pseudo-element is a microsoft extension that is used to display a password reveal button for use with a password field created by <input type="password">.
Displaying notifications (deprecated) - Archive of obsolete content
creating a notification the first thing you need to do is create the notification object by using the navigator.moznotification object's createnotification() method, as follows: var notification = navigator.moznotification.createnotification( "hey, check this out!", "this is a notification posted by " + "firefox 4.
... setting up event listeners on the notification there are two events you can listen to on created notifications: onclick this event is fired when the user clicks (or taps) on the notification.
... for example, let's simply append a little html to our document when these events fire: notification.onclick = function() { var e = document.createelement("p"); e.innerhtml = "<strong>the notification was clicked.</strong>"; document.body.appendchild(e); }; notification.onclose = function() { var e = document.createelement("p"); e.innerhtml = "<strong>the notification was closed.</strong>"; document.body.appendchild(e); }; displaying the notification once the notification is configured the way you want it to be, call its show() method to display the notification: notifica...
Generator comprehensions - Archive of obsolete content
generator comprehensions are syntactically almost identical to array comprehensions — they use parentheses instead of braces— but instead of building an array they create a generator that can execute lazily.
...we want to create a new iterator that will iterate over their doubles.
... an array comprehension would create a full array in memory containing the doubled values: var doubles = [for (i in it) i * 2]; a generator comprehension on the other hand would create a new iterator which would create doubled values on demand as they were needed: var it2 = (for (i in it) i * 2); console.log(it2.next()); // the first value from it, doubled console.log(it2.next()); // the second value from it, doubled when a generator comprehension is used as the argument to a function, the parentheses used for the function call means that the outer parentheses can be omitted: var result = dosomething(for (i in it) i * 2); the significant difference between the two examples being that by using the generator comprehension, you would only have to loop over the 'obj' structure once, total, ...
VBArray.dimensions - Archive of obsolete content
the first part is vbscript code to create a visual basic safe array.
... <head> <script type="text/vbscript"> <!-- function createvbarray() dim i, j, k dim a(2, 2) k = 1 for i = 0 to 2 for j = 0 to 2 a(j, i) = k k = k + 1 next next createvbarray = a end function --> </script> <script type="text/javascript"> <!-- function vbarraytest(vba) { var i; var a = new vbarray(vba); var s = ""; for (i = 1; i <= a.dimensions(); i++) { s += "the upper bound of dimension "; s += i + " is "; s += a.ubound(i); ...
... s += ".<br />"; } return(s); } --> </script> </head> <body> <script type="text/javascript"> document.write(vbarraytest(createvbarray())); </script> </body> requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, and internet explorer 10 standards.
VBArray.getItem - Archive of obsolete content
the first part is vbscript code to create a visual basic safe array.
... <head> <script type="text/vbscript"> <!-- function createvbarray() dim i, j, k dim a(2, 2) k = 1 for i = 0 to 2 for j = 0 to 2 a(i, j) = k document.writeln(k) k = k + 1 next document.writeln("<br>") next createvbarray = a end function --> </script> <script type="text/javascript"> <!-- function getitemtest(vbarray) { var i, j; var a = new vbarray(vbarray); for (i = 0; i <= 2; i++) { for (j =0; j <= 2; j++) { document.writ...
...eln(a.getitem(i, j)); } } } --> </script> </head> <body> <script type="text/javascript"> <!-- getitemtest(createvbarray()); --> </script> </body> requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, and internet explorer 10 standards.
VBArray.toArray - Archive of obsolete content
the first part is vbscript code to create a visual basic safe array.
... <head> <script type="text/vbscript"> <!-- function createvbarray() dim i, j, k dim a(2, 2) k = 1 for i = 0 to 2 for j = 0 to 2 a(j, i) = k document.writeln(k) k = k + 1 next document.writeln("<br>") next createvbarray = a end function --> </script> <script type="text/javascript"> <!-- function vbarraytest(vbarray) { var a = new vbarray(vbarray); var b = a.toarray(); var i; for (i = 0; i < 9; i++) { document.writeln(b[i]); } } --> </script> </head> <...
...body> <script type="text/javascript"> <!-- vbarraytest(createvbarray()); --> </script> </body> requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, and internet explorer 10 standards.
VBArray.ubound - Archive of obsolete content
the first part is vbscript code to create a visual basic safe array.
... <head> <script type="text/vbscript"> <!-- function createvbarray() dim i, j, k dim a(2, 2) k = 1 for i = 0 to 2 for j = 0 to 2 a(j, i) = k k = k + 1 next next createvbarray = a end function --> </script> <script type="text/javascript"> <!-- function vbarraytest(vba) { var i; var a = new vbarray(vba); var s = ""; for (i = 1; i <= a.dimensions(); i++) { s += "the upper bound of dimension "; s += i + " is "; s += a.ubound(i); ...
... s += ".<br />"; } return (s); } --> </script> </head> <body> <script type="text/javascript"> document.write(vbarraytest(createvbarray())); </script> </body> requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, and internet explorer 10 standards.
JavaObject - Archive of obsolete content
created by any java method which returns an object type.
... description the javaobject object is an instance of a java class that is created in or passed to javascript.
... examples example: instantiating a java object in javascript the following code creates the javaobject thestring, which is an instance of the class java.lang.string: var thestring = new packages.java.lang.string("hello, world"); because the string class is in the java package, you can also use the java synonym and omit the packages keyword when you instantiate the class: var thestring = new java.lang.string("hello, world"); example: accessing methods of a java object because...
Sharp variables in JavaScript - Archive of obsolete content
usage to create a sharp variable, simply assign an object to it in a line of code using an equal sign.
...you can use this to create objects in a single line of code that would otherwise take multiple lines of code.
... 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.
Styling the Amazing Netscape Fish Cam Page - Archive of obsolete content
thus: div.card {float: left; width: 45%; margin: 1em 2% 0 2%;} div.card img {float: left; margin: 4px 0 0 0; border: 1px solid #339;} div.card h3 {border: 1px solid #339; border-left: 5px double #339; background: #eec url(body-bg-tan.jpg) bottom left no-repeat fixed; color: #339;} finishing the style adding the background to the heading containing the name of the fish created three problems: the double border was completely covered up by the image.
...in order to create visual appeal, i decided to offset the top let corners of the fish image and fish name.
... i hope that our little cruise through this aspect of the redesign has gotten you hooked on the idea of using simple markup and css to create interesting effects, if you weren't already.
XForms Custom Controls - Archive of obsolete content
purpose you are in the right place if you would like to create your own custom renderings of the xforms controls like input, output, trigger, etc.
... we will also show you how to create custom controls that work with the xforms model and are automatically updated just like xforms controls.
...we recommend that you use this attribute to create the css binding rule for your custom control.
Introduction to game development for the Web - Game development
the range of games that can be created is on par with desktop and native os counterparts.
... web audio api this api for controlling the playback, synthesis, and manipulation of audio from javascript code lets you create awesome sound effects as well as play and manipulate music in real time.
... webgl lets you create high-performance, hardware-accelerated 3d (and 2d) graphics from web content.
Async scripts for asm.js - Game development
putting async into action getting async compilation is easy: when writing your javascript, just use the async attribute like so: <script async src="file.js"></script> or, to do the same thing via script: var script = document.createelement('script'); script.src = "file.js"; document.body.appendchild(script); (scripts created from script default to async.) the default html shell emscripten generates produces the latter.
... two common situations in which a script is *not* async (as defined by the html spec) are: <script async>code</script> and var script = document.createelement('script'); script.innerhtml = "code"; document.body.appendchild(script); both are counted as 'inline' scripts and get compiled and then run immediately.
...instead of using eval or innerhtml, both of which trigger synchronous compilation, you should use a blob with an object url: var blob = new blob([codestring]); var script = document.createelement('script'); var url = url.createobjecturl(blob); script.onload = script.onerror = function() { url.revokeobjecturl(url); }; script.src = url; document.body.appendchild(script); the setting of src rather than innerhtml is what makes this script async.
Crisp pixel art look with image-rendering - Game development
the steps to achieve this effect are: create a <canvas> element and set its width and height attributes to the original, smaller resolution.
...if the canvas was created with a 128 pixel width, for example, we would set the css width to 512px if we wanted a 4x scale.
...the original image we want to upscale looks like this: here's some html to create a simple canvas: <canvas id="game" width="128" height="128"></canvas> css to size the canvas and render a crisp image: canvas { width: 512px; height: 512px; image-rendering: -moz-crisp-edges; image-rendering: -webkit-crisp-edges; image-rendering: pixelated; image-rendering: crisp-edges; } and some javascript to set up the canvas and load the image: // get canvas context var ctx ...
Build the brick field - Game development
what a breakout game really needs is some bricks to destroy with the ball, and this is what we'll create now!
...add the following just below your variables: var bricks = []; for(var c=0; c<brickcolumncount; c++) { bricks[c] = []; for(var r=0; r<brickrowcount; r++) { bricks[c][r] = { x: 0, y: 0 }; } } the code above will loop through the rows and columns and create the new bricks.
... brick drawing logic now let's create a function to loop through all the bricks in the array and draw them on the screen.
2D breakout game using pure JavaScript - Game development
next » in this step-by-step tutorial we create a simple mdn breakout game written entirely in pure javascript and rendered on html5 <canvas>.
... lesson details all the lessons — and the different versions of the mdn breakout game we are building together — are available on github: create the canvas and draw on it move the ball bounce off the walls paddle and keyboard controls game over build the brick field collision detection track the score and win mouse controls finishing up starting with pure javascript is the best way to get a solid knowledge of web game development.
...head to the first chapter— create the canvas and draw on it.
Animations and tweens - Game development
we will show the sprites sequentially to create the illusion of animation.
... loading the animation next up, go into your create() function, find the line that loads the ball sprite, and below it put the call to animations.add() seen below: ball = game.add.sprite(50, 250, 'ball'); ball.animations.add('wobble', [0,1,0,2,0,1,0,2,0], 24); to add an animation to the object we use the animations.add() method, which contains the following parameters the name we chose for the animation an array defining the order in which to display the frames during the animation.
...update the first line inside update() as shown below: function update() { game.physics.arcade.collide(ball, paddle, ballhitpaddle); game.physics.arcade.collide(ball, bricks, ballhitbrick); paddle.x = game.input.x || game.world.width*0.5; } then we can create the ballhitpaddle() function (having ball and paddle as default parameters), playing the wobble animation when it is called.
Visual JS GE - Game development
if you use editor.js to visually create game objects, you must start the build_from_editor_to_visual_js_file.js when you have finished.
... this tool will create visual.js in the starter/ directory along with all your game objects.
...the actual image objects will be created after you add animation to the game objects.
Grid - MDN Web Docs Glossary: Definitions of Web-related terms
if you place content outside of this explicit grid, or if you are relying on auto-placement and the grid algorithm needs to create additional row or column tracks to hold grid items, then extra tracks will be created in the implicit grid.
... the implicit grid is the grid created automatically due to content being added outside of the tracks defined.
... in the example below i have created an explicit grid of three columns and two rows.
Grid Areas - MDN Web Docs Glossary: Definitions of Web-related terms
grid areas are created when you place an item using line-based placement or when defining areas using named grid areas.
... grid areas must be rectangular in nature; it is not possible to create, for example, a t- or l-shaped grid area.
...this creates two grid areas, one covering four grid cells, the other two.
Houdini - MDN Web Docs Glossary: Definitions of Web-related terms
the benefit of houdini is that developers can create css features without waiting for web standards specifications to define them and without waiting for every browser to fully implement the features.
... while many of the features houdini enables can be created with javascript, interacting directly with the cssom before javascript is enabled provides for faster parse times.
... browsers create the cssom — including layout, paint, and composite processes — before applying any style updates found in scripts: layout, paint, and composite processes are repeated for updated javascript styles to be implemented.
Primitive - MDN Web Docs Glossary: Definitions of Web-related terms
it correctly finds our variable instantiated with our first statement after finding it, the expression is evaluated, foo is replaced by 5 and the javascript engine passes that value to the functions as an argument before executing the statements inside the functions' bodies, javascript takes a copy of the originally passed argument (which is a primitive) and creates a local copy.
... these copies, existing only inside the functions' scopes, are accessible via the identifiers we specified in the functions' definitions (num for addtwo, foo for addtwo_v2) then, the functions' statements are executed: in the first function, a local num variable had been created.
... in the second function, a local foo variable had been created.
Thread - MDN Web Docs Glossary: Definitions of Web-related terms
however, modern javascript offers ways to create additional threads, each executing independently while possibly communicating between one another.
... a special type of worker, called a service worker, can be created which can be left behind by a site—with the user's permission—to run even when the user isn't currently using that site.
... this is used to create sites capable of notifying the user when things happen while they're not actively engaged with a site.
Test your skills: CSS and JavaScript accessibility - Learn web development
we'd like you to assume that the existing ruleset with the a selector is supplied by some cms, and that you can't change it — instead, you need to create new rules to make the links look and behave like links, and for the user to be able to tell where they are in the list.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
Cascade and inheritance - Learn web development
usually the problem is that you have created two rules which could potentially apply to the same element.
...a common practice is to define generic styles for the basic elements, and then create classes for those which are different.
... for example, in the stylesheet below we have defined generic styles for level 2 headings, and then created some classes which change only some of the properties and values.
Overflowing content - Learn web development
in addition, some of the methods discussed in sizing items in css may help you create boxes that scale better with varying amounts of content.
... overflow establishes a block formatting context when you use a value of overflow such as scroll or auto, you create a block formatting context (bfc).
...this enables scrolling behavior, as all box content needs to be contained and not overlap, in order to create a consistent scrolling experience.
Test your skills: The Box Model - Learn web development
try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the example as displayed in the image: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor.
Test your skills: sizing - Learn web development
try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the example as displayed in the image: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the example as displayed in the image: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor.
Test your skills: values and units - Learn web development
try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the example as displayed in the image: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the example as displayed in the image: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor.
Test your skills: Writing Modes and Logical Properties - Learn web development
try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the example as displayed in the image: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor.
Floats - Learn web development
prerequisites: html basics (study introduction to html), and an idea of how css works (study introduction to css.) objective: to learn how to create floated features on webpages, and to use the clear property and other methods of clearing floats.
... floats have commonly been used to create entire web site layouts featuring multiple columns of information floated so they sit alongside one another (the default behavior would be for the columns to sit below one another, in the same order as they appear in the source).
...this exists only to create a bfc without using hacks — there will be no unintended consequences when you use it.
Test your skills: floats - Learn web development
try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor.
Getting started with CSS - Learn web development
it contains an <em>emphasized</em> element.</p> <ul> <li>item one</li> <li>item two</li> <li>item <em>three</em></li> </ul> </body> </html> note: if you are reading this on a device or an environment where you can't easily create files, then don't worry — live code editors are provided below to allow you to write example code right here in the page.
... create a file in the same folder as your html document and save it as styles.css.
...therefore it is sometimes best to bypass the element and simply refer to the class, unless you know that you want to create some special rules for one element alone, and perhaps want to make sure they are not applied to other things.
CSS first steps - Learn web development
looking at it, consuming the content.) a basic work environment set up as detailed in installing basic software, and an understanding of how to create and manage files, as detailed in dealing with files.
... note: if you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as jsbin or glitch.
... css (cascading style sheets) allows you to create great-looking web pages, but how does it work under the hood?
Fundamental text and font styling - Learn web development
oblique: sets the text to use a simulated version of an italic font, created by slanting the normal version.
...you can use combinations of these property values to create interesting effects, for example text-decoration: line-through red wavy.
... <input id="reset" type="button" value="reset" style="margin: 10px 10px 0 0;"> </div> </div> const htmlinput = document.queryselector(".html-input"); const cssinput = document.queryselector(".css-input"); const reset = document.getelementbyid("reset"); let htmlcode = htmlinput.value; let csscode = cssinput.value; const output = document.queryselector(".output"); const styleelem = document.createelement('style'); const headelem = document.queryselector('head'); headelem.appendchild(styleelem); function drawoutput() { output.innerhtml = htmlinput.value; styleelem.textcontent = cssinput.value; } reset.addeventlistener("click", function() { htmlinput.value = htmlcode; cssinput.value = csscode; drawoutput(); }); htmlinput.addeventlistener("input", drawoutput); cssinput.addeventli...
Styling links - Learn web development
two points to note here are: the underline has been created using border-bottom, not text-decoration — some people prefer this because the former has better styling options than the latter, and is drawn a bit lower, so doesn't cut across the descenders of the word being underlined (e.g.
...lution" style="margin: 10px 0 0 10px;"> </div> </div> var htmlinput = document.queryselector(".html-input"); var cssinput = document.queryselector(".css-input"); var reset = document.getelementbyid("reset"); var htmlcode = htmlinput.value; var csscode = cssinput.value; var output = document.queryselector(".output"); var solution = document.getelementbyid("solution"); var styleelem = document.createelement('style'); var headelem = document.queryselector('head'); headelem.appendchild(styleelem); function drawoutput() { output.innerhtml = htmlinput.value; styleelem.textcontent = cssinput.value; } reset.addeventlistener("click", function() { htmlinput.value = htmlcode; cssinput.value = csscode; drawoutput(); }); solution.addeventlistener("click", function() { htmlinput.value = ht...
... note: you may have noticed that the list items in the html are all put on the same line as each other — this is done because spaces/line breaks in between inline block elements create spaces on the page, just like the spaces in between words, and such spaces would break our horizontal navigation menu layout.
How do I use GitHub Pages? - Learn web development
st-site on your desktop: cd desktop/test-site when the command line is pointing inside your website directory, type the following command, which tells the git tool to turn the directory into a git repository: git init an aside on command line interfaces the best way to upload your code to github is via the command line — this is a window where you type in commands to do things like create files and run programs, rather than clicking inside a user interface.
... creating a repo for your code next, you need to create a new repo for your files to go in.
...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.
What software do I need to build a website? - Learn web development
you'll need tools to: create and edit webpages upload files to your web server view your website nearly all operating systems by default include a text editor and a browser, which you can use to view websites.
... dig deeper creating and editing webpages to create and edit a website, you need a text editor.
... text editors create and modify unformatted text files.
How to structure a web form - Learn web development
each time you want to create an html form, you must start it by using this element, nesting all the contents inside.
... the <fieldset> and <legend> elements the <fieldset> element is a convenient way to create groups of widgets that share the same purpose, for styling and semantic purposes.
... apply the css to the html by adding the following line inside the html <head>: <link href="payment-form.css" rel="stylesheet"> next, create your form by adding the outer <form> element: <form> </form> inside the <form> tags, add a heading and paragraph to inform users how required fields are marked: <h1>payment form</h1> <p>required fields are followed by <strong><abbr title="required">*</abbr></strong>.</p> next we'll add a larger section of code into the form, below our previous entry.
Test your skills: HTML5 controls - Learn web development
create appropriate inputs for a user to update their details for: email website phone number favourite color try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... create a corresponding output element to put the current value of the slider into.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
UI pseudo-classes - Learn web development
we create it using this css: input + span { position: relative; } input:required + span::after { font-size: 0.7rem; position: absolute; content: "required"; color: white; background-color: black; padding: 5px 10px; top: -26px; left: -70px; } we set the <span> to position: relative simply so that we can set the generated content to position: absolute and position it relative to the <spa...
...we style the indeterminate radio buttons with the following css: input[type="radio"]:indeterminate { border: 2px solid red; animation: 0.4s linear infinite alternate border-pulse; } @keyframes border-pulse { from { border: 2px solid red; } to { border: 6px solid red; } } this creates a fun little animated border on the radio buttons, which hopefully indicates that you need to select one of them!
...keep playing with them, and create some fun form styles!
Document and website structure - Learn web development
line breaks and horizontal rules two elements that you'll use occasionally and will want to know about are <br> and <hr>: <br> creates a line break in a paragraph; it is the only way to force a rigid structure in a situation where you want a series of fixed short lines, such as in a postal address or a poem.
...ple: <p>there once was a man named o'dell<br> who loved to write html<br> but his structure was bad, his semantics were sad<br> and his markup didn't read very well.</p> without the <br> elements, the paragraph would just be rendered in one long line (as we said earlier in the course, html ignores most whitespace); with <br> elements in the code, the markup renders like this: <hr> elements create a horizontal rule in the document that denotes a thematic change in the text (such as a change in topic or scene).
... active learning: create your own sitemap try carrying out the above exercise for a website of your own creation.
Test your skills: HTML text basics - Learn web development
try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
Test your skills: Links - Learn web development
try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
Introduction to HTML - Learn web development
you should have a basic work environment set up (as detailed in installing basic software), and understand how to create and manage files (as detailed in dealing with files).
... note: if you are working on a computer/tablet/other devices that doesn't let you create your own files, you can try out (most of) the code examples in an online coding program such as jsbin or glitch.
...this article looks at how to use html to break up a block of text into a structure of headings and paragraphs, add emphasis/importance to words, create lists, and more.
Test your skills: HTML images - Learn web development
try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
Mozilla splash page - Learn web development
alternatively, you could use an online tool such as glitch to create your example.
...the following subsections detail what you need to do: preparing images using your favourite image editor, create 400px wide and 120px wide versions of: firefox_logo-only_rgb.png firefox-addons.jpg mozilla-dinosaur-head.png call them something sensible, e.g.
... next, create a 1200px wide landscape version of red-panda.jpg, and a 600px wide portrait version that shows the panda in more of a close up shot.
Test your skills: Multimedia and embedding - Learn web development
try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
Functions — reusable blocks of code - Learn web development
you don't need to learn about the inner workings of structured javascript objects yet — you can wait until our later module that will teach you all about the inner workings of objects, and how to create your own.
...so far we have just created a function like so: function myfunction() { alert('hello'); } but you can also create a function that doesn't have a name: function() { alert('hello'); } this is called an anonymous function — it has no name!
...when you create a function, the variables and other things defined inside the function are inside their own separate scope, meaning that they are locked away in their own separate compartments, unreachable from code outside the functions.
Making decisions in your code — conditionals - Learn web development
a function called createcalendar() that draws the calendar and displays the correct month in the <h1> element.
...="a11y-label">press esc to move focus away from the code area (tab inserts a tab character).</p> <textarea id="code" class="playable-code" style="height: 400px;width: 95%"> const select = document.queryselector('select'); const list = document.queryselector('ul'); const h1 = document.queryselector('h1'); select.onchange = function() { const choice = select.value; // add conditional here createcalendar(days, choice); } function createcalendar(days, choice) { list.innerhtml = ''; h1.textcontent = choice; for (let i = 1; i <= days; i++) { const listitem = document.createelement('li'); listitem.textcontent = i; list.appendchild(listitem); } } createcalendar(31,'january'); </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="reset"> <i...
...nst select = document.queryselector(\'select\');\nconst list = document.queryselector(\'ul\');\nconst h1 = document.queryselector(\'h1\');\n\nselect.onchange = function() {\n const choice = select.value;\n let days = 31;\n if(choice === \'february\') {\n days = 28;\n } else if(choice === \'april\' || choice === \'june\' || choice === \'september\'|| choice === \'november\') {\n days = 30;\n }\n\n createcalendar(days, choice);\n}\n\nfunction createcalendar(days, choice) {\n list.innerhtml = \'\';\n h1.textcontent = choice;\n for(let i = 1; i <= days; i++) {\n const listitem = document.createelement(\'li\');\n listitem.textcontent = i;\n list.appendchild(listitem);\n }\n }\n\ncreatecalendar(31,\'january\');'; let solutionentry = jssolution; textarea.addeventlistener('input', updatecode); window.a...
Test your skills: Math - Learn web development
you will have to create four numeric values, then add the first two together, then subtract the fourth from the third, then multiply the two secondary results together to get a result of 48.
... so, try updating the live code below to recreate the finished example, following these steps: create four variables that contain numbers.
... try updating the live code below to recreate the finished example, following these steps: write a calculation that multiplies result and result2 together and assigns the result back to result.
Test your skills: variables - Learn web development
try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
Test your skills: Object basics - Learn web development
try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
Measuring performance - Learn web development
performance apis when writing code for the web, there are a large number of web apis available that allow you to create your own performance measuring tools.
...a performance entry can be directly created by making a performance mark or measure (for example by calling the mark() method) at an explicit point in an application.
... performance entries are also created in indirect ways; such as loading a resource, like an image.
Website security - Learn web development
a successful injection attack might spoof identities, create new identities with administration rights, access all data on the server, or destroy/modify the data to make it unusable.
... select * from users where name = 'a';drop table users; select * from userinfo where 't' = 't'; the modified statement creates a valid sql statement that deletes the users table and selects all data from the userinfo table (which reveals the information of every user).
...even if he found out the secret and created a form for a particular user, he would no longer be able to use that same form to attack every user.
Accessibility in React - Learn web development
react’s useref hook creates an object with a single property: current.
... change the import statement at the top of todo.js so that it includes useref: import react, { useref, usestate } from "react"; then, create two new constants beneath the hooks in your todo() function.
...look out for opportunities to practice them more, because doing so will allow you to create inclusive experiences for users.
Rendering a list of Vue components - Learn web development
export default { name: 'app', components: { todoitem }, data() { return { todoitems: [ { label: 'learn vue', done: false }, { label: 'create a vue project with the cli', done: true }, { label: 'have fun', done: true }, { label: 'create a to-do list', done: false } ] }; } }; now that we have a list of items, we can use the v-for directive to display them.
... your app.vue <script> element contents should now look like this: import todoitem from './components/todoitem.vue'; import uniqueid from 'lodash.uniqueid' export default { name: 'app', components: { todoitem }, data() { return { todoitems: [ { id: uniqueid('todo-'), label: 'learn vue', done: false }, { id: uniqueid('todo-'), label: 'create a vue project with the cli', done: true }, { id: uniqueid('todo-'), label: 'have fun', done: true }, { id: uniqueid('todo-'), label: 'create a to-do list', done: false } ] }; } }; now, add the v-for directive and key attribute to the <li> element in your app.vue template, like so: <ul> <li v-for="item in todoitems" :key="item.id"> <to-do-item label="my t...
...while this isn't strictly necessary, it makes it easier for us to manage since we already need to create a unique id for each todo item anyway.
Accessibility API cross-reference
to do fill out mac api column.(mac os x - carbon accessibility api and accessibility constants) finish aria column - add explanation of the term 'abstract role' fill out html column create aom column fill out xul column.
... feed a landmark region that contains a collection of items and objects that, as a whole, combine to create a form.
... n/a n/a rowgroup n/a a table row header rowheader row_header row_header, table_row_header rowheader <th scope=row> vertical or horizontal scrollbar scrollbar scroll_bar scroll_bar scrollbar a landmark region that contains a collection of items and objects that, as a whole, combine to create a search facility.
Accessible Toolkit Checklist
the system should require these labels to be created/associated with each widget, not as a separate static text with no tie to the widget.
...this is one reason why a label must be created together with each widget, rather than separately.
..., focused, readonly, offscreen, focusable to avoid extra work, utilize implementing an msaa server mnemonics ability to define in xml for any widget with a text label (via attribute or a preceding char in label) automatically define mnemonics for all standard common dialogs (like yes/no confirmations and retry/exit error dialogs) support mnemonics in dialogs created via method calls layout engine - drawing underline under correct letter events - making keystrokes do the right thing msaa support, via iaccessible's get_acckeyboardshortcut support for ms windows settings when high contrast checkbox is set (in accessibility control panel, spi_gethighcontrast), or when user selects a "native" skin option in your software, t...
Frequently Asked Questions for Lightweight themes
creating your own themes can i create my own theme?
...all you need to do is create two graphics files in your favorite graphics editing program (e.g., photoshop).
... to get started read more about how to create a theme.
Creating JavaScript callbacks in components
callback patterns in idl xpcom components use idl to create interfaces.
...a common pattern used with interfaces to create a bi-directional communication between two groups of code is the observer (or listener) pattern.
...now we can create a callback javascript function to handle the onword event: function handleword(word) { alert(word); } var stringparser = /* get a reference to the parser somehow */ stringparser.addobserver(handleword); stringparser.parse("pay no attention to the man behind the curtain"); yes, you can still use the normal interface-based callback implementation too.
Creating a Firefox sidebar
there are two ways to create a sidebar for firefox users: the social api and an extension.
...there are some ways to create an extension: the new sidebar api has been implemented in firefox 29 as part of the add-on sdk.
... it's the easiest way to create an extension with a sidebar.obsolete since gecko 57 you can also build a restartless extension yourself without the sdk.
Creating a spell check dictionary add-on
parts needed to create a dictionary add-on, you first need two things: a spell check dictionary in hunspell or myspell format, with a license which allows you to use it.
...to create a dictionary add-on, simply create a zip file which contains the following files and folders: my-dictionary.xpi install.rdf dictionaries/ locale-code.dic locale-code.aff the .dic and .aff files must be placed in a subfolder named dictionaries within the zip file.
...you can create and edit it with a plain text editor such as notepad.
Debugging on Windows
ways to start the debugger first of all, it's necessary to install a visual studio extension to be able to follow child processes as they are created.
...this will also create a visual c++ mozilla project in the directory of the executable by default.
...for each dll, click the "new" button which creates a new entry and then hit the "..." buttons which lets you browse to the dll.
Old Thunderbird build
first, cd into the comm-central subdirectory (created automatically by the previous command): cd comm-central then run: python client.py checkout on some types of network connections, "hg clone" might fail because it gets interrupted.
... build configuration to build thunderbird, you need to add a file named mozconfig to the root directory of the comm-central checkout that contains the following line: ac_add_options --enable-application=mail you can create a file with this line by doing this: cd comm-central echo 'ac_add_options --enable-application=mail' > mozconfig if you omit this line, the build system will build firefox instead.
...for example, to create a debug build instead of a release build, that file would contain: ac_add_options --enable-debug for more on configuration options, see the page configuring build options.
Eclipse CDT Manual Setup
whenever you create a new workspace for a mozilla source tree, you should be sure to turn off the following two settings in the workspace preferences (window > preferences, or eclipse > preferences) before creating a project in that workspace: in "general > workspace", disable "build automatically" in "c/c++ > indexer", disable "automatically update the index" turning off automatic indexing prevents the cpu in...
... creating an eclipse project to create an eclipse project for your mozilla source tree, select "file > new > makefile project with existing code".
... to create resource filters, open the project properties (different to the workspace preferences!) by selecting properties from the context menu for the project (root item) in the project explorer tab on the left, or by selecting project > properties from the menubar.
Experimental features in Firefox
this allows to create gallery style layouts like on pinterest.
... nightly 63 no developer edition 63 no beta 63 no release 63 starting in firefox 68, on android only preference name dom.visualviewport.enabled constructable stylesheets the addition of a constructor to the cssstylesheet interface as well as a variety of related changes makes it possible to directly create new stylesheets without having to add the sheet to the html.
... this makes it much easier to create reusable stylesheets for use with shadow dom.
Limitations of chrome scripts
however, you must listen to content-document-global-created and document-element-inserted in a frame script.
... sandboxes you can create sandboxes in the chrome or the content process.
... sandboxes are often used as a safe way to manipulate web content, and if that's your goal, create the sandbox in the content process.
Frame script loading and lifetime
if you've set allowdelayedload, the script is loaded into a new tab as soon as it is created.
...if you want to limit a script to the lifetime of a page you can create a sandbox instead, where the current content page is used as prototype.
... if you want a frame script to do something when a new document is loaded, you need to listen for an appropriate dom event, generally domwindowcreated, domcontentloaded, or load.
How to Report a Hung Firefox
create a new bug report at bugzilla.mozilla.org using this link.
... create a new bug report at bugzilla.mozilla.org using this link.
... create a new bug report at bugzilla.mozilla.org using this link.
Internationalized Domain Names (IDN) Support in Mozilla Browsers
these preferences can be modified or new ones can be created without quitting the browser using the steps described below.
... create a new preference item using the menu new > string via a right-mouse click.
... next create another new preference item using the right-mouse click menu new > boolean.
Introduction to Layout in Mozilla
reflow painting setting up assume basic knowledge of embedding and network apis (doc shell, streams) content dll auto-registers a document loader factory (dlf) @mozilla.org/content-viewer-factory/view;1?type=text/html all mime types mapped to the same class, nscontentdlf nsdocshell receives inbound content via nsdsuricontentlistener invokes nsidlf::createinstance, passes mime type to dlf nscontentdlf creates a nshtmldocument object, invokes startdocumentload.
... creates a parser, returned as nsistreamlistener back to the docshell creates a content sink, which is linked to the parser and the document creates a documentviewerimpl object, which is returned as nsicontentviewer back to the docshell documentviewerimpl creates pres context and pres shell content model construction content arrives from network via nsistreamlistener::ondataavailable parser tokenizes & processes content; invokes methods on nsicontentsink with parser node objects some buffering and fixup occurs here opencontainer, closecontainer, addleaf content sink creates and attaches content nodes using nsicontent interface content sink maintains stack of “live” elements more buffering and f...
...notifications passes these to the style set object, who in turn passes to the frame constructor frame constructor creates frames constructframeinternal recursively walks content tree, resolves style and creates frames either created by tag (<select>) or by display type (<p>) frame manager maintains mapping from content to frame style resolution compute stylistic information based on the style rules that apply for the frame’s content node style data broken into different structures ...
API-provided widgets
to create a widget, you should pass a specification object with its desired properties.
... onbeforecreated(adoc) attached to all non-custom widgets; a function that will be invoked before the widget gets a dom node constructed, passing the document in which that will happen.
... oncreated(anode) attached to all widgets; a function that will be invoked whenever the widget has a dom node constructed, passing the constructed node as an argument.
Following the Android Toasts Tutorial from a JNI Perspective
toasts do not have to be created with jni; they are exposed by the nativewindow feature on firefox for android, see toast documentation.
...ontext = getapplicationcontext(); var context = geckoappshell.getcontext(); // charsequence text = 'hello toast!'; var text = 'hello toast!'; // int duration = toast.length_short; var duration = toast.length_short; // toast toast = toast.maketext(context, text, duration); var toast = toast.maketext(context, text, duration); // toast.show(); toast.show(); notice that the charsequence was not created with a constructor.
...ength_short; // toast toast = toast.maketext(context, text, duration); var toast = toast.maketext(context, text, duration); // toast.show(); toast.show(); } finally { if (my_jenv) { jni.unloadclasses(my_jenv); } } references oracle :: jni types and data structures and determine the signature of a method - these articles are crucial because it tells us how to create our jni signatures.
OS.File.Info
before deprecation, this used to be the date at which the file was created on windows and mac os x, as a javascript date object.
... windows winbirthdate a date representing the time at which the file was created.
... winattributes hidden boolean readonly boolean system boolean macos x macbirthdate a date representing the time at which the file was created.
Examples
userdefinedpromise(); mypromise.then( function(asuccessreason) { alert('mypromise was succesful and reason was = "' + asuccessreason + '"'); }, function(arejectreason) { alert('mypromise failed for reason = "' + uneval(arejectreason) + '"'); } ); function myuserdefinedpromise() { return 'i didnt do a promise.resolve so this will not understand that mypromise is a promise'; } // creates this error: /* exception: mypromise.then is not a function @scratchpad/5:8:1 wca_evalwithdebugger@resource://gre/modules/commonjs/toolkit/loader.js -> resource://gre/modules/devtools/server/actors/webconsole.js:1069:7 wca_onevaluatejs@resource://gre/modules/commonjs/toolkit/loader.js -> resource://gre/modules/devtools/server/actors/webconsole.js:734:9 dsc_onpacket@resource://gre/modules/commonjs...
...server/main.js:1098:9 ldt_send/<@resource://gre/modules/devtools/dbg-client.jsm -> resource://gre/modules/devtools/server/transport.js:279:11 makeinfallible/<@resource://gre/modules/commonjs/toolkit/loader.js -> resource://gre/modules/devtools/devtoolsutils.js:84:7 */ intermediate of user defined promise function 1 components.utils.import("resource://gre/modules/promise.jsm"); // this function creates and returns a new promise.
... make user defined promise return after multiple images finish loading (promise.all and promise.defer) this example shows how to use promise.all to wait to create multiple promises with promise.defer() and return at the end of it.
Sqlite.jsm
sqlite.jsm will create, manage, and destroy statement instances for you.
... you don't need to worry about caching created statement instances, destroying them when you are done, etc.
...if the path does not exist, a new sqlite database will be created.
Task.jsm
; return "value"; } methods async() create and return an "async function" that starts a new task.
...}); // behaves the same spawn() creates and starts a new task.
... let's create a promise object, wait on // it and capture its resolution value.
SVN for Localizers
enter the following command in your command-line tool: svn checkout https://svn.mozilla.org/projects/mozilla.com/trunk/locales/[your locale code] mozilla-l10n-[your-localecode] this command creates the mozilla-l10n-[your-localecode] directory on your computer and copies into it all of the files from https://svn.mozilla.org/projects/moz...om/trunk/locales/[your locale code].
... note: the directory you create will be located inside the directory that you're currently in with your console (or cygwin console).
...it's a bit hard to read, but you can also create a diff file (aka a diff patch) use svn diff > /path/to/output/file.diff to save the output to a file.
What every Mozilla translator should know
when a development is started for an specific version, a new repository is created under hg.mozilla.org/releases/.
... 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" revi...
... do the changes in your local disk create a diff file with the changes $ hg diff -p -u 8 filename create a new bug: product: mozilla localization component: your language ...
GC and CC logs
it also creates a file named cc-edges-nnnn.log to which it dumps the parts of the heap visible to the cycle collector, which includes native c++ objects that participate in cycle collection, as well as js objects being held alive by those c++ objects.
...by default, the file is created in some temp directory, and the path to the file is printed to the error console.
... alternatives there are two add-ons that can be used to create and analyze cc graphs.
A brief guide to Mozilla preferences
prefs.js is automatically generated by the application and should not be edited manually, whereas user.js is an optional file the user can create to override preferences initialized by other preferences files.
... sticky preferences are created when they are defined using sticky_pref().
... these preferences act as default preferences but whenever a value is created for the preference, that value is always written even when it matches the default.
browser.pagethumbnails.capturing_disabled
the preference browser.pagethumbnails.capturing_disabled controls whether the application creates screenshots of visited pages which will be shown if the web page is shown in the grid of the "new tab page" (about:newtab) which offers the most often visited pages for fast navigation.
... 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.
... true (default) the application doesn't create screenshots of visited web pages.
Optimizing Applications For NSPR
create a global thread and call the system call in that thread, and have the primordial thread join that thread.
...the thread that created a stack variable sees his own stack variables correctly across thread switches.
...also, the new socket created by an <tt>pr_accept()</tt> call on a listening socket inherits the mode of the listening socket, and cannot be changed.
I/O Functions
pr_open pr_delete pr_getfileinfo pr_getfileinfo64 pr_rename pr_access type praccesshow functions that act on file descriptors pr_close pr_read pr_write pr_writev pr_getopenfileinfo pr_getopenfileinfo64 pr_seek pr_seek64 pr_available pr_available64 pr_sync pr_getdesctype pr_getspecialfd pr_createpipe directory i/o functions pr_opendir pr_readdir pr_closedir pr_mkdir pr_rmdir socket manipulation functions the network programming interface presented here is a socket api modeled after the popular berkeley sockets.
... pr_createfilemap pr_memmap pr_memunmap pr_closefilemap anonymous pipe function pr_createpipe polling functions this section describes two of the most important polling functions provided by nspr: pr_poll pr_getconnectstatus pollable events a pollable event is a special kind of file descriptor.
...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 ...
Named Shared Memory
shared memory protocol named shared memory functions shared memory protocol using named shared memory functions pr_opensharedmemory creates the shared memory segment, if it does not already exist, or opens a connection with the existing shared memory segment if it already exists.
...pr_opensharedmemory creates file using the name passed in.
...set permissions and or access controls at create and attach time to ensure you get the desired security.
PL_NewHashTable
create a new hash table.
... description pl_newhashtable creates a new hash table.
...you can pass a value of 0 as numbuckets to create the default number of buckets in the new table.
PRDescIdentity
there are three well-known identities: pr_invalid_io_layer, an invalid layer identity, for error return pr_top_io_layer, the identity of the top of the stack pr_nspr_io_layer, the identity used by nspr proper layers are created by pr_getuniqueidentity.
... a string may be associated with a layer when the layer is created.
...there is no way to delete a layer's identity after the layer is created.
PR_GetUniqueIdentity
description a string may be associated with a layer when the layer is created.
...the string can be subsequently passed to pr_createiolayerstub to create a new file descriptor of that layer.
...if you're creating a custom i/o layer, cache the result, and then use that cached result every time you call pr_createiolayerstub.
PR_ImportFileMapFromString
creates a prfilemap from an identifying string.
... syntax #include <prshma.h> nspr_api( prfilemap * ) pr_importfilemapfromstring( const char *fmstring ); parameter the function has the following parameter: fmstring a pointer to string created by pr_exportfilemapasstring.
... description pr_importfilemapfromstring creates a prfilemap object from a string previously created by pr_exportfilemapasstring.
PR_NewLock
creates a new lock.
... if unsuccessful (for example, the lock cannot be created because of resource constraints), null.
... description pr_newlock creates a new opaque lock.
PR_OpenTCPSocket
creates a new tcp socket of the specified address family.
... returns the function returns one of the following values: upon successful completion, a pointer to the prfiledesc object created for the newly opened tcp socket.
...pr_opentcpsocket creates a new tcp socket of the address family af.
PR OpenUDPSocket
creates a new udp socket of the specified address family.
... returns the function returns one of the following values: upon successful completion, a pointer to the prfiledesc object created for the newly opened udp socket.
... pr_openudpsocket creates a new udp socket of the address family af.
PR_ProcessAttrSetInheritableFileMap
prepare filemap for export to my children processes via pr_createprocess.
... syntax #include <prshma.h> nspr_api(prstatus) pr_processattrsetinheritablefilemap( prprocessattr *attr, prfilemap *fm, const char *shmname ); parameters the function has the following parameters: attr pointer to a prprocessattr structure used to pass data to pr_createprocess.
...a subsequent call to pr_createprocess makes the prfilemap importable by the child process.
PR_PushIOLayer
description a file descriptor for a layer (possibly allocated using pr_createiolayerstub) may be pushed onto an existing stack of file descriptors at any time.
...if the original container was allocated using a different mechanism than used by the runtime, the default calling of the layer's destructor by the runtime will fail pr_createiolayerstub is provided to allocate layer objects and template implementations).
...if the containers are allocated by some method other than pr_createiolayerstub, it may be required that the stack have the layers popped off (in reverse order that they were pushed) before calling pr_close.
Process Management and Interprocess Communication
nspr provides routines to create a new process and to wait for the termination of another process.
...the newly-created process executes its program from the beginning.
... process management types and constants the types defined for process management are: prprocess prprocessattr process management functions the process manipulation function fall into these categories: setting the attributes of a new process creating and managing processes setting the attributes of a new process the functions that create and manipulate attribute sets of new processes are: pr_newprocessattr pr_resetprocessattr pr_destroyprocessattr pr_processattrsetstdioredirect pr_processattrsetcurrentdirectory pr_processattrsetinheritablefd creating and managing processes the functions that create and manage processes are: pr_createprocess pr_detachprocess pr_waitprocess pr_killprocess ...
NSS 3.14.1 release notes
nss 3.14.1 source distributions are also available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_14_1_rtm/src/ new in nss 3.14.1 new functionality nss now has the ability to create signed ocsp responses.
... the ability to create signed ocsp responses has been added in nss 3.14.1.
... new functions in ocspt.h cert_createocspsingleresponsegood cert_createocspsingleresponseunknown cert_createocspsingleresponserevoked cert_createencodedocspsuccessresponse cert_createencodedocsperrorresponse new types in ocspt.h ​certocspresponderidtype notable changes in nss 3.14.1 windows ce support has been removed from the code base.
NSS 3.24 release notes
items allocated from the arena are still created on the heap, only the arena itself is stack-allocated.
... in secport.h port_initcheaparena - initializes an arena that was created on the stack.
... (see portcheaparenapool.) port_destroycheaparena - destroys an arena that was created on the stack.
NSS Sample Code Sample_2_Initialization of NSS
* it creates an nss configuration directory with empty databases * and initializes the databases.
...progname + 1 : argv[0]; /* parse command line arguments */ optstate = pl_createoptstate(argc, argv, "d:p:q:f:g:"); while ((status = pl_getnextopt(optstate)) == pl_opt_ok) { switch (optstate->option) { case 'd': dbdir = strdup(optstate->value); break; case 'p': plainpass = strdup(optstate->value); break; case 'f': pwfile = strdup(optstate->value); break; d...
...efault: usage(progname); break; } } pl_destroyoptstate(optstate); if (!dbdir) usage(progname); pr_init(pr_user_thread, pr_priority_normal, 0); /* create the database */ rv = nss_initreadwrite(dbdir); if (rv != secsuccess) { pr_fprintf(pr_stderr, "nss_initialize failed"); pr_cleanup(); exit(rv); } if (pl_strcmp(slotname, "internal") == 0) slot = pk11_getinternalkeyslot(); /* if creating new database, initialize the password.
Initialize NSS database - sample 2
* it creates an nss configuration directory with empty databases * and initializes the databases.
...progname + 1 : argv[0]; /* parse command line arguments */ optstate = pl_createoptstate(argc, argv, "d:p:q:f:g:"); while ((status = pl_getnextopt(optstate)) == pl_opt_ok) { switch (optstate->option) { case 'd': dbdir = strdup(optstate->value); break; case 'p': plainpass = strdup(optstate->value); break; case 'f': pwfile = strdup(optstate->value); break; d...
...efault: usage(progname); break; } } pl_destroyoptstate(optstate); if (!dbdir) usage(progname); pr_init(pr_user_thread, pr_priority_normal, 0); /* create the database */ rv = nss_initreadwrite(dbdir); if (rv != secsuccess) { pr_fprintf(pr_stderr, "nss_initialize failed"); pr_cleanup(); exit(rv); } if (pl_strcmp(slotname, "internal") == 0) slot = pk11_getinternalkeyslot(); /* if creating new database, initialize the password.
FC_Initialize
the pinitargs argument must point to a ck_c_initialize_args structure whose members should have the following values: createmutex should be null.
... ckr_device_error we failed to create the oid tables, random number generator, or internal locks.
... examples #include <assert.h> ck_function_list_ptr pfunctionlist; ck_rv crv; ck_c_initialize_args initargs; crv = fc_getfunctionlist(&pfunctionlist); assert(crv == ckr_ok); initargs.createmutex = null; initargs.destroymutex = null; initargs.lockmutex = null; initargs.unlockmutex = null; initargs.flags = ckf_os_locking_ok; initargs.libraryparameters = "..."; initargs.preserved = null; /* invoke fc_initialize as pfunctionlist->c_initialize */ crv = pfunctionlist->c_initialize(&initargs); see also fc_finalize ...
sslerr.html
ssl_error_md5_digest_failure -12215 "md5 digest function failed." ssl_error_sha_digest_failure -12214 "sha-1 digest function failed." ssl_error_mac_computation_failure -12213 "message authentication code computation failed." ssl_error_sym_key_context_failure -12212 "failure to create symmetric key context." ssl_error_sym_key_unwrap_failure -12211 "failure to unwrap the symmetric key in client key exchange message." ssl_error_iv_param_failure -12209 "pkcs11 code failed to translate an iv into a param." ssl_error_init_cipher_suite_failure -12208 "failed to initialize the selected cipher suite." ssl_error_session_key_gen_fail...
... sec_error_safe_not_created -8122 error while creating safe object.
... sec_error_baggage_not_created -8121 error while creating baggage object.
sslintro.html
if an application will use ssl sockets that handshake as a server, you must specifically create and configure a server cache, using either ssl_configserversessionidcache or ssl_configmpserversidcache.
...a legal nspr socket is required to be passed to ssl_importfd, whether it is created with this function or by another method.
...you can pass this function a model file descriptor to create the new ssl socket with the same configuration state as the model.
Rhino serialization
reading the serialized object back into memory is similarly simple: fileinputstream fis = new fileinputstream(filename); objectinputstream in = new scriptableinputstream(fis, scope); object deserialized = in.readobject(); in.close(); again, we need the scope to create our serialization stream class.
...upon deserialization the initial object and the objects it refers to are all created and the references between the objects are resolved.
... however, for javascript this creates a problem.
Invariants
when a new object is created, it is automatically created in cx->compartment, but its parent and prototype are often determined by examining the scope chain.
...so it is utterly crucially important that this invariant always be true if objects are being created.
... however, there is another internal api, js::switchtocompartment, that lets you break this invariant, and of course in xpconnect we use that from time to time when we know we aren't going to be creating any new objects (other than global objects, which have no parent or prototype) or doing anything that might call back into native code that could create objects.
JS::CompileOptions
use this in code that only needs to access compilation options created elsewhere, like the compiler.
... don't instantiate this class (the constructor is protected anyway); instead, create instances only of the derived classes: compileoptions and owningcompileoptions.
...if you create an instance of this type, it's up to you to guarantee that everything you store in it will outlive it.
JS::GetSelfHostedFunction
this article covers features introduced in spidermonkey 31 create a new javascript function that is implemented in self-hosted javascript.
... description js::getselfhostedfunction creates a new javascript function implemented in self-hosted javascript.
... on success, js::getselfhostedfunction returns a pointer to the newly created function.
JS::NewFunctionFromSpec
create a new function based on the given jsfunctionspec.
... description js::newfunctionfromspec creates a new function based on the given jsfunctionspec, *fs.
... on success, js::newfunctionfromspec returns a pointer to newly created function.
JS::PropertySpecNameToPermanentId
this article covers features introduced in spidermonkey 38 create a jsid that does not need to be marked for gc.
...receives the created id.
... description js::propertyspecnametopermanentid creates a jsid that does not need to be marked for gc from jspropertyspec::name or jsfunctionspec::name.
JSExtendedClass
a c/c++ program can use a jsextendedclass with the js_initclass and js_newobject apis to create objects that have custom methods and properties implemented in c/c++.
...creates and returns a new iterator.
... description to implement a custom class that uses any of the jsextendedclass callbacks: create a jsextendedclass and populate both the base fields and the extended fields.
JSRuntime
once created, a context can be used any number of times for different scripts or jsapi queries.
... for example, a browser might create a separate context for each html page; every script in the page could use the same context.
...there's no fixed association between an object and the context in which it is created.
JS_AddExternalStringFinalizer
the js engine will automatically call this function each time a string created by js_newexternalstring is garbage-collected.
...this is always a string that the application previously created by calling js_newexternalstring.
... description add a finalizer for external strings created by js_newexternalstring using a type-code returned from this function, and that understands how to free or release the memory pointed at by js_getstringchars(str).
JS_ClearNewbornRoots
description the last gc thing of each type (object, string, double, external string types) created on a given context is kept alive until another thing of the same type is created, using a newborn root in the context.
... these newborn roots help native code protect newly-created gc-things from gc invocations activated before those things can be rooted using local or global roots.
...see js_enterlocalrootscope for a better way to manage newborns in cases where native hooks (functions, getters, setters, etc.) create many gc-things, potentially without connecting them to predefined local roots such as *rval or argv[i] in an active jsnative function.
JS_DefineElement
creates a numeric property on a specified object.
...ouble value, unsigned attrs, jsnative getter = nullptr, jsnative setter = nullptr); /* obsolete since jsapi 32 */ js_defineelement(jscontext *cx, jsobject *obj, uint32_t index, jsval value, jspropertyop getter, jsstrictpropertyop setter, unsigned attrs); name type description cx jscontext * the context in which to create the new property.
... obj js::handleobject or jsobject * the object on which to create the new property.
JS_DefineFunction
create a native function and assign it as a property to a specified js object.
...it creates the new function object as though by calling js_newfunction, then makes it a method of obj as though by calling js_defineproperty.
...name is the name of the property to create in obj.
JS_GetExternalStringClosure
this article covers features introduced in spidermonkey 6 returns the string closure stored in a jsstring created by calling js_newexternalstringwithclosure.
...the result is null if the external string was created without one (that is, by calling js_newexternalstring rather than js_newexternalstringwithclosure).
... description to determine if a string was created as an external string, you can call js_isexternalstring.
JS_New
this article covers features introduced in spidermonkey 1.8 create an object as though by using the new keyword and a javascript function.
... syntax jsobject * js_new(jscontext *cx, js::handleobject ctor, const js::handlevaluearray& args); // added in jsapi 32 jsobject * js_new(jscontext *cx, jsobject *ctor, unsigned argc, jsval *argv); // obsolete since jsapi 32 name type description cx jscontext * the context in which to create the new object.
...obsolete since jsapi 32 description js_new creates a new object as though by using the new operator, as described in ecma 262-3 §11.2.2.
JS_NewCompartmentAndGlobalObject
create a new global object in a new compartment.
... syntax jsobject * js_newcompartmentandglobalobject(jscontext *cx, jsclass *clasp, jsprincipals *principals); name type description cx jscontext * the context in which to create the new global object.
... description js_newcompartmentandglobalobject creates a new compartment, and then creates a new global object as the first object in that compartment.
JS_NewContext
create a new jscontext.
... description js_newcontext creates a new jscontext in the runtime rt.
...for sample code that creates and initializes a jscontext, see jsapi user guide.
JS_NewDateObject
this article covers features introduced in spidermonkey 1.8.5 creates a new date object instance for the given time and date.
... syntax jsobject * js_newdateobject(jscontext *cx, int year, int mon, int mday, int hour, int min, int sec); name type description cx jscontext * the context in which to create the new date object.
... description creates and returns a new jsobject representing a javascript date object, which is pre-configured using the specified values.
JS_NewDoubleValue
create a floating-point jsval syntax jsbool js_newdoublevalue(jscontext *cx, jsdouble d, jsval *rval); name type description cx jscontext * the context in which to create the new number.
... description js_newdoublevalue creates a floating-point jsval.
...if it is, js_newdoublevalue creates a bad jsval that might behave as desired in some cases but not others.
JS_NewPlainObject
this article covers features introduced in spidermonkey 38 creates a new plain javascript object.
... syntax jsobject * js_newplainobject(jscontext *cx); name type description cx jscontext * the context in which to create the new object.
... description js_newplainobject creates a new plain object, like new object(), with object.prototype as [[prototype]].
JS_NewScriptObject
syntax jsobject * js_newscriptobject(jscontext *cx, jsscript *script); name type description cx jscontext * the context in which to create the new script object.
... script jsscript * the compiled script for which to create a new script object.
...once you have created a script, you should immediately ensure that its script object is reachable (perhaps by using js_addroot or js_enterlocalrootscope).
JS_NewUCString
syntax jsstring * js_newucstring(jscontext *cx, char16_t *chars, size_t length); jsstring * js_newstring(jscontext *cx, char *buf, size_t length); // obsolete since jsapi 1.8.5 name type description cx jscontext * the context in which to create the new string.
... buf char * or char16_t * pointer to a character array, allocated with js_malloc, containing the characters for the js string to create.
... description js_newstring creates and returns a new string, using the memory starting at buf and ending at buf + length as the character storage.
JS_NewStringCopyN
create a new js string.
... s const char* or const char16_t * pointer to the array of characters containing the text for the js string to create.
...the two functions differ only in the type of the character array s; both functions create ordinary javascript strings, and all javascript strings are made up of 16-bit characters.
JS_ReportErrorNumber
description these functions create a jserrorreport, populate it with an error message obtained from the given jserrorcallback, and either report it to the current error reporter callback or create an error object and set it as the pending exception.
...otherwise, if the jserrorformatstring returned by the jserrorcallback has .exntype == jsexn_none, then the error reporter, if any, is called, and no error object is created.
...the source code seems to say we ignore the .exntype, actually, but surely i'm just missing something.) otherwise, if any javascript code is running in cx (for example, if the caller is a jsnative that was called from a script), then an error object is created and becomes the pending exception.
JS_SetOptions
the former creates a property on the global object.
... the latter creates a property on obj.
... with this flag, both create a global property.
JSAPI reference
d in spidermonkey 24 js_reportoutofmemory js_reportallocationoverflow added in spidermonkey 1.8 js_geterrorreporter js_seterrorreporterobsolete since jsapi 52 js_errorfromexception js_geterrorprototype jsreport_is_exception jsreport_is_strict jsreport_is_warning jsreport_is_strict_mode_error the following functions allow c/c++ functions to throw and catch javascript exceptions: js::createerror added in spidermonkey 38 js_isexceptionpending js_getpendingexception js_setpendingexception js_clearpendingexception js_throwstopiteration added in spidermonkey 1.8 js_isstopiteration added in spidermonkey 31 typedef jsexceptionstate js_saveexceptionstate js_restoreexceptionstate js_dropexceptionstate these functions translate errors into exceptions and vice versa: js_repo...
...for example, js_valuetoobject(cx, s) where s is a string creates a new string wrapper object.
...they never create new objects or call into javascript code.
Zest usecase: Reporting Security Vulnerabilities to Developers
while it will still be necessary to describe vulnerabilities, zest allows security teams to create reproducible test cases which they can then share with the developers.
...ideally security engineers will be able to use their favourite security tools to create zest scripts while developers will be able to rerun those scripts using the tools that they are familiar with.
... in this case the sequence of events could be: the security team discovers a vulnerability using specialist security tools they use those tools to create a zest script which reproduces the problem they hand the script over to the developer the developer adjusts the script to match their local environment they run the script and see the vulnerability they fix the vulnerability they rerun the script to check that the vulnerability is fixed the fix is applied to the system that the security team is testing the security team rerun the script as an initial check they then perform any manual testing they think is necessary note that the developers could also include the script in the regression tests to make sure that it doesnt reoccur.
Secure Development Guidelines
uctions example: sqlite3_stmt *stmt; char *str = "select * from account where name='?'"; sqlite3_prepare_v2(db, str, strlen(str), &stmt, null); sqlite3_bind_text(stmt, 1, name, strlen(name), sqlite_transient); sqlite3_step(stmt); sqlite3_finalize(p_stmt); writing secure code: arithmetic issues integer overflows/underflows overflows occur when an arithmetic operation attempts to create a numeric value that is larger than can be represented within the available storage space max + 1 will be 0 and 0 – 1 will be max!
... i/o a lot can go wrong because a lot can be done with file input and output filenames permissions file handles and descriptors file i/o: filename divided in directories, subdirectories, and the file itself ‘/’ is separator; in windows ‘\’ would work too int openfile(char *file) { handle fh; if (strstr(file, “\”)) return -1; fh = createfilea(file, ...); writefile(fh, data, sizeofdata, null, null); } could be a normal file, directory, device, or link directory traversal (../../../../) file i/o: file permissions should be set correctly be sure not to make world-writable files sensitive files shouldn’t be world readable file i/o: file descriptors and handles could be a race if instances of fh are shared betw...
...erminate strncat() length parameter is very confusing banned api list examples of incorrect strncat usage buffer overflow strncat(buffer, string, sizeof(buffer)); off-by-one strncat(buffer, string, sizeof(buffer) – strlen(string)); correct usage strncat(buffer, string, sizeof(buffer) – strlen(string) – 1)); banned api list: recommendations create wrappers or replacements for standard functions with a bad design libc function name reason to ban it strcpy, strcat, gets, sprintf, vsprintf no bounds checking.
The Places database
moz_hosts: one entry in this table is created each time you visit a new host.
... history tables moz_historyvisits: one entry in this table is created each time you visit a page.
...there are several ways for orphans to be created, including calling markpageastyped and then never visiting the page.
Querying Places
executing a query places queries have several basic parts: the query object: nsinavhistoryquery, holds the search parameters the query options: nsinavhistoryqueryoptions, allows configuration of the search result the history service: nsinavhistoryservice, executes the query the first first step is to create the query and options, and fill them with the parameters you want.
... // |query| and |options| are objects created in the previous section query.setparents([placesutils.bookmarks.toolbarguid], 1); let result = placesutils.history.executequery(query, options); serializing queries query and options objects can be serialized into a string starting with "place:" using queriestoquerystring.
..."\n"); break; case node.result_type_query: var query = node.queryinterface(ci.nsinavhistoryqueryresultnode); dump("query, place uri = " + query.uri + "\n"); break; case node.result_type_folder: // note that folder nodes are of type nsinavhistorycontainerresultnode by default, but // can be qi'd to nsinavhistoryqueryresultnode to access the query and options that // created it.
Using the Places history service
when the user starts browsing (for example, by typing in a link or following a bookmark), a new session id is created.
... break; case historyservice.database_status_create: // database did not exist, a new one has just been created and initialized.
... break; case historyservice.database_status_corrupt: // database was corrupt, has been moved to a .corrupt file and a new one has been created and initialized.
Components.utils.evalInSandbox
the evalinsandbox() function enables you to evaluate javascript code inside a sandbox you've previously created using the components.utils.sandbox constructor.
... use to use evalinsandbox(), you must first create a sandbox object using its constructor, components.utils.sandbox.
... for example: function double(n) { return n * 2; } // create new sandbox instance var mysandbox = new components.utils.sandbox("http://www.example.com/"); mysandbox.y = 5; // insert property 'y' with value 5 into global scope.
Components.utils.exportFunction
this does not have to be the global window object: it could be any other object in the target window, or an object created by the caller.
... returns the placeholder function which has been created in the target context.
... modifying the argument while cloning creates a copy of an object, an xray for an object refers to the original, so any changes to the argument that are made in the exported function will affect the original object that was passed in: // privileged scope: for example, a content script function changemyname(user) { user.name = "bill"; } exportfunction(changemyname, contentwindow, { defineas: "changemyname" }); // less-privileged sco...
NS_NewLocalFile
« xpcom api reference summary the ns_newlocalfile function creates an instance of nsilocalfile that provides a platform independent representation of a file path.
... aresult [out] a reference to the newly created nsilocalfile instance.
... example code // create a local file that references c:\foo.txt nsresult rv; nscomptr<nsilocalfile> file; rv = ns_newlocalfile(nsembedstring(l"c:\\foo.txt"), pr_false, getter_addrefs(file)); if (ns_failed(rv)) return rv; note: gcc requires the -fshort-wchar option to compile this example since prunichar is an unsigned short.
NS_NewNativeLocalFile
« xpcom api reference summary the ns_newnativelocalfile function creates an instance of nsilocalfile that provides a platform independent representation of a file path.
... aresult [out] a reference to the newly created nsilocalfile instance.
... example code // create a local file that references c:\foo.txt nsresult rv; nscomptr<nsilocalfile> file; rv = ns_newnativelocalfile(nsembedcstring("c:\\foo.txt"), pr_false, getter_addrefs(file)); if (ns_failed(rv)) return rv; here, nsembedcstring is used to convert the ascii string literal to an object that can be passed as a const nsacstring& parameter.
mozIJSSubScriptLoader
any top-level functions or variables created by the loaded script via var are created as properties of the targetobj target object (but things declared via let and const are not).
... note: undeclared variables in the loaded script will be created as global variables in the caller (ie.: in the caller's global object).
...note: undeclared variables in the loaded script will be created as global variables in the caller (ie.: in the caller's global object).
mozIRegistry
summary clients will rely on nsrepository to create instances of a given class.
...one way is to create instances by using nsrepository.
... nsrepository is essentially a mapping from xpcom clsids to class factories, plus code to manage that mapping, including functions that create instances of a given clsid.
mozIStorageProgressHandler
see also storage mozstorage introduction and how-to article mozistorageconnection database connection to a specific file or in-memory data storage mozistoragestatement create and execute sql statements on a sqlite database.
...mozistoragefunction create a new sqlite function.
... mozistorageaggregatefunction create a new sqlite aggregate function.
mozIStorageValueArray
see also storage introduction and how-to article mozistorageconnection database connection to a specific file or in-memory data storage mozistoragestatement create and execute sql statements on a sqlite database.
... mozistoragefunction create a new sqlite function.
... mozistorageaggregatefunction create a new sqlite aggregate function.
nsIAccessibleDocument
you can also get one from nsiaccessnode.getaccessibledocument() or nsiaccessibleevent.getaccessibledocument() method overview nsiaccessible getaccessibleinparentchain(in nsidomnode adomnode, in boolean acancreate); obsolete since gecko 2.0 nsiaccessnode getcachedaccessnode(in voidptr auniqueid); native code only!
... nsiaccessible getaccessibleinparentchain( in nsidomnode adomnode, in boolean acancreate ); parameters adomnode the dom node we need an accessible for.
... acancreate if true, this method can create a new accessible.
nsIAlertsService
principal optional the principal of the page that created the alert.
...click here to focus the tab', true, null, notiflistener, 'stackoverflow notifier'); closealert() closes alerts created by the service.
...if no name is provided then only a notification created with no name (if any) will be closed.
nsIAnnotationService
if they haven't visited a page in a couple of months, they probably aren't interested in many other annotations, the positions of things, or other stuff you create, so put that in the weeks policy.
... this means that if you create an annotation on an unvisited uri, it will get deleted when the browser shuts down.
... this means that if you create an annotation on an unvisited uri, it will get deleted when the browser shuts down.
nsIClassInfo
classid nscidptr a classid through which an instance of this class can be created, or null.
... classidnoalloc nscid a classid through which an instance of this class can be created, or null.
...violates the xpcom interface guidelines exceptions thrown ns_error_not_available if the class does not have a classid contractid string a contractid through which an instance of this class can be created, or null.
nsICompositionStringSynthesizer
every instance is associated with a dom window at created by nsidomwindowutils.createcompositionstringsynthesizer().
... to create an instance for this: var domwindowutils = window.windowutils; var compositionstringsynthesizer = domwindowutils.createcompositionstringsynthesizer(); for example, when you create a composition whose composing string is "foo-bar-buzz" and "bar" is selected to convert, then, first, you need to start composition: domwindowutils.sendcompositionevent("compositionstart", "", ""); next, dispatch composition string with crause information and caret information (optional): // set new composition string with .setstring().
...(optional) compositionstringsynthesizer.setcaret("foo-bar".length, 0); // dispatch dom events to modify the focused editor compositionstringsynthesizer.dispatchevent(); when you modify the composing string, you don't need to recreate the instance anymore.
nsIDownloadManager
methods adddownload() creates an nsidownload and adds it to the list of activities being managed by the download manager.
...if you want to both add and start a download, you need to create an nsiwebbrowserpersist object, call this method, set the progresslistener to the returned nsidownload object, and then call the nsiwebbrowserpersist.saveuri() method.
...to be removed at the end of the private browsing session, cached in non-permanent storage, etc.) return value the newly created download item with the passed-in properties.
nsIDynamicContainer
it can also create additional containers for each container, registered to its service.
...the service need not worry about removing any created nodes, they will be automatically removed when this call completes.
... see also places nsinavhistorycontainerresultnode nsinavhistoryqueryoptions nsinavbookmarksservice.createdynamiccontainer() ...
nsIEditor
ocument doc, in nsicontent aroot, in nsiselectioncontroller aselcon, in unsigned long aflags); void setattributeorequivalent(in nsidomelement element, in astring sourceattrname, in astring sourceattrvalue, in boolean asuppresstransaction); void removeattributeorequivalent(in nsidomelement element, in domstring sourceattrname, in boolean asuppresstransaction); void postcreate(); void predestroy(in boolean adestroyingframes); selected content removal void deleteselection(in short action, in short stripwrappers); document info and file methods void resetmodificationcount(); long getmodificationcount(); void incrementmodificationcount(in long amodcount); void incrementmodificationcount(in long amodco...
..., out boolean canredo); void begintransaction(); void endtransaction(); void beginplaceholdertransaction(in nsiatom name); void endplaceholdertransaction(); boolean shouldtxnsetselection(); void setshouldtxnsetselection(in boolean should); inline spellchecking methods nsiinlinespellchecker getinlinespellchecker(in boolean autocreate); void syncrealtimespell(); void setspellcheckuseroverride(in boolean enable); clipboard methods void cut(); boolean cancut(); void copy(); boolean cancopy(); void paste(in long aselectiontype); boolean canpaste(in long aselectiontype); selection methods void selectall(); void beginningofdo...
...tr,in astring attvalue); boolean getattributevalue(in nsidomelement aelement, in astring attributestr, out astring resultvalue); void removeattribute(in nsidomelement aelement, in astring aattribute); void cloneattribute(in astring aattribute, in nsidomnode asourcenode); void cloneattributes(in nsidomnode destnode, in nsidomnode sourcenode); nsidomnode createnode(in astring tag, in nsidomnode parent, in long position); void insertnode(in nsidomnode node, in nsidomnode parent, in long aposition); void splitnode(in nsidomnode existingrightnode, in long offset, out nsidomnode newleftnode); void joinnodes(in nsidomnode leftnode, in nsidomnode rightnode, in nsidomnode parent); void deletenode(in nsidomnode child); ...
nsIHttpServer
an example : https://github.com/laurentj/slimerjs/blob/master/src/modules/webserver.jsm var exported_symbols = ["create"]; components.utils.import("resource://gre/modules/services.jsm"); function create() { var server = components.classes["@mozilla.org/server/jshttp;1"] .createinstance(components.interfaces.nsihttpserver); return { get objectname () { return "webserver"; }, /** * @param integer|string port port or "host:port" * @param object opt optional options.
... [host, port] = port.split(':'); port = parseint(port); server.identity.add('http', host, port); } server.wrappedjsobject._start(port, host); return true; }, registerfile: function(path, filepath) { var file = components.classes['@mozilla.org/file/local;1'] .createinstance(components.interfaces.nsilocalfile); file.initwithpath(filepath); return server.registerfile(path, file); }, registerdirectory : function(path, directorypath) { var file = components.classes['@mozilla.org/file/local;1'] .createinstance(components.interfaces.nsilocalfile); file.initwithpath(directo...
...rypath); return server.registerdirectory(path, file); }, registerpathhandler: function(path, handlercallback) { server.registerpathhandler(path, function (request, response) { var req = createhttprequest(request); var resp = new httpresponse(response); handlercallback(req, resp); }); }, registerprefixhandler: function(prefix, handlercallback) { server.registerprefixhandler(prefix, function (request, response) { var req = createhttprequest(request); var resp = new httpresponse(response); handlercallback(req, resp); }); }, close: function(){ server.stop(f...
nsIINIParser
inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) typically, you'll create an nsiiniparser object by calling nsiiniparserfactory.createiniparser().
... */ function getinivalue (inifile, section, prop) { var inifact = components.manager.getclassobjectbycontractid( "@mozilla.org/xpcom/ini-parser-factory;1", components.interfaces.nsiiniparserfactory ); var iniparser = inifact.createiniparser(inifile); try { return iniparser.getstring(section,prop); } catch(e) { return undefined; } } // usage: var lang = getinivalue(file,"setting","language"); enumerating sections this example gets a list of all the sections in the ini file.
...// get all keys for the "setting" section var keysenum = iniparser.getkeys("setting"); // save the keys and values in an object var keys = {}; while (keysenum && keysenum.hasmore()) { var key = keysenum.getnext(); // create a property for each key and assing the ini value.
nsIINIParserWriter
to create an nsiiniparserwriter object, you use the nsiiniparserfactory interface to create a parser, then nsisupports.queryinterface() that to get an nsiiniparserwriter, like this: let writer = components.classes["@mozilla.org/xpcom/ini-processor-factory;1"].
... .getservice(components.interfaces.nsiiniparserfactory) .createiniparser(somelocalfile) .queryinterface(components.interfaces.nsiiniparserwriter); here, somelocalfile is an nsifile based object, such as an nsilocalfile.
... once the writer object is created, you can use the setstring() method to set the value of a property within a given section; the section is created if it hasn't been yet.
nsIJetpack
*/); void registerreceiver(in astring amessagename, in jsval areceiver); void unregisterreceiver(in astring amessagename, in jsval areceiver); void unregisterreceivers(in astring amessagename); void evalscript(in astring ascript); nsivariant createhandle(); void destroy(); methods sendmessage() this method asynchronously sends a message to the jetpack process.
... createhandle() this creates an opaque handle that can transparently be exchanged between processes.
... nsivariant createhandle(); parameters none.
nsILoginInfo
to create and manage logins use nsiloginmanager.
...to create an instance, use: var logininfo = components.classes["@mozilla.org/login-manager/logininfo;1"] .createinstance(components.interfaces.nsilogininfo); method overview nsilogininfo clone(); boolean equals(in nsilogininfo alogininfo); void init(in astring ahostname, in astring aformsubmiturl, in astring ahttprealm, in astring ausername, in astring apassword, in astring ausernamefield, in astring apasswordfield); boolean matches(in nsilogininfo alogininfo, in boolea...
... init() initializes a newly created nsilogininfo object.
nsILoginMetaInfo
this data can usually be ignored by most users of the login manager, which will create and maintain appropriate default values.
...this can be any arbitrary string, but a format as created by nsiuuidgenerator is recommended.
... for example, "{d4e1a1f6-5ea0-40ee-bff5-da57982f21cf}" timecreated unsigned long long the time, in unix epoch milliseconds, when the login was first created.
nsIMicrosummaryService
s removed in gecko 6.0 (firefox 6.0 / thunderbird 6.0 / seamonkey 2.3) implemented by: @mozilla.org/microsummary/service;1 as a service: var microsummaryservice = components.classes["@mozilla.org/microsummary/service;1"] .getservice(components.interfaces.nsimicrosummaryservice); method overview void addgenerator(in nsiuri generatoruri); nsimicrosummary createmicrosummary(in nsiuri pageuri, in nsiuri generatoruri); nsisimpleenumerator getbookmarks(); nsimicrosummarygenerator getgenerator(in nsiuri generatoruri); nsimicrosummaryset getmicrosummaries(in nsiuri pageuri, in long long bookmarkid); nsimicrosummary getmicrosummary(in long long bookmarkid); boolean hasmicrosummary(in long long bookmarkid); ...
... createmicrosummary() create a microsummary for a given page uri and generator uri.
... nsimicrosummary createmicrosummary( in nsiuri pageuri, in nsiuri generatoruri ); parameters pageuri the uri of the page to be summarized.
nsINavHistoryService
if the uri does not have an entry in the history database already, one will be created with no visits, no title, hidden, not typed.
... aisredirect true if the given visit redirects to somewhere else (that is you will create a visit out of here that is a redirect transition).
... return value returns the id of the created visit.
nsIPrefService
using a set method on this object will always create or set a user preference value.
...using a set method on this object will always create or set a default preference value.
... note: few consumers will want to create default branch objects.
nsIPromptService
a delay can be useful not only to give the user more time to think before acting, but also as a countermeasure against malicious web sites that intentionally create a race condition whereby the user intends to click or type a key responding, for example, to the web site's prompt but the security dialog pops up unexpectedly and its button is unintentionally activated.
...the following example creates a dialog with an ok button and a custom button description.
...prompt-service;1"] .getservice(components.interfaces.nsipromptservice); var check = {value: false}; // default the checkbox to false var flags = prompts.button_pos_0 * prompts.button_title_save + prompts.button_pos_1 * prompts.button_title_is_string + prompts.button_pos_2 * prompts.button_title_cancel; // this value of flags will create 3 buttons.
nsISHistory
inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) in an embedded browser environment, the nsiwebbrowser object creates an instance of session history for each open window.
...in a non-embedded situation, the owner of the session history component must create a instance of it and set it in the nsiwebnavigation object.
...to create an instance, use: var shistory = components.classes["@mozilla.org/browser/shistory;1"] .createinstance(components.interfaces.nsishistory); method overview void addshistorylistener(in nsishistorylistener alistener); nsishentry getentryatindex(in long index, in boolean modifyindex); void purgehistory(in long numentries); void reloadcurrententry(); void removeshistorylistener(in nsishistorylistener alistener); attributes attribute type description count long the number of toplevel documents currently available in session history.
nsIScriptError
to create an instance, use: var scripterror = components.classes["@mozilla.org/scripterror;1"] .createinstance(components.interfaces.nsiscripterror); note: the nsiscripterror2 interface was merged into this interface in gecko 12.0.
... timestamp long long elapsed time, in milliseconds, from a platform-specific zero time to the time the message was created.
... function mylogtoconsole(amessage, asourcename, asourceline, alinenumber, acolumnnumber, aflags, acategory) { var consoleservice = components.classes["@mozilla.org/consoleservice;1"] .getservice(components.interfaces.nsiconsoleservice); var scripterror = components.classes["@mozilla.org/scripterror;1"] .createinstance(components.interfaces.nsiscripterror); scripterror.init(amessage, asourcename, asourceline, alinenumber, acolumnnumber, aflags, acategory); consoleservice.logmessage(scripterror); } categories there are a lot of categories, and they're not all maintained in a single list anywhere in the code.
nsISecurityCheckedComponent
method overview string cancallmethod(in nsiidptr iid, in wstring methodname); string cancreatewrapper(in nsiidptr iid); string cangetproperty(in nsiidptr iid, in wstring propertyname); string cansetproperty(in nsiidptr iid, in wstring propertyname); methods cancallmethod() returns a capability string indicating what permissions are required to call the specified method on the given interface.
...cancreatewrapper() returns a string indicating what permissions are required to create a wrapper for the given interface.
... string cancreatewrapper( in nsiidptr iid ); parameters iid the interface to reflect into javascript.
nsIServiceManager
unlike createinstance, this will always return the same object each time it is called with the same arguments.
... return value true if the service has already been created.
... return value true if the service has already been created.
nsISmsDatabaseService
to create an instance, use: var smsservice = components.classes["@mozilla.org/sms/smsdatabaseservice;1"] .createinstance(components.interfaces.nsismsdatabaseservice); method overview long savereceivedmessage(in domstring asender, in domstring abody, in unsigned long long adate); long savesentmessage(in domstring areceiver, in domstring abody, in unsigned long long adate); void getmessage(in long messageid, in ...
...long requestid, [optional] in unsigned long long processid); void deletemessage(in long messageid, in long requestid, [optional] in unsigned long long processid); void createmessagelist(in nsidommozsmsfilter filter, in boolean reverse, in long requestid, [optional] in unsigned long long processid); void getnextmessageinlist(in long listid, in long requestid, [optional] in unsigned long long processid); void clearmessagelist(in long listid); void markmessageread(in long messageid, in boolean value, in long requestid, [optional] in unsigned long long processid) methods savereceivedmessage() void savereceivedmessage( in domstring asender, in domstring abody, in unsigned long long adate ); parameters asender a domstring with the sender of the text message.
... createmessagelist() void createmessagelist( in nsidommozsmsfilter filter, in boolean reverse, in long requestid, [optional] in unsigned long long processid ); parameters filter a smsfilter to filter out sms messages from a list.
nsIThread
to create a thread, use the nsithreadmanager interface.
...instead, you must only call it from another thread (usually the thread that created it, or the main application thread).
... exceptions thrown ns_error_unexpected shutdown() was erroneously called from within the thread itself, the thread was not created with the thread manager's nsithreadmanager.newthread() method, or the thread is already in the process of being shut down.
nsIThreadPoolListener
last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) inherits from: nsisupports method overview void onthreadcreated(); void onthreadshuttingdown(); methods onthreadcreated() called when a new thread is created by the thread pool.
... the notification happens on the newly created thread.
... void onthreadcreated(); parameters none.
nsITransferable
to create an instance, use: var transferable = components.classes["@mozilla.org/widget/transferable;1"] .createinstance(components.interfaces.nsitransferable); it's important to note that a flavor, which specifies a type of data the transferable supports, is represented by a null-terminated string indicating the mime type of the format supported by the flavor.
... isprivatedata boolean although this is not a read-only attribute, you should generally avoid changing it, since doing so may cause it not to actually reflect the status of the context in which the transferable was created.
... requestingnode nsidomnode the source dom node this transferable was created from.
nsIWorkerFactory
dom/interfaces/threads/nsidomworkers.idlscriptable creates and returns a new worker 1.0 66 introduced gecko 2.0 obsolete gecko 8.0 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) this interface was removed in gecko 8.0.
... you don't need to use it anymore to create workers from chrome.
...to create an instance, use: var workerfactory = components.classes['@mozilla.org/threads/workerfactory;1'] .createinstance(components.interfaces.nsiworkerfactory); method overview nsiworker newchromeworker(in domstring ascripturl); methods newchromeworker() returns a new chromeworker that will run a specified script.
nsIXULTemplateQueryProcessor
the template builder creates the query processor, and there is no other means to retrieve it.
...the template builder creates the query processor, and there is no other means to retrieve it.
...this method must only be called with results that were created by this query processor.
nsIXULTemplateResult
a result is expected to only be created by a query processor.
...the dom element created for this result, if any, will have its id attribute set to this value.
...the query must always be one that was compiled by the query processor that created this result.
Setting HTTP request headers
observers to get notified about some topic (like "http-on-modify-request") we need to create an observer.
...registering after we've created the observer, we need to register it.
...4-c1631bd1be1c}"), myprogid: "@dougt/myhttplistener;1", myname: "simple http listener", myfactory: { queryinterface: function (aiid) { if (!aiid.equals(components.interfaces.nsisupports) && !aiid.equals(components.interfaces.nsifactory)) throw components.results.ns_error_no_interface; return this; }, createinstance: function (outer, iid) { log("----------------------------> createinstance"); return new myhttplistener(); } }, canunload: function(compmgr) { return true; } }; function nsgetmodule(compmgr, filespec) { return mymodule; } privacy and security good practice a use case for setting specific a http request header is to have a specific w...
Cached compose window FAQ
instead of destroying the mail compose window on send (or close) just to create a new one the next time, mozilla mail will "cache" the compose window on send (or close), and use that instead.
... any new window performance problems that mozilla has are especially painful in mail compose, as we need to create a new compose window on every new mail message or reply.
... if the user has this usage pattern, we wouldn't have to create a new window.
Creating a gloda message query
this content covers features introduced in thunderbird 3 this page describes how to programmatically create a message query using gloda, thunderbird's global database.
...you can find the file, which includes doxygen markup of sorts, here: https://hg.mozilla.org/comm-central/file/tip/mailnews/db/gloda/modules/gloda.js components.utils.import("resource:///modules/gloda/public.js"); create the query let query = gloda.newquery(gloda.noun_message); add constraints to the query each constraint function takes one or more arguments which are "or"ed together.
... create a collection from the query your listener is notified as messages are added to the collection as the database query completes.
Filelink Providers
if the nsimsgcloudfileprovider is being created as part of an add-on, the add-on must register the component in chrome.manifest.
... the account setup dialog the account setup dialog allows the user to select what account type they would like to create from a menulist.
... management interface once an account has been created, it is manageable from within the preferences dialog, in the attachment pane, in the outgoing tab.
Building a Thunderbird extension 2: extension file layout
when this tutorial is finished, our extension will look like this: myfirstext.xpi: //created in step 8 /install.rdf //created in step 3 /chrome.manifest //created in step 4 /chrome/ /content/ /content/myhelloworld.xul //created in step 5 /content/overlay.js //created in step 6 /chrome/locale/* //building an extension# l...
... to start with the tutorial, manually create the initial directory structure for the extension as it is depicted above in a folder called myfirstext@jen.zed.
... this directory could be created anywhere on your filesystem.
Building a Thunderbird extension 5: XUL
example xul overlay document create a new file called myhelloworld.xul within the content folder you created earlier with the following content: <?xml version="1.0"?> <overlay id="sample" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="application/javascript" src="chrome://myfirstext/content/overlay.js"/><!-- a reference to your javascript file --> <statusbar id="status-bar"> <statusbarpane...
...in the example above we have defined a new <statusbarpanel> item (that can be referred to as my-panel) which will create a new instance of this widget type and add it at the end of the statusbar.
... the overlay.js file will be created in a later section and your add-on will still work if the file is missing.
Use SQLite
this will create an sqlite db named tbird.sqlite inside your profile directory with a table called attachments.
... getservice(ci.mozistorageservice); var dbconnection; if (!dbfile.exists()) dbconnection = this._dbcreate(dbservice, dbfile); else { dbconnection = dbservice.opendatabase(dbfile); } this.dbconnection = dbconnection; }, _dbcreate: function(adbservice, adbfile) { var dbconnection = adbservice.opendatabase(adbfile); this._dbcreatetables(dbconnection); return dbconnection; }, _dbcreatetables: function(adbconnection) { for(var name in this.dbschema.tables) ...
... adbconnection.createtable(name, this.dbschema.tables[name]); }, }; window.addeventlistener("load", function(e) { tbirdsqlite.onload(e); }, false); this is another practical sample on how to handle opendatabase and sql queries on the client side, using in-memory (blob) storage of 2mb: var db = opendatabase('mydb', '1.0', 'test db', 2 * 1024 * 1024); var msg; db.transaction(function (tx) { tx.executesql('create table if not exists logs (id unique, log)'); tx.executesql('insert into logs (id, log) values (1, "foobar")'); tx.executesql('insert into logs (id, log) values (2, "logmsg")'); msg = '<p>log message created and row inserted.</p>'; document.queryselector('#status').innerhtml = msg; }); db.transaction(function (tx) { tx.executesql('select * from logs', [], function (tx, res...
Virtualenv
virtualenv tools virtualenv does one thing well: creates isolated virtual environments of python packages.
...python project for local installation; https://bitbucket.org/kumar303/velcro/ virtualenvwrapper: a set of extensions to ian bicking’s virtualenv tool for creating isolated python development environments; http://www.doughellmann.com/projects...tualenvwrapper the mozilla-central virtualenv in order to make use of various python modules located throughout mozilla-central, a virtualenv is created as part of the build process: http://mxr.mozilla.org/mozilla-central/source/js/src/build/autoconf/python-virtualenv.m4 .
... the virtualenv is created in ${objdir}/_virtualenv and should be recreated as part of the configure step.
Using Objective-C from js-ctypes
nsstring literals another objective-c syntax used is the @"..." literal, which creates nsstring instance.
...to create a block with js-ctypes, use the function: function createblock(afunctypeptr) { /** * creates a c block instance from a js function.
...<< 29, block_has_signature: 1 << 30 }; // based on work from here: https://github.com/trueinteractions/tint2/blob/f6ce18b16ada165b98b07869314dad1d7bee0252/modules/bridge/core.js#l370-l394 var bl = block_literal_1(); // set the class of the instance bl.isa = _nsconcreteglobalblock; // global flags bl.flags = block_const.block_has_stret; bl.reserved = 0; bl.invoke = afunctypeptr; // create descriptor var desc = block_descriptor_1(); desc.reserved = 0; desc.size = block_literal_1.size; // set descriptor into block literal bl.descriptor = desc.address(); return bl; } an example of this function in use can be seen here: _ff-addon-snippet-objc_monitorevents - shows how to monitor and block mouse and key events on mac os x ...
Declaring types
for example, to define a new 32-bit integer variable with the value 5: var i = ctypes.int32_t(5); you can then pass a pointer to this value to a c function that requires a pointer to a 32-bit integer, like this: some_c_function(i.address()); declaring new primitive types there are times when you want to create new types that are simply new names for existing primitive types.
...you can, optionally, leave out the field descriptor array; this creates an opaque structure whose contents are not defined.
...for example, to create a type for an array of c standard i/o file pointers (perhaps for tracking a number of active files on disk): const file = new ctypes.structtype("file").ptr; // create file as a file * type const filearray = new ctypes.arraytype(file); // create a filearray type in this example, file is an opaque pointer we can use to refer to c file records, as defined in stdio.h.
ctypes.open
there are two options: custom native file (dll, so, dylib, etc.) standard os libraries custom native file for this method, a native file must be created.
... a native file for use on unix systems is an so file, which is created and a c function called add() is written.
... int add(int a, int b) { return a + b; } to make this a shared library, a native file which can be loaded and used from js-ctypes, compile it with these commands: gcc -fpic -c mycfuntionsforunix.c gcc -shared -o mycfuntionsforunix.so mycfuntionsforunix.o a file named mycfuntionsforunix.so is successfully created.
Using js-ctypes
instead, you'll need to create a shim library that uses c functions that then call into the c++ library for you.
...e ); /* https://developer.apple.com/library/mac/documentation/corefoundation/reference/cftyperef/#//apple_ref/c/func/cfrelease * void cfrelease ( * cftyperef cf * ); */ var cfrelease = libcf.declare('cfrelease', ctypes.default_abi, void, // return cftyperef // cf ); /* https://developer.apple.com/library/mac/documentation/corefoundation/reference/cfstringref/#//apple_ref/c/func/cfstringcreatewithcharacters * cfstringref cfstringcreatewithcharacters ( * cfallocatorref alloc, * const unichar *chars, * cfindex numchars * ); */ var cfstringcreatewithcharacters = libcf.declare('cfstringcreatewithcharacters', ctypes.default_abi, cfstringref, // return cfallocatorref, // alloc unichar.ptr, // *chars cfindex // numchars ); // helper functions function makecfstr(jsstr) {...
... // js str is just a string // returns a cfstr that must be released with cfrelease when done return cfstringcreatewithcharacters(null, jsstr, jsstr.length); } // main var mycfstrs = { head: makecfstr('core foundation says...'), body: makecfstr('we just called the equivalent of the "standardalert carbon function" for 64bit osx from javascript!') }; var rez = cfusernotificationdisplaynotice(0, kcfusernotificationcautionalertlevel, null, null, null, mycfstrs.head, mycfstrs.body, null); console.info('rez:', rez, rez.tostring(), uneval(rez)); // cfusernotificationdisplaynotice does not block till user clicks dialog, it will return immediately if (rez.tostring() == '0') { console.log('notification was succesfully shown!!'); } else { console.error('failed to show notification...
ctypes
the ctypes object contains methods and predefined data types used to create and manage a library.
... examples example of structtype() on windows let's say we need tb_button, this type needs to be created.
...so we will figure that out and create the structure appropriately.
Flash Activation: Browser Comparison - Plugins
even if the plugin element will eventually be hidden, pages should create the plugin element so that it's visible on the page, and should resize or hide it only after the user has activated the plugin.
... this can be done by calling a javascript function when the plugin is activated: function plugincreated() { // we don't need to see the plugin, so hide it by resizing var plugin = document.getelementbyid('myplugin'); plugin.height = 0; plugin.width = 0; plugin.callpluginmethod(); } the html, by default, specifies the flash object to be a size that makes it visible, like this: <!-- give the plugin an initial size so it is visible --> <object type="application/x-shockwave-flash" data="myapp.swf" id="myplugin" width="300" height="300"> <param name="callback" value="plugincreated()"> </object> the callback parameter defined in the html can be called in flash using its flash.external.externalinterface api.
... first, set your up your html with a callback that calls the javascript function plugincreated(), like this: <object type="application/x-my-plugin" data="somedata.mytype" id="myplugin"> <param name="callback" value="plugincreated()"> </object> the plugincreated() function is then responsible for the setup of your script and any calls back into the plugin that you need to make: function plugincreated() { document.getelementbyid('myplugin').callpluginmethod(); } ...
URLs - Plugins
if the browser cannot locate the url and retrieve the data, it does not create a stream for the instance; in this case, the plug-in receives notification of the result.
...if the target parameter is set to null, the application creates a new stream and delivers the data to the plug-in instance, through calls to npp_newstream, npp_writeready and npp_write, and npp_destroystream.
...safest target, even though, when used with a mailto or news url, this creates an extra blank browser instance.
Gecko Plugin API Reference - Plugins
s unix event handling for windowed plug-ins windowless plug-ins specifying that a plug-in is windowless invalidating the drawing area forcing a paint message making a plug-in opaque making a plug-in transparent creating 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 ...
... npn_geturl asks the browser to create a stream for the specified url.
... accessing browser objects from a plugin how to call plugin native methods the api extensions npstring npvariant npn_releasevariantvalue npn_getstringidentifier npn_getstringidentifiers npn_getintidentifier npn_identifierisstring npn_utf8fromidentifier npn_intfromidentifier npobject npn_createobject npn_retainobject npn_releaseobject npn_invoke npn_invokedefault npn_evaluate npn_getproperty npn_setproperty npn_removeproperty npn_hasproperty npn_hasmethod npn_setexception npclass structures npanycallbackstruct npbyterange npembedprint npevent npfullprint npp np_port npprint npprintcallbackstruct nprect...
Debugger.Environment - Firefox Developer Tools
spidermonkey creates debugger.environment instances as needed as the debugger inspects stack frames and function objects; calling debugger.environment as a function or constructor raises a typeerror exception.
... spidermonkey creates exactly one debugger.environment instance for each environment it presents via a given debugger instance: if the debugger encounters the same environment through two different routes (perhaps two functions have closed over the same environment), spidermonkey presents the same debugger.environment instance to the debugger each time.
...function calls, calls to eval, let blocks, catch blocks, and the like create declarative environment records.
DevTools API - Firefox Developer Tools
toolbox-ready(toolbox) a new toolbox has been created and is ready to use.
...the frame is the <iframe> element that has been created for the tool.
... id: "inspector", icon: "chrome://browser/skin/devtools/inspector-icon.png", url: "chrome://browser/content/devtools/inspector/inspector.xul", get label() { let strings = services.strings.createbundle("chrome://browser/locale/devtools/inspector.properties"); return strings.getstringfromname("inspector.label"); }, istargetsupported: function(target) { return !target.isremote; }, build: function(iframewindow, toolbox, node) { return new inspectorpanel(iframewindow, toolbox, node); } }); open a tool, or select it if the toolbox is already open: let target = target...
Monster example - Firefox Developer Tools
ar 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.
... specifically: the code creates an object with three properties, each an array: one for fierce monsters one for friendly monsters one for monsters who haven't decided yet.
... for each array, the code creates and appends 5000 randomly-initialized monsters.
Tree map view - Firefox Developer Tools
here are some example snapshots, as they appear in the tree map view: this treemap is from the dom allocation example, which simply runs a script that creates a large number of dom nodes (200 htmldivelement objects and 4000 htmlspanelement objects).
... you can see how almost all the heap usage is from the htmlspanelement objects that it creates.
... this treemap is from the monster allocation example, which creates three arrays, each containing 5000 monsters, each monster having a randomly-generated name.
Edit Shape Paths in CSS - Firefox Developer Tools
the shape path editor is a tool that helps you see and edit shapes created using clip-path and also the css shape-outside property and <basic-shape> values.
... understanding the lines drawn by the editor once you have selected a shape on your page, the shape path editor will draw lines to help you understand the path that is being created.
...you can then copy these values back into your stylesheet to create the new, tweaked shape path.
Style Editor - Firefox Developer Tools
the style editor enables you to: view and edit all the stylesheets associated with a page create new stylesheets from scratch and apply them to the page import existing stylesheets and apply them to the page to open the style editor choose the "style editor" option from the "web developer" menu (which is a submenu in the "tools" menu on the mac).
... the media sidebar works especially well with responsive design view for creating and debugging responsive layouts: from firefox 46 onwards, if an @media rule contains a screen size in a condition, then it is made clickable: clicking it then resizes the screen to that size using the responsive design view: creating and importing style sheets you can create a new style sheet by clicking the new button in the toolbar.
... source map support web developers often create css files using a preprocessor like sass, less, or stylus.
AbortController - Web APIs
you can create a new abortcontroller object using the abortcontroller.abortcontroller() constructor.
... constructor abortcontroller() creates a new abortcontroller object instance.
... we first create a controller using the abortcontroller() constructor, then grab a reference to its associated abortsignal object using the abortcontroller.signal property.
AnalyserNode.getByteFrequencyData() - Web APIs
syntax var audioctx = new audiocontext(); var analyser = audioctx.createanalyser(); var dataarray = new uint8array(analyser.frequencybincount); // uint8array should be the same length as the frequencybincount void analyser.getbytefrequencydata(dataarray); // fill the uint8array with data returned from getbytefrequencydata() parameters array the uint8array that the frequency domain data will be copied to.
... example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input.
... var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); ...
AnalyserNode.getByteTimeDomainData() - Web APIs
syntax const audioctx = new audiocontext(); const analyser = audioctx.createanalyser(); const dataarray = new uint8array(analyser.fftsize); // uint8array should be the same length as the fftsize analyser.getbytetimedomaindata(dataarray); // fill the uint8array with data returned from getbytetimedomaindata() parameters array the uint8array that the time domain data will be copied to.
... return value void | none example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input.
... const audioctx = new (window.audiocontext || window.webkitaudiocontext)(); const analyser = audioctx.createanalyser(); ...
AnalyserNode.getFloatTimeDomainData() - Web APIs
syntax var audioctx = new audiocontext(); var analyser = audioctx.createanalyser(); var dataarray = new float32array(analyser.fftsize); // float32array needs to be the same length as the fftsize analyser.getfloattimedomaindata(dataarray); // fill the float32array with data returned from getfloattimedomaindata() parameters array the float32array that the time domain data will be copied to.
... example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input.
... var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); ...
Animation - Web APIs
WebAPIAnimation
constructor animation() creates a new animation object instance.
...if they are indefinite (i.e., forwards-filling), this can result in a huge animations list, which could create a memory leak.
... consider providing a mechanism for pausing or disabling animation, as well as using the reduced motion media query to create a complimentary experience for users who have expressed a preference for no animated experiences.
AnimationEvent.initAnimationEvent() - Web APIs
summary the animationevent.initanimationevent() method initializes an animation event created using the deprecated document.createevent("animationevent") method.
... animationevent created this way are untrusted.
...do not use this method; instead, use the standard constructor, animationevent(), to create a synthetic animationevent.
AudioParam.setValueAtTime() - Web APIs
starttime a double representing the time (in seconds) after the audiocontext was first created that the change in value will happen.
...when the buttons are pressed, the currgain variable is incremented/decremented by 0.25, then the setvalueattime() method is used to set the gain value equal to currgain, one second from now (audioctx.currenttime + 1.) // create audio context var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); // set basic variables for example var myaudio = document.queryselector('audio'); var pre = document.queryselector('pre'); var myscript = document.queryselector('script'); pre.innerhtml = myscript.innerhtml; var targetattimeplus = document.queryselector('.set-target-at-time-plu...
...s'); var targetattimeminus = document.queryselector('.set-target-at-time-minus'); // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a gain node and set it's gain value to 0.5 var gainnode = audioctx.creategain(); gainnode.gain.value = 0.5; var currgain = gainnode.gain.value; // connect the audiobuffersourcenode to the gainnode // and the gainnode to the destination source.connect(gainnode); gainnode.connect(audioctx.destination); // set buttons to do something onclick targetattimeplus.onclick = function() { currgain += 0.25; gainnode.gain.setvalueattime(currgain, audioctx.currenttime + 1); } targetattimeminus.onclick = function() { currgain -= 0.25; gainnode.gain.setvalueattime(currgain, au...
AudioParam.setValueCurveAtTime() - Web APIs
starttime a double representing the time (in seconds) after the audiocontext was first created that the change in value will happen.
... examples in this example, we have a media source with a single button (see the webaudio-examples repo for the source code, or view the example live.) when this button is pressed, setvaluecurveattime() is used to change the gain value between the values contained in the wavearray array: // create audio context var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); // set basic variables for example var myaudio = document.queryselector('audio'); var pre = document.queryselector('pre'); var myscript = document.queryselector('script'); pre.innerhtml = myscript.innerhtml; var valuecurve = document.queryselector('.value-curve'); // create a ...
...mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a gain node and set it's gain value to 0.5 var gainnode = audioctx.creategain(); gainnode.gain.value = 0.5; var currgain = gainnode.gain.value; // connect the audiobuffersourcenode to the gainnode // and the gainnode to the destination source.connect(gainnode); gainnode.connect(audioctx.destination); // set button to do something onclick var wavearray = new float32array(9); wavearray[0] = 0.5; wavearray[1] = 1; wavearray[2] = 0.5; wavearray[3] = 0; wavearray[4] = 0.5; wavearray[5] = 1; wavearray[6] = 0.5; wavearray[7] = 0; wavearray[8] = 0.5; valuecurve.onclick = function() { gainnode.gain.setvaluecurveattime(wavearray, audioctx.currenttime, 2); } specificat...
AudioProcessingEvent - Web APIs
the number of channels is defined as a parameter, numberofinputchannels, of the factory method audiocontext.createscriptprocessor().
...the number of channels is defined as a parameter, numberofoutputchannels, of the factory method audiocontext.createscriptprocessor().
... note: for a full working example, see our script-processor-node github repo (also view the source code.) var myscript = document.queryselector('script'); var mypre = document.queryselector('pre'); var playbutton = document.queryselector('button'); // create audiocontext and buffer source var audioctx = new audiocontext(); source = audioctx.createbuffersource(); // create a scriptprocessornode with a buffersize of 4096 and a single input and output channel var scriptnode = audioctx.createscriptprocessor(4096, 1, 1); console.log(scriptnode.buffersize); // load in an audio track via xhr and decodeaudiodata function getdata() { request = new xmlhtt...
AudioWorkletGlobalScope.registerProcessor - Web APIs
a new processor by the given name is internally created and associated with the new node.
... examples in this example we create a custom audioworkletnode that outputs silence.
... // test-processor.js class testprocessor extends audioworkletprocessor { process (inputs, outputs, parameters) { return true } } registerprocessor('test-processor', testprocessor) next, in our main script file we'll load the processor, create an instance of audioworkletnode — passing it the processor name that we used when calling registerprocessor — and connect it to an audio graph.
AudioWorkletNode.parameters - Web APIs
there we've created a simple node which outputs white noise.
... here, additionally, we'll create a custom gain parameter, so we can directly change volume of the output (although you could use gainnode to achieve this as well).
... } }) return true } } registerprocessor('white-noise-processor', whitenoiseprocessor) next, in our main scripts file we'll load the processor, create an instance of audioworkletnode passing it the name of the processor, and connect the node to an audio graph.
AudioWorkletProcessor() - Web APIs
the audioworkletprocessor() constructor creates a new audioworkletprocessor object, which represents an underlying audio processing mechanism of an audioworkletnode.
...instead, they are created only internally by the creation of an associated audioworkletnodes.
... // test-processor.js class testprocessor extends audioworkletprocessor { constructor (options) { super() console.log(options.numberofinputs) console.log(options.processoroptions.someusefulvariable) } process (inputs, outputs, parameters) { return true } } registerprocessor('test-processor', testprocessor) next, in our main script file we'll load the processor, create an instance of audioworkletnode passing it the name of the processor and options object.
AuthenticatorAttestationResponse.attestationObject - Web APIs
as part of the credentialscontainer.create() call, an authenticator will create a new keypair as well as an attestationobject for that keypair.
... the public key that corresponds to the private key that has created the attestation signature is well known; however, there are various well known attestation public key chains for different ecosystems (for example, android or tpm attestations).
... examples var publickey = { challenge: /* from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(16), name: "jdoe@example.com", displayname: "john doe" }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { var attestationobj = newcredentialinfo.response.attestationobject; // this will be a cbor encoded arraybuffer // do something with the response // (sending it back to the relying party server maybe?) }).catch(function (err) { console.error(err); }); specifications specification status comment ...
AuthenticatorAttestationResponse - Web APIs
the authenticatorattestationresponse interface of the web authentication api is returned by credentialscontainer.create() when a publickeycredential is passed, and provides a cryptographic root of trust for the new key pair that has been generated.
... authenticatorattestationresponse.attestationobject secure contextread only an arraybuffer containing authenticator data and an attestation statement for a newly-created key pair.
... examples var publickey = { challenge: /* from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(16), name: "jdoe@example.com", displayname: "john doe" }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { var response = newcredentialinfo.response; // do something with the response // (sending it back to the relying party server maybe?) }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials lev...
AuthenticatorResponse.clientDataJSON - Web APIs
the clientdatajson property of the authenticatorresponse interface stores a json string in an arraybuffer, representing the client data that was passed to credentialscontainer.create() or credentialscontainer.get().
... properties after the clientdatajson object is converted from an arraybuffer to a javascript object, it will have the following properties: type a string which is either "webauthn.get" when an existing credential is retrieved or "webauthn.create" when a new credential is created.
... examples function arraybuffertostr(buf) { return string.fromcharcode.apply(null, new uint8array(buf)); } // pk is a publickeycredential that is the result of a create() or get() promise var clientdatastr = arraybuffertostr(pk.clientdatajson); var clientdataobj = json.parse(clientdatastr); console.log(clientdataobj.type); // "webauthn.create" or "webauthn.get" console.log(clientdataobj.challenge); // base64 encoded string containing the original challenge console.log(clientdataobj.origin); // the window.origin specifications specification ...
BiquadFilterNode.Q - Web APIs
syntax var audioctx = new audiocontext(); var biquadfilter = audioctx.createbiquadfilter(); biquadfilter.q.value = 100; note: though the audioparam returned is read-only, the value it represents is not.
... example the following example shows basic usage of an audiocontext to create a biquad filter node.
... var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); //set up the different audio nodes we will use for the app var analyser = audioctx.createanalyser(); var distortion = audioctx.createwaveshaper(); var gainnode = audioctx.creategain(); var biquadfilter = audioctx.createbiquadfilter(); var convolver = audioctx.createconvolver(); // connect the nodes together source = audioctx.createmediastreamsource(stream); source.connect(analyser); analyser.connect(distortion); distortion.connect(biquadfilter); biquadfilter.connect(convolver); convolver.connect(gainnode); gainnode.connect(audioctx.destination); // manipulate the biquad filter biquadfilter.type = "lowshelf"; biquadf...
BiquadFilterNode.detune - Web APIs
syntax var audioctx = new audiocontext(); var biquadfilter = audioctx.createbiquadfilter(); biquadfilter.detune.value = 100; note: though the audioparam returned is read-only, the value it represents is not.
... example the following example shows basic usage of an audiocontext to create a biquad filter node.
... var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); //set up the different audio nodes we will use for the app var analyser = audioctx.createanalyser(); var distortion = audioctx.createwaveshaper(); var gainnode = audioctx.creategain(); var biquadfilter = audioctx.createbiquadfilter(); var convolver = audioctx.createconvolver(); // connect the nodes together source = audioctx.createmediastreamsource(stream); source.connect(analyser); analyser.connect(distortion); distortion.connect(biquadfilter); biquadfilter.connect(convolver); convolver.connect(gainnode); gainnode.connect(audioctx.destination); // manipulate the biquad filter biquadfilter.type = "lowshelf"; biquadf...
BiquadFilterNode.frequency - Web APIs
syntax var audioctx = new audiocontext(); var biquadfilter = audioctx.createbiquadfilter(); biquadfilter.frequency.value = 3000; note: though the audioparam returned is read-only, the value it represents is not.
... example the following example shows basic usage of an audiocontext to create a biquad filter node.
... var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); //set up the different audio nodes we will use for the app var analyser = audioctx.createanalyser(); var distortion = audioctx.createwaveshaper(); var gainnode = audioctx.creategain(); var biquadfilter = audioctx.createbiquadfilter(); var convolver = audioctx.createconvolver(); // connect the nodes together source = audioctx.createmediastreamsource(stream); source.connect(analyser); analyser.connect(distortion); distortion.connect(biquadfilter); biquadfilter.connect(convolver); convolver.connect(gainnode); gainnode.connect(audioctx.destination); // manipulate the biquad filter biquadfilter.type = "lowshelf"; biquadf...
BiquadFilterNode.gain - Web APIs
syntax var audioctx = new audiocontext(); var biquadfilter = audioctx.createbiquadfilter(); biquadfilter.gain.value = 25; note: though the audioparam returned is read-only, the value it represents is not.
... example the following example shows basic usage of an audiocontext to create a biquad filter node.
... var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); //set up the different audio nodes we will use for the app var analyser = audioctx.createanalyser(); var distortion = audioctx.createwaveshaper(); var gainnode = audioctx.creategain(); var biquadfilter = audioctx.createbiquadfilter(); var convolver = audioctx.createconvolver(); // connect the nodes together source = audioctx.createmediastreamsource(stream); source.connect(analyser); analyser.connect(distortion); distortion.connect(biquadfilter); biquadfilter.connect(convolver); convolver.connect(gainnode); gainnode.connect(audioctx.destination); // manipulate the biquad filter biquadfilter.type = "lowshelf"; biquadf...
BiquadFilterNode.type - Web APIs
syntax var audioctx = new audiocontext(); var biquadfilter = audioctx.createbiquadfilter(); biquadfilter.type = 'lowpass'; value a string (enum) representing a biquadfiltertype.
... not used example the following example shows basic usage of an audiocontext to create a biquad filter node.
... var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); //set up the different audio nodes we will use for the app var analyser = audioctx.createanalyser(); var distortion = audioctx.createwaveshaper(); var gainnode = audioctx.creategain(); var biquadfilter = audioctx.createbiquadfilter(); var convolver = audioctx.createconvolver(); // connect the nodes together source = audioctx.createmediastreamsource(stream); source.connect(analyser); analyser.connect(distortion); distortion.connect(biquadfilter); biquadfilter.connect(convolver); convolver.connect(gainnode); gainnode.connect(audioctx.destination); // manipulate the biquad filter biquadfilter.type = "lowshelf"; biquadf...
Body.arrayBuffer() - Web APIs
WebAPIBodyarrayBuffer
if you need to play ogg during downloading (stream it) - consider htmlaudioelement: new audio("music.ogg").play(); in getdata() we create a new request using the request() constructor, then use it to fetch an ogg music track.
... we also use audiocontext.createbuffersource to create an audio buffer source.
... once getdata() has finished running, we start the audio source playing with start(0), then disable the play button so it can't be clicked again when it is already playing (this would cause an error.) function getdata() { source = audioctx.createbuffersource(); var myrequest = new request('viper.ogg'); fetch(myrequest).then(function(response) { return response.arraybuffer(); }).then(function(buffer) { audioctx.decodeaudiodata(buffer, function(decodeddata) { source.buffer = decodeddata; source.connect(audioctx.destination); }); }); }; // wire up buttons to stop and play audio play.onclick = function() { ...
Body.bodyUsed - Web APIs
WebAPIBodybodyUsed
example in our fetch request example (run fetch request live), we create a new request using the request() constructor, then use it to fetch a jpg.
... when the fetch is successful, we read a blob out of the response using blob(), put it into an object url using url.createobjecturl, and then set that url as the source of an <img> element to display the image.
...="https://udn.realityripple.com/samples/46/29059a2b39.png"> js content var myimage = document.queryselector('.my-image'); fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/delete_key1.jpg').then(function(response) { console.log(response.bodyused); var res = response.blob(); console.log(response.bodyused); return res; }).then(function(response) { var objecturl = url.createobjecturl(response); myimage.src = objecturl; }); specifications specification status comment fetchthe definition of 'bodyused' in that specification.
Body.json() - Web APIs
WebAPIBodyjson
example in our fetch json example (run fetch json live), we create a new request using the request() constructor, then use it to fetch a .json file.
... const mylist = document.queryselector('ul'); const myrequest = new request('products.json'); fetch(myrequest) .then(response => response.json()) .then(data => { for (const product of data.products) { let listitem = document.createelement('li'); listitem.appendchild( document.createelement('strong') ).textcontent = product.name; listitem.append( ` can be found in ${ product.location }.
... cost: ` ); listitem.appendchild( document.createelement('strong') ).textcontent = `£${product.price}`; mylist.appendchild(listitem); } }) .catch(console.error); specifications specification status comment fetchthe definition of 'body.json()' in that specification.
CSSMathSum - Web APIs
a cssmathsum is the object type returned when the stylepropertymapreadonly.get() method is used on a css property whosevalue is created with a calc() function.
... constructor cssmathsum.cssmathsum() creates a new cssmathsum object.
... examples we create an element with a width determined using a calc() function, then console.log() the operator and values, and dig into the values a bit.
CSSStyleSheet - Web APIs
a cssstylesheet object is created and inserted into the document's document.stylesheets list automatically by the browser, when a stylesheet is loaded for a document.
... as the stylesheet list cannot be modified directly, there's no useful way to create a new cssstylesheet object manually (although constructable stylesheet objects is coming to the web platform soon and is already supported in blink).
... to create a new stylesheet, insert a <style> or <link> element into the document.
CSS Painting API - Web APIs
concepts and usage essentially, the css painting api contains functionality allowing developers to create custom values for paint(), a css <image> function.
... examples to draw directly into an element's background using javascript in our css, we define a paint worklet using the registerpaint() function, tell the document to include the worklet using the paintworklet addmodule() method, then include the image we created using the css paint() function.
... we create our paintworklet called 'hollowhighlights' using the registerpaint() function: registerpaint('hollowhighlights', class { static get inputproperties() { return ['--boxcolor']; } static get inputarguments() { return ['*','<length>']; } static get contextoptions() { return {alpha: true}; } paint(ctx, size, props, args) { const x = 0; const y = size.height * 0.3; const blockwidth = size.width * 0.33; const blockheight = size.height * 0.85; const thecolor = props.get( '--boxcolor' ); const stroketype = args[0].tostring(); const strokewidth = parseint(args[1]); console.log(thecolor); if ( strokewidth ) { ctx.linewidth = strokewidth; } else { ctx.linewidth = 1.0; } if ( stroketype === 'stroke' ) { ctx.fillstyle = 'transparent'; ctx.stro...
CacheStorage - Web APIs
cachestorage.open() returns a promise that resolves to the cache object matching the cachename (a new cache is created if it doesn't already exist.) cachestorage.delete() finds the cache object matching the cachename, and if found, deletes the cache object and returns a promise that resolves to true.
...this consists of calling cachestorage.open to create a new cache, then using cache.addall to add a series of assets to it.
... if not, fetch the request from the network, then also open the cache created in the first block and add a clone of the request to it using cache.put (cache.put(event.request, response.clone()).) if this fails (e.g.
CanvasRenderingContext2D.arcTo() - Web APIs
without arcto(), these two segments would form a sharp corner: arcto() creates a circular arc that fits this corner and smooths is out.
...5; ctx.moveto(200, 20); ctx.arcto(200,130, 50,20, 40); ctx.stroke(); // start point ctx.beginpath(); ctx.fillstyle = 'blue'; ctx.arc(200, 20, 5, 0, 2 * math.pi); ctx.fill(); // control points ctx.beginpath(); ctx.fillstyle = 'red'; ctx.arc(200, 130, 5, 0, 2 * math.pi); // control point one ctx.arc(50, 20, 5, 0, 2 * math.pi); // control point two ctx.fill(); result in this example, the path created by arcto() is thick and black.
... creating a rounded corner this example creates a rounded corner using arcto().
CanvasRenderingContext2D.beginPath() - Web APIs
call this method when you want to create a new path.
... note: to create a new sub-path, i.e., one matching the current canvas state, you can use canvasrenderingcontext2d.moveto().
... syntax void ctx.beginpath(); examples creating distinct paths this example creates two paths, each of which contains a single line.
CanvasRenderingContext2D.filter - Web APIs
it defines the value of the standard deviation to the gaussian function, i.e., how many pixels on the screen blend into each other; thus, a larger value will create more blur.
...a value of 0% will create an image that is completely black, while a value of 100% leaves the input unchanged.
...a value of 0% will create a drawing that is completely black.
CanvasRenderingContext2D.rect() - Web APIs
note: to both create and render a rectangle in one step, use the fillrect() or strokerect() methods.
... syntax void ctx.rect(x, y, width, height); the rect() method creates a rectangular path whose starting point is at (x, y) and whose size is specified by width and height.
... examples drawing a rectangle this example creates a rectangular path using the rect() method.
Advanced animations - Web APIs
to draw the ball, we will create a ball object which contains properties and a draw() method to paint it on the canvas.
...if you replace this method with a semi-transparent fillrect, you can easily create a trailing effect.
... breakout this short chapter only explains some techniques to create more advanced animations.
Canvas tutorial - Web APIs
this can, for instance, be used to draw graphs, combine photos, or create simple (and not so simple) animations.
... the images on this page show examples of <canvas> implementations which will be created in this tutorial.
...in order to draw graphics on the canvas we use a javascript context object, which creates graphics on the fly.
Channel Messaging API - Web APIs
channel messaging concepts and usage a message channel is created using the messagechannel() constructor.
... once created, the two ports of the channel can be accessed through the messagechannel.port1 and messagechannel.port2 properties (which both return messageport objects.) the app that created the channel uses port1, and the app at the other end of the port uses port2 — you send a message to port2, and transfer the port over to the other browsing context using window.postmessage along with two arguments (the message to send, and the object to transfer ownership of, in this case the port itself.) when these transferable objects are transferred, they are 'neutered' on the previous context — the one they previously belonged to.
... channel messaging interfaces messagechannel creates a new message channel to send messages across.
CloseEvent - Web APIs
constructor closeevent() creates a new closeevent.
... 1000 normal closure normal closure; the connection successfully completed whatever purpose for which it was created.
... closeevent.initcloseevent() initializes the value of a closeevent created.
Console.groupCollapsed() - Web APIs
creates a new inline group in the web console.
... unlike console.group(), however, the new group is created collapsed.
... the user will need to use the disclosure button next to it to expand it, revealing the entries created in the group.
ConstantSourceNode() - Web APIs
the constantsourcenode() constructor creates a new constantsourcenode object instance, representing an audio source which constantly outputs samples whose values are always the same.
... example in this example, an audio context is created, then a constantsourcenode is established with its offset initialized to 0.5.
... let audiocontext = new audiocontext(); let myconstantsource = new constantsourcenode(audiocontext, { offset: 0.5 }); note: the new constantsourcenode created by the constructor has a channelcount of 2.
ConvolverNode.normalize - Web APIs
syntax var audioctx = new audiocontext(); var convolver = audioctx.createconvolver(); convolver.normalize = false; value a boolean.
... example var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var convolver = audioctx.createconvolver(); ...
...dio track via xhr for convolver node var soundsource, concerthallbuffer; ajaxrequest = new xmlhttprequest(); ajaxrequest.open('get', 'concert-crowd.ogg', true); ajaxrequest.responsetype = 'arraybuffer'; ajaxrequest.onload = function() { var audiodata = ajaxrequest.response; audioctx.decodeaudiodata(audiodata, function(buffer) { concerthallbuffer = buffer; soundsource = audioctx.createbuffersource(); soundsource.buffer = concerthallbuffer; }, function(e){"error with decoding audio data" + e.err}); } ajaxrequest.send(); ...
DOMHighResTimeStamp - Web APIs
it's calculated like this: if the script's global object is a window, the time origin is determined as follows: if the current document is the first one loaded in the window, the time origin is the time at which the browser context was created.
... if the script's global object is a workerglobalscope (that is, the script is running as a web worker), the time origin is the moment at which the worker was created.
... usage notes you can get the current timestamp value—the time that has elapsed since the context was created—by calling the performance method now().
DOMMatrix() - Web APIs
the dommatrix constructor creates a new dommatrix object which represents 4x4 matrices, suitable for 2d and 3d operations..
... syntax var dommatrix = new dommatrix([init]) parameters init optional a string containing a sequence of numbers or an array of numbers specifying the matrix you want to create, or a css transform string.
... example this example creates a dommatrix to use as an argument for calling point.matrixtransform().
DOMMatrixReadOnly.scale() - Web APIs
the scale() method of the dommatrixreadonly interface creates a new matrix being the result of the original matrix with a scale transform applied.
... examples this svg contains three squares, one red, one blue, and one green, each positioned at the document origin: <svg width="250" height="250" viewbox="0 0 25 25"> <rect width="25" height="25" fill="red" /> <rect id="transformed" width="25" height="25" fill="blue" /> <rect id="transformedorigin" width="25" height="25" fill="green" /> </svg> this javascript first creates an identity matrix, then uses the scale() method to create a new matrix with a single parameter.
... we then create a new matrix scaled about a given origin, using either three or six parameters depending on the browser support.
DOMPoint.fromPoint() - Web APIs
the static dompoint method frompoint() creates and returns a new mutable dompoint object given a source point.
... you can also create a new dompoint object using the new dompoint() constructor.
... examples creating a mutable point from a read-only point if you have a dompointreadonly object, you can easily create a mutable copy of that point: var mutablepoint = dompoint.frompoint(readonlypoint); creating a 2d point this sample creates a 2d point, specifying an inline object that includes the values to use for x and y.
DOMPoint.DOMPoint() - Web APIs
WebAPIDOMPointDOMPoint
the dompoint() constructor creates and returns a new dompoint object, given the values for some or all of its properties.
... you can also create a dompoint by calling the dompoint.frompoint() static function.
... examples this example creates a dompoint representing the top-left corner of the current window, then creates a second point based on the first, which is then offset by 100 pixels both vertically and horizontally.
DOMPoint - Web APIs
WebAPIDOMPoint
constructor dompoint() creates and returns a new dompoint object given the values of zero or more of its coordinate components and optionally the w perspective value.
... you can also use an existing dompoint or dompointreadonly or a dompointinit dictionary to create a new point by calling the dompoint.frompoint() static method.
... static methods dompoint.frompoint() creates a new mutable dompoint object given an existing point (or a dompointinit dictionary) which provides the values for its properties.
DataTransferItemList.add() - Web APIs
the datatransferitemlist.add() method creates a new datatransferitem using the specified data and adds it to the drag data list.
...if the item is successfully added to the list, the newly-created datatransferitem object is returned.
...if the drag item couldn't be created (for example, if the associated datatransfer object has no data store), null is returned.
DeprecationReportBody - Web APIs
examples in our deprecation_report.html example, we create a simple reporting observer to observe usage of deprecated features on our web page: let options = { types: ['deprecation'], buffered: true } let observer = new reportingobserver(function(reports, observer) { reportbtn.onclick = () => displayreports(reports); }, options); we then tell it to start observing reports using reportingobserver.observe(); this tells the observer to start collec...
... the report details are displayed via the displayreports() fuction, which takes the observer callback's reports parameter as its parameter: function displayreports(reports) { const outputelem = document.queryselector('.output'); const list = document.createelement('ul'); outputelem.appendchild(list); for(let i = 0; i < reports.length; i++) { let listitem = document.createelement('li'); let textnode = document.createtextnode('report ' + (i + 1) + ', type: ' + reports[i].type); listitem.appendchild(textnode); let innerlist = document.createelement('ul'); listitem.appendchild(innerlist); list.appendchild(listitem); for...
... (let key in reports[i].body) { let innerlistitem = document.createelement('li'); let keyvalue = reports[i].body[key]; innerlistitem.textcontent = key + ': ' + keyvalue; innerlist.appendchild(innerlistitem); } } } the reports parameter contains an array of all the reports in the observer's report queue.
Examples of web and XML development using the DOM - Web APIs
ad> <meta charset="utf-8"/> <title>show event properties</title> <style> table { border-collapse: collapse; } thead { font-weight: bold; } td { padding: 2px 10px 2px 10px; } .odd { background-color: #efdfef; } .even { background-color: #ffffff; } </style> <script> function showeventproperties(e) { function addcell(row, text) { var cell = row.insertcell(-1); cell.appendchild(document.createtextnode(text)); } var e = e || window.event; document.getelementbyid('eventtype').innerhtml = e.type; var table = document.createelement('table'); var thead = table.createthead(); var row = thead.insertrow(-1); var lablelist = ['#', 'property', 'value']; var len = lablelist.length; for (var i=0; i<len; i++) { addcell(row, lablelist[i]); } var tbody = document.createe...
... to add a row and some cells to an existing table: <table id="table0"> <tr> <td>row 0 cell 0</td> <td>row 0 cell 1</td> </tr> </table> <script> var table = document.getelementbyid('table0'); var row = table.insertrow(-1); var cell, text; for (var i = 0; i < 2; i++) { cell = row.insertcell(-1); text = 'row ' + row.rowindex + ' cell ' + i; cell.appendchild(document.createtextnode(text)); } </script> notes a table's innerhtml property should never be used to modify a table, although you can use it to write an entire table or the content of a cell.
... if dom core methods document.createelement and node.appendchild are used to create rows and cells, ie requires that they are appended to a tbody element, whereas other browsers will allow appending to a table element (the rows will be added to the last tbody element).
DynamicsCompressorNode.attack - Web APIs
syntax var audioctx = new audiocontext(); var compressor = audioctx.createdynamicscompressor(); compressor.attack.value = 0; value an audioparam.
... example the below code demonstrates a simple usage of createdynamicscompressor() to add compression to an audio track.
... // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a compressor node var compressor = audioctx.createdynamicscompressor(); compressor.threshold.setvalueattime(-50, audioctx.currenttime); compressor.knee.setvalueattime(40, audioctx.currenttime); compressor.ratio.setvalueattime(12, audioctx.currenttime); compressor.attack.setvalueattime(0, audioctx.currenttime); compressor.release.setvalueattime(0.25, audioctx.currenttime); // connect the audiobuffersourcenode to the destination source.connect(audioctx.destination); button.onclick = function() { var active = button.getattribute('data-active'); if(activ...
DynamicsCompressorNode.knee - Web APIs
syntax var audioctx = new audiocontext(); var compressor = audioctx.createdynamicscompressor(); compressor.knee.value = 40; value an audioparam.
... example the below code demonstrates a simple usage of createdynamicscompressor() to add compression to an audio track.
... // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a compressor node var compressor = audioctx.createdynamicscompressor(); compressor.threshold.setvalueattime(-50, audioctx.currenttime); compressor.knee.setvalueattime(40, audioctx.currenttime); compressor.ratio.setvalueattime(12, audioctx.currenttime); compressor.attack.setvalueattime(0, audioctx.currenttime); compressor.release.setvalueattime(0.25, audioctx.currenttime); // connect the audiobuffersourcenode to the destination source.connect(audioctx.destination); button.onclick = function() { var active = button.getattribute('data-active'); if(activ...
DynamicsCompressorNode.ratio - Web APIs
syntax var audioctx = new audiocontext(); var compressor = audioctx.createdynamicscompressor(); compressor.ratio.value = 12; value an audioparam.
... example the below code demonstrates a simple usage of createdynamicscompressor() to add compression to an audio track.
... // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a compressor node var compressor = audioctx.createdynamicscompressor(); compressor.threshold.setvalueattime(-50, audioctx.currenttime); compressor.knee.setvalueattime(40, audioctx.currenttime); compressor.ratio.setvalueattime(12, audioctx.currenttime); compressor.attack.setvalueattime(0, audioctx.currenttime); compressor.release.setvalueattime(0.25, audioctx.currenttime); // connect the audiobuffersourcenode to the destination source.connect(audioctx.destination); button.onclick = function() { var active = button.getattribute('data-active'); if(activ...
DynamicsCompressorNode.release - Web APIs
syntax var audioctx = new audiocontext(); var compressor = audioctx.createdynamicscompressor(); compressor.release.value = 0.25; value an audioparam.
... example the below code demonstrates a simple usage of createdynamicscompressor() to add compression to an audio track.
... // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a compressor node var compressor = audioctx.createdynamicscompressor(); compressor.threshold.setvalueattime(-50, audioctx.currenttime); compressor.knee.setvalueattime(40, audioctx.currenttime); compressor.ratio.setvalueattime(12, audioctx.currenttime); compressor.attack.setvalueattime(0, audioctx.currenttime); compressor.release.setvalueattime(0.25, audioctx.currenttime); // connect the audiobuffersourcenode to the destination source.connect(audioctx.destination); button.onclick = function() { var active = button.getattribute('data-active'); if(activ...
DynamicsCompressorNode.threshold - Web APIs
syntax var audioctx = new audiocontext(); var compressor = audioctx.createdynamicscompressor(); compressor.threshold.value = -50; value an audioparam.
... example the below code demonstrates a simple usage of createdynamicscompressor() to add compression to an audio track.
... // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a compressor node var compressor = audioctx.createdynamicscompressor(); compressor.threshold.setvalueattime(-50, audioctx.currenttime); compressor.knee.setvalueattime(40, audioctx.currenttime); compressor.ratio.setvalueattime(12, audioctx.currenttime); compressor.attack.setvalueattime(0, audioctx.currenttime); compressor.release.setvalueattime(0.25, audioctx.currenttime); // connect the audiobuffersourcenode to the destination source.connect(audioctx.destination); button.onclick = function() { var active = button.getattribute('data-active'); if(activ...
Element.animate() - Web APIs
WebAPIElementanimate
the element interface's animate() method is a shortcut method which creates a new animation, applies it to the element, then plays the animation.
... it returns the created animation object instance.
... examples in the demo down the rabbit hole (with the web animation api), we use the convenient animate() method to immediately create and play an animation on the #tunnel element to make it flow upwards, infinitely.
Element.innerHTML - Web APIs
WebAPIElementinnerHTML
if the element whose contents are being replaced is a <template> element, then the <template> element's content attribute is replaced with the new documentfragment created in step 1.
... example this example uses innerhtml to create a mechanism for logging messages into a box on a web page.
... javascript function log(msg) { var logelem = document.queryselector(".log"); var time = new date(); var timestr = time.tolocaletimestring(); logelem.innerhtml += timestr + ": " + msg + "<br/>"; } log("logging mouse events inside this container..."); the log() function creates the log output by getting the current time from a date object using tolocaletimestring(), and building a string with the timestamp and the message text.
FileEntrySync - Web APIs
basic concepts to write content to file, create a filewriter object by calling createwriter().
... method overview filewritersync createwriter () raises (fileexception); file file () raises (fileexception); methods createwriter() creates a new filewriter associated with the file that the fileentry represents.
... void createwriter ( ) raises (fileexception); parameter none.
File and Directory Entries API - Web APIs
you can develop apps which read, write, and create files and/or directories in a virtual, sandboxed file system.
... filesystemdirectoryreader created by calling filesystemdirectoryentry.createreader(), this interface provides the functionality which lets you read the contents of a directory.
... filesystemdirectoryreadersync created by calling filesystemdirectoryentrysync.createreader(), this interface provides the functionality which lets you read the contents of a directory.
GainNode.gain - Web APIs
WebAPIGainNodegain
syntax var audioctx = new audiocontext(); var gainnode = audioctx.creategain(); gainnode.gain.value = 0.5; value an audioparam.
... example the following example shows basic usage of an audiocontext to create a gainnode, which is then used to mute and unmute the audio when a mute button is clicked by changing the gain property value.
... the below snippet wouldn't work as is — for a complete working example, check out our voice-change-o-matic demo (view source.) <div> <button class="mute">mute button</button> </div> var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var gainnode = audioctx.creategain(); var mute = document.queryselector('.mute'); var source; if (navigator.mediadevices.getusermedia) { navigator.mediadevices.getusermedia ( // constraints - only audio needed for this app { audio: true }, // success callback function(stream) { source = audioctx.createmediastreamsource(stream); }, // error callback function(err) { console.log('the following gum error occured: ' + err); } ); } else { console.log('getusermedia not supported on your browse...
Audio() - Web APIs
the audio() constructor creates and returns a new htmlaudioelement which can be either attached to a document for the user to interact with and/or listen to, or can be used offscreen to manage and play audio.
... usage notes you can also use other element-creation methods, such as the document object's createelement() method, to construct a new htmlaudioelement.
... the event-based approach is best: myaudioelement.addeventlistener("canplaythrough", event => { /* the audio is now playable; play it if permissions allow */ myaudioelement.play(); }); memory usage and management if all references to an audio element created using the audio() constructor are deleted, the element itself won't be removed from memory by the javascript runtime's garbage collection mechanism if playback is currently underway.
HTMLAudioElement - Web APIs
ement" target="_top"><rect x="131" y="65" width="160" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="211" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmlaudioelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor audio() creates and returns a new htmlaudioelement object, optionally starting the process of loading an audio file into it if the file url is given.
... mozcurrentsampleoffset() returns the number of samples form the beginning of the stream that have been written so far into the audio stream created by calling mozwriteaudio().
... examples basic usage you can create a htmlaudioelement entirely with javascript using the audio() constructor: var audioelement = new audio('car_horn.wav'); then you can invoke the play() method on the element audioelement.play(); a common gotcha is trying to play an audio element immediately on page load.
HTMLImageElement.crossOrigin - Web APIs
example in this example, a new <img> element is created and added to the document, loading the image with the anonymous state; the image will be loaded using cors and credentials will be used for all cross-origin loads.
... javascript the code below demonstrates setting the crossorigin property on an <img> element to configure cors access for the fetch of a newly-created image.
... const imageurl = "https://mdn.mozillademos.org/files/16797/clock-demo-400px.png"; const container = document.queryselector(".container"); function loadimage(url) { const image = new image(200, 200); image.addeventlistener("load", () => container.prepend(image) ); image.addeventlistener("error", () => { const errmsg = document.createelement("output"); errmsg.value = `error loading image at ${url}`; container.append(errmsg); }); image.crossorigin = "anonymous"; image.alt = ""; image.src = url; } loadimage(imageurl); html <div class="container"> <p>here's a paragraph.
HTMLImageElement - Web APIs
ct x="331" y="65" width="160" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="411" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmlimageelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor image() the image() constructor creates and returns a new htmlimageelement object representing an html <img> element which is not attached to any dom tree.
...when called without parameters, new image() is equivalent to calling document.createelement("img").
... example var img1 = new image(); // image constructor img1.src = 'image1.png'; img1.alt = 'alt'; document.body.appendchild(img1); var img2 = document.createelement('img'); // use dom htmlimageelement img2.src = 'image2.jpg'; img2.alt = 'alt text'; document.body.appendchild(img2); // using first image in the document alert(document.images[0].src); specifications specification status comment css object model (cssom) view modulethe definition of 'extensions to htmlimageelement' in that specification.
HTMLScriptElement - Web APIs
examples dynamically importing scripts let's create a function that imports new scripts within a document creating a <script> node immediately before the <script> that hosts the following code (through document.currentscript).
... function loaderror(oerror) { throw new urierror("the script " + oerror.target.src + " didn't load correctly."); } function prefixscript(url, onloadfunction) { var newscript = document.createelement("script"); newscript.onerror = loaderror; if (onloadfunction) { newscript.onload = onloadfunction; } document.currentscript.parentnode.insertbefore(newscript, document.currentscript); newscript.src = url; } this next function, instead of prepending the new scripts immediately before the document.currentscript element, appends them as children of the <head> tag.
... function loaderror(oerror) { throw new urierror("the script " + oerror.target.src + " didn't load correctly."); } function affixscripttohead(url, onloadfunction) { var newscript = document.createelement("script"); newscript.onerror = loaderror; if (onloadfunction) { newscript.onload = onloadfunction; } document.head.appendchild(newscript); newscript.src = url; } sample usage: affixscripttohead("myscript1.js"); affixscripttohead("myscript2.js", function () { alert("the script \"myscript2.js\" has been correctly loaded."); }); specifications specification status comment html living standardthe definition of 'htmlscriptelement' in that specification.
HTMLSelectElement.add() - Web APIs
examples creating elements from scratch var sel = document.createelement("select"); var opt1 = document.createelement("option"); var opt2 = document.createelement("option"); opt1.value = "1"; opt1.text = "option: value 1"; opt2.value = "2"; opt2.text = "option: value 2"; sel.add(opt1, null); sel.add(opt2, null); /* produces the following, conceptually: <select> <option value="1">option: value 1</option> <option value="2">option: value 2</option...
... append to an existing collection var sel = document.getelementbyid("existinglist"); var opt = document.createelement("option"); opt.value = "3"; opt.text = "option: value 3"; sel.add(opt, null); /* takes the existing following select object: <select id="existinglist"> <option value="1">option: value 1</option> <option value="2">option: value 2</option> </select> and changes it to: <select id="existinglist"> <option value="1">option: value 1</option> <option value="2">option: value 2</option> <option value="3">option: value 3</option> </select> */ the before parameter is optional.
... inserting to an existing collection var sel = document.getelementbyid("existinglist"); var opt = document.createelement("option"); opt.value = "3"; opt.text = "option: value 3"; sel.add(opt, sel.options[1]); /* takes the existing following select object: <select id="existinglist"> <option value="1">option: value 1</option> <option value="2">option: value 2</option> </select> and changes it to: <select id="existinglist"> <option value="1">option: value 1</option> <option value="3">option: value 3</option> <option value="2">option: value 2</option> </select> */ specifications specification status comment html living standardthe definition of 'htmlselectelement.add()' in that sp...
HTMLTableElement.insertRow() - Web APIs
the row does not need to be appended separately as would be the case if document.createelement() had been used to create the new <tr> element.
...(to be valid html, a <tr> must have at least one <td> element.) finally, we add some text to the cell using document.createtextnode() and node.appendchild().
...row 2</td></tr> <tr><td>row 3</td></tr> </table> javascript function addrow(tableid) { // get a reference to the table let tableref = document.getelementbyid(tableid); // insert a row at the end of the table let newrow = tableref.insertrow(-1); // insert a cell in the row at index 0 let newcell = newrow.insertcell(0); // append a text node to the cell let newtext = document.createtextnode('new bottom row'); newcell.appendchild(newtext); } // call addrow() with the table's id addrow('my-table'); result specifications specification status comment html living standardthe definition of 'htmltableelement.insertrow()' in that specification.
HTML Drag and Drop API - Web APIs
function dragstart_handler(ev) { // create an image and then use it for the drag image.
... // note: change "example.gif" to a real image url or the image // will not be created and the default drag image will be used.
... link indicates that some form of relationship or connection will be created between the source and drop locations.
Headers() - Web APIs
WebAPIHeadersHeaders
the headers() constructor creates a new headers object.
... example creating an empty headers object is simple: var myheaders = new headers(); // currently empty you could add a header to this using headers.append: myheaders.append('content-type', 'image/jpeg'); myheaders.get('content-type'); // returns 'image/jpeg' or you can add the headers you want as the headers object is created.
... in the following snippet we create a new headers object, adding some headers by passing the constructor an init object as an argument: var httpheaders = { 'content-type' : 'image/jpeg', 'accept-charset' : 'utf-8', 'x-my-custom-header' : 'zeke are cool' }; var myheaders = new headers(httpheaders); you can now create another headers object, passing it the first headers object as its init object: var secondheadersobj = new headers(myheaders); secondheadersobj.get('content-type'); // would return 'image/jpeg' — it inherits it from the first headers object specifications specification status comment fetchthe definition of 'headers()' in that specification.
Headers - Web APIs
WebAPIHeaders
you can retrieve a headers object via the request.headers and response.headers properties, and create a new headers object using the headers.headers() constructor.
... constructor headers() creates a new headers object.
... examples in the following snippet, we create a new header using the headers() constructor, add a new header to it using append(), then return that header value using get(): var myheaders = new headers(); myheaders.append('content-type', 'text/xml'); myheaders.get('content-type') // should return 'text/xml' the same can be achieved by passing an array of arrays or an object literal to the constructor: var myheaders = new headers({ '...
Ajax navigation example - Web APIs
to see how it works, please create the following files (or git clone https://github.com/giabao/mdn-ajax-nav-example.git ): note: for fully integrating the <form> elements within this mechanism, please take a look at the paragraph submitting forms and uploading files.
...idx < nlen; document.links[nidx++].onclick = processlink); } const /* customizable constants */ stargetid = "ajax-content", sviewkey = "view_as", sajaxclass = "ajax-nav", /* not customizable constants */ rsearch = /\?.*$/, rhost = /^[^\?]*\?*&*/, rview = new regexp("&" + sviewkey + "\\=[^&]*|&*$", "i"), rendqstmark = /\?$/, oloadingbox = document.createelement("div"), ocover = document.createelement("div"), oloadingimg = new image(), opageinfo = { title: null, url: location.href }, ohttpstatus = /* http://www.iana.org/assignments/http-status-codes/http-status-codes.xml */ { 100: "continue", 101: "switching protocols", 102: "processing", 200: "ok", ...
... 201: "created", 202: "accepted", 203: "non-authoritative information", 204: "no content", 205: "reset content", 206: "partial content", 207: "multi-status", 208: "already reported", 226: "im used", 300: "multiple choices", 301: "moved permanently", 302: "found", 303: "see other", 304: "not modified", 305: "use proxy", 306: "reserved", 307: "temporary redirect", 308: "permanent redirect", 400: "bad request", 401: "unauthorized", 402: "payment required", 403: "forbidden", 404: "not found", 405: "method not allowed", ...
IDBCursor.delete() - Web APIs
WebAPIIDBCursordelete
invalidstateerror the cursor was created using idbindex.openkeycursor, is currently being iterated, or has iterated past its end.
... example in this simple fragment we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store.
...even power windows is better.'); }; } else { var listitem = document.createelement('li'); listitem.innerhtml = '<strong>' + cursor.value.albumtitle + '</strong>, ' + cursor.value.year; list.appendchild(listitem); } cursor.continue(); } else { console.log('entries displayed.'); } }; }; specifications specification status comment indexed database api 2.0the definition of 'delete()' in that specification.
IDBDatabase: abort event - Web APIs
// open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = (event) => { const db = event.target.result; // create an objectstore for this database const objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month',...
... 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = (event) => { const db = dbopenrequest.result; db.addeventlistener('abort', () => { console.log('transaction aborted'); }); // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['todolist'], 'readwrite'); // abort the transaction transaction.abort(); }; the same example, but assigning the event handler to the onabort property: // open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = (event) => { const db = event.target.result; // create an objectstore for this database const objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' })...
...; // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = (event) => { const db = dbopenrequest.result; db.onabort = () => { console.log('transaction aborted'); }; // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['todolist'], 'readwrite'); // abort the transaction transaction.abort(); }; ...
IDBDatabase: close event - Web APIs
bubbles no cancelable no interface event event handler property onerror examples this example opens a database and listens for the close event: // open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = (event) => { const db = event.target.result; // create an objectstore for this database const objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month',...
... 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = (event) => { const db = dbopenrequest.result; db.addeventlistener('close', () => { console.log('database connection closed'); }); }; the same example, using the onclose property instead of addeventlistener(): // open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = (event) => { const db = event.target.result; // create an objectstore for this database const objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', {...
... unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = (event) => { const db = dbopenrequest.result; db.onclose = () => { console.log('database connection closed'); }; }; ...
IDBDatabase: error event - Web APIs
roperty onerror examples this example opens a database and tries to add a record, listening for the error event for the add() operation (this will occur if, for example, a record with the given tasktitle already exists): // open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = (event) => { const db = event.target.result; // create an objectstore for this database const objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month',...
... 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = (event) => { const newitem = { tasktitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'january', year: 2020 }; const db = dbopenrequest.result; db.addeventlistener('error', () => { console.log(`error adding new item: ${newitem.tasktitle}`); }); // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['todolist'], 'readwrite'); const objectstore = transaction.objectstore('todolist'); const objectstorerequest = objectstore.add(newitem); }; the same example, using the onerror property instead of addeventlistener(): // open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequ...
...est.onupgradeneeded = (event) => { const db = event.target.result; // create an objectstore for this database const objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = (event) => { const newitem = { tasktitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'january', year: 2020 }; const db = dbopenrequest.result; db.onerror = () => { console.log(`error a...
IDBDatabase.onabort - Web APIs
}; example this example shows an idbopendbrequest.onupgradeneeded block that creates a new object store; it also includes onerror and onabort functions to handle non-success cases.
... dbopenrequest.onupgradeneeded = function(event) { var db = event.target.result; db.onerror = function() { note.innerhtml += '<li>error opening database.</li>'; }; db.onabort = function() { note.innerhtml += '<li>database opening aborted!</li>'; }; // create an objectstore for this database var objectstore = db.createobjectstore("todolist", { keypath: "tasktitle" }); // define what data items the objectstore will contain objectstore.createindex("hours", "hours", { unique: false }); objectstore.createindex("minutes", "minutes", { unique: false }); objectstore.createindex("day", "day", { unique: false }); objectstore.createindex("month", "month", { unique: false }); objectstore.createindex("year", "year", { unique: false }); objectstore.createindex("noti...
...fied", "notified", { unique: false }); note.innerhtml += '<li>object store created.</li>'; }; specifications specification status comment indexed database api 2.0the definition of 'onabort' in that specification.
IDBDatabase.onerror - Web APIs
} example this example shows an idbopendbrequest.onupgradeneeded block that creates a new object store; it also includes onerror and onabort functions to handle non-success cases.
... dbopenrequest.onupgradeneeded = function(event) { var db = this.result; db.onerror = function(event) { note.innerhtml += '<li>error opening database.</li>'; }; db.onabort = function(event) { note.innerhtml += '<li>database opening aborted!</li>'; }; // create an objectstore for this database var objectstore = db.createobjectstore("todolist", { keypath: "tasktitle" }); // define what data items the objectstore will contain objectstore.createindex("hours", "hours", { unique: false }); objectstore.createindex("minutes", "minutes", { unique: false }); objectstore.createindex("day", "day", { unique: false }); objectstore.createindex("month", "month", { unique: false }); objectstore.createindex("year", "year", { unique: false }); objectstore.createindex("no...
...tified", "notified", { unique: false }); note.innerhtml += '<li>object store created.</li>'; }; specifications specification status comment indexed database api 2.0the definition of 'onerror' in that specification.
IDBDatabase.onversionchange - Web APIs
} example this example shows an idbopendbrequest.onupgradeneeded block that creates a new object store; it also includes onerror and onabort functions to handle non-success cases, and an onversionchange function to notify when a database structure change has occurred.
... request.onupgradeneeded = function(event) { var db = event.target.result; db.onerror = function(event) { note.innerhtml += '<li>error opening database.</li>'; }; db.onabort = function(event) { note.innerhtml += '<li>database opening aborted!</li>'; }; // create an objectstore for this database var objectstore = db.createobjectstore("todolist", { keypath: "tasktitle" }); // define what data items the objectstore will contain objectstore.createindex("hours", "hours", { unique: false }); objectstore.createindex("minutes", "minutes", { unique: false }); objectstore.createindex("day", "day", { unique: false }); objectstore.createindex("month", "month", { unique: false }); objectstore.createindex("year", "year", { unique: false }); objectstore.createindex("...
...notified", "notified", { unique: false }); note.innerhtml += '<li>object store created.</li>'; db.onversionchange = function(event) { note.innerhtml += '<li>a database change has occurred; you should refresh this browser window, or close it down and use the other open version of this application, wherever it exists.</li>'; }; }; specifications specification status comment indexed database api 2.0the definition of 'onversionchange' in that specification.
IDBDatabase: versionchange event - Web APIs
bubbles no cancelable no interface event event handler property onversionchange examples this example opens a database and, on success, adds a listener to versionchange: // open the database const dbopenrequest = window.indexeddb.open('nonexistent', 4); dbopenrequest.onupgradeneeded = event => { const db = event.target.result; // create an objectstore for this database const objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month',...
... 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.addeventlistener('success', event => { const db = event.target.result; db.addeventlistener('versionchange', event => { console.log('the version of this database has changed'); }); }); the same example, using the onversionchange event handler property: // open the database const dbopenrequest = window.indexeddb.open('nonexistent', 4); dbopenrequest.onupgradeneeded = event => { const db = event.target.result; // create an objectstore for this database const objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.create...
...index('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = event => { const db = event.target.result; db.onversionchange = event => { console.log('the version of this database has changed'); }; }; ...
IDBKeyRange.bound() - Web APIs
WebAPIIDBKeyRangebound
the bound() method of the idbkeyrange interface creates a new key range with the specified upper and lower bounds.
... return value idbkeyrange: the newly created key range.
...-examples repo (view the example live too.) function displaydata() { var keyrangevalue = idbkeyrange.bound("a", "f"); var transaction = db.transaction(['fthings'], 'readonly'); var objectstore = transaction.objectstore('fthings'); objectstore.opencursor(keyrangevalue).onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listitem = document.createelement('li'); listitem.innerhtml = '<strong>' + cursor.value.fthing + '</strong>, ' + cursor.value.frating; list.appendchild(listitem); cursor.continue(); } else { console.log('entries all displayed.'); } }; }; specification specification status comment indexed database api 2.0the definition of 'bound()' in that specifi...
IDBKeyRange.lowerBound() - Web APIs
the lowerbound() method of the idbkeyrange interface creates a new key range with only a lower bound.
... return value idbkeyrange: the newly created key range.
...e-example repo (view the example live too.) function displaydata() { var keyrangevalue = idbkeyrange.lowerbound("f"); var transaction = db.transaction(['fthings'], 'readonly'); var objectstore = transaction.objectstore('fthings'); objectstore.opencursor(keyrangevalue).onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listitem = document.createelement('li'); listitem.innerhtml = '<strong>' + cursor.value.fthing + '</strong>, ' + cursor.value.frating; list.appendchild(listitem); cursor.continue(); } else { console.log('entries all displayed.'); } }; }; specification specification status comment indexed database api 2.0the definition of 'lowerbound()' in that ...
IDBKeyRange.only() - Web APIs
WebAPIIDBKeyRangeonly
the only() method of the idbkeyrange interface creates a new key range containing a single value.
... return value idbkeyrange: the newly created key range.
...our idbkeyrange repo (view the example live too.) function displaydata() { var keyrangevalue = idbkeyrange.only("a"); var transaction = db.transaction(['fthings'], 'readonly'); var objectstore = transaction.objectstore('fthings'); objectstore.opencursor(keyrangevalue).onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listitem = document.createelement('li'); listitem.innerhtml = '<strong>' + cursor.value.fthing + '</strong>, ' + cursor.value.frating; list.appendchild(listitem); cursor.continue(); } else { console.log('entries all displayed.'); } }; }; specification specification status comment indexed database api 2.0the definition of 'only' in that specificati...
IDBKeyRange.upperBound() - Web APIs
the upperbound() method of the idbkeyrange interface creates a new upper-bound key range.
...optional return value idbkeyrange: the newly created key range.
...e-example repo (view the example live too.) function displaydata() { var keyrangevalue = idbkeyrange.upperbound("f"); var transaction = db.transaction(['fthings'], 'readonly'); var objectstore = transaction.objectstore('fthings'); objectstore.opencursor(keyrangevalue).onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listitem = document.createelement('li'); listitem.innerhtml = '<strong>' + cursor.value.fthing + '</strong>, ' + cursor.value.frating; list.appendchild(listitem); cursor.continue(); } else { console.log('entries all displayed.'); } }; }; specification specification status comment indexed database api 2.0the definition of 'upperbound()' in th...
IDBObjectStore.add() - Web APIs
the add() method of the idbobjectstore interface returns an idbrequest object, and, in a separate thread, creates a structured clone of the value, and stores the cloned value in the object store.
... // this is used a lot below db = dbopenrequest.result; // run the adddata() function to add the data to the database adddata(); }; function adddata() { // create a new object ready to insert into the idb var newitem = [ { tasktitle: "walk dog", hours: 19, minutes: 30, day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of the transaction completing, when everything is done transaction.onco...
...duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // make a request to add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of our request note.innerhtml += '<li>request successful.</li>'; }; }; specification specification status comment indexed database api 2.0the definition of 'add()' in that specification.
IDBObjectStore.autoIncrement - Web APIs
after the object store has been created, we log objectstore.autoincrement to the console.
... // this is used a lot below db = dbopenrequest.result; // run the adddata() function to add the data to the database adddata(); }; function adddata() { // create a new object ready to insert into the idb var newitem = [ { tasktitle: "walk dog", hours: 19, minutes: 30, day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of the transaction completing, when everything is done transaction.onco...
...duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); console.log(objectstore.autoincrement); // make a request to add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of our request note.innerhtml += '<li>request successful.</li>'; }; }; specification specification status comment indexed database api 2.0the definition of 'autoincrement' in that specifica...
IDBObjectStore.deleteIndex() - Web APIs
idbobjectstore.createindex is used to create new indexes on the object store, after which we delete the unneeded old indexes with deleteindex().
...this is used a lot below db = this.result; // run the displaydata() function to populate the task list with all the to-do list data already in the idb displaydata(); }; // this event handles the event whereby a new version of the database needs to be created // either one has not been created before, or a new version number has been submitted via the // window.indexeddb.open line above //it is only implemented in recent browsers dbopenrequest.onupgradeneeded = function(event) { var db = this.result; db.onerror = function(event) { note.innerhtml += '<li>error loading database.</li>'; }; // create an objectstore for this database var o...
...bjectstore = db.createobjectstore("todolist", { keypath: "tasktitle" }); // define what data items the objectstore will contain objectstore.createindex("hours", "hours", { unique: false }); objectstore.createindex("minutes", "minutes", { unique: false }); objectstore.createindex("day", "day", { unique: false }); objectstore.createindex("month", "month", { unique: false }); objectstore.createindex("year", "year", { unique: false }); objectstore.createindex("notified", "notified", { unique: false }); objectstore.deleteindex("seconds"); objectstore.deleteindex("contact"); }; specifications specification status comment indexed database api 2.0the definition of 'deleteindex()' in that specification.
IDBObjectStore.indexNames - Web APIs
after the object store has been created, we log objectstore.indexnames to the console.
... // this is used a lot below db = this.result; // run the adddata() function to add the data to the database adddata(); }; function adddata() { // create a new object ready to insert into the idb var newitem = [ { tasktitle: "walk dog", hours: 19, minutes: 30, day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of the transaction completing, when everything is done transaction.onco...
...duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); console.log(objectstore.indexnames); // make a request to add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of our request note.innerhtml += '<li>request successful.</li>'; }; }; specification specification status comment indexed database api 2.0the definition of 'indexnames' in that specification.
IDBObjectStore.keyPath - Web APIs
after the object store has been created, we log objectstore.keypath to the console.
... // this is used a lot below db = dbopenrequest.result; // run the adddata() function to add the data to the database adddata(); }; function adddata() { // create a new object ready to insert into the idb var newitem = [ { tasktitle: "walk dog", hours: 19, minutes: 30, day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of the transaction completing, when everything is done transaction.onco...
...duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); console.log(objectstore.keypath); // make a request to add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of our request note.innerhtml += '<li>request successful.</li>'; }; }; specification specification status comment indexed database api 2.0the definition of 'keypath' in that specification.
IDBObjectStore.name - Web APIs
after the object store has been created, we log objectstore.name to the console.
... // this is used a lot below db = dbopenrequest.result; // run the adddata() function to add the data to the database adddata(); }; function adddata() { // create a new object ready to insert into the idb var newitem = [ { tasktitle: "walk dog", hours: 19, minutes: 30, day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of the transaction completing, when everything is done transaction.onco...
...duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); console.log(objectstore.name); // make a request to add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of our request note.innerhtml += '<li>request successful.</li>'; }; }; specification specification status comment indexed database api 2.0the definition of 'name' in that specification.
IDBObjectStore.transaction - Web APIs
after the object store has been created, we log objectstore.transaction to the console.
... // this is used a lot below db = dbopenrequest.result; // run the adddata() function to add the data to the database adddata(); }; function adddata() { // create a new object ready to insert into the idb var newitem = [ { tasktitle: "walk dog", hours: 19, minutes: 30, day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of the transaction completing, when everything is done transaction.onco...
...duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); console.log(objectstore.transaction); // make a request to add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of our request note.innerhtml += '<li>request successful.</li>'; }; }; specification specification status comment indexed database api 2.0the definition of 'transaction' in that specification...
IDBOpenDBRequest: blocked event - Web APIs
cancelable no interface idbversionchangeevent event handler property onblocked examples using addeventlistener(): // open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = (event) => { const db = event.target.result; db.onerror = () => { console.log('error creating database'); }; // create an objectstore for this database var objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', '...
...month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = (event) => { // let's try to open the same database with a higher revision version const req2 = indexeddb.open('todolist', 5); // in this case the onblocked handler will be executed req2.addeventlistener('blocked', () => { console.log('request was blocked'); }); }; using the onblocked property: // open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = (event) => { const db = event.target.result; db.onerror = () => { console.log('error creating database'); }; // create an objectstore for this database var objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define...
... what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = (event) => { // let's try to open the same database with a higher revision version const req2 = indexeddb.open('todolist', 5); // in this case the onblocked handler will be executed req2.onblocked = () => { console.log('request was blocked'); }; }; ...
IDBOpenDBRequest: upgradeneeded event - Web APIs
// open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.addeventlistener('upgradeneeded', event => { const db = event.target.result; console.log(`upgrading to version ${db.version}`); // create an objectstore for this database var objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', '...
...month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }); this is the same example, but uses the onupgradeneeded event handler property.
... // open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = event => { const db = event.target.result; console.log(`upgrading to version ${db.version}`); // create an objectstore for this database var objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; ...
IDBRequest: error event - Web APIs
cord, listening for the error event for the add() operation (this will occur if, for example, a record with the given tasktitle already exists): // open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.addeventlistener('upgradeneeded', event => { const db = event.target.result; db.onerror = () => { console.log('error creating database'); }; // create an objectstore for this database var objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', '...
...month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }); dbopenrequest.addeventlistener('success', event => { const db = dbopenrequest.result; // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['todolist'], 'readwrite'); const objectstore = transaction.objectstore('todolist'); const newitem = { tasktitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'january', year: 2020 }; const objectstorerequest = objectstore.add(newitem); objectstorerequest.addeventlistener('error', () => { console.log(`error adding new item: ${newitem.tasktitle}`); }); }); the same example, using the onerror property instead of addeventlistener(): // open the database const dbopenrequest = window.indexeddb.op...
...en('todolist', 4); dbopenrequest.onupgradeneeded = event => { const db = event.target.result; db.onerror = () => { console.log('error creating database'); }; // create an objectstore for this database var objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = event => { const db = dbopenrequest.result; // open a read/write db transaction, ready for adding t...
IDBRequest: success event - Web APIs
nt event handler property onsuccess examples this example tries to open a database and listens for the success event using addeventlistener(): // open the database const openrequest = window.indexeddb.open('todolist', 4); openrequest.onupgradeneeded = (event) => { const db = event.target.result; db.onerror = () => { console.log('error creating database'); }; // create an objectstore for this database var objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', '...
...month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; openrequest.addeventlistener('success', (event) => { console.log('database opened successfully!'); }); the same example, but using the onsuccess event handler property: // open the database const openrequest = window.indexeddb.open('todolist', 4); openrequest.onupgradeneeded = (event) => { const db = event.target.result; db.onerror = () => { console.log('error creating database'); }; // create an objectstore for this database var objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: f...
...alse }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; openrequest.onsuccess = (event) => { console.log('database opened successfully!'); }; ...
IDBTransaction.abort() - Web APIs
all pending idbrequest objects created during this transaction have their idbrequest.error attribute set to aborterror.
...this is used a lot below db = dbopenrequest.result; // run the adddata() function to add the data to the database adddata(); }; function adddata() { // create a new object ready for being inserted into the idb var newitem = [ { tasktitle: "walk dog", hours: 19, minutes: 30, day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(e...
...duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of the request (this does not mean the item // has been stored successfully in the db - for that you need transaction.onsuccess) note.innerhtml += '<li>request successful.</li>'; }; // abort the transaction we just did transaction.abort(); }; specificat...
IDBTransaction: abort event - Web APIs
// open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = event => { const db = event.target.result; db.onerror = () => { console.log('error creating database'); }; // create an objectstore for this database var objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', '...
...month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = event => { const db = dbopenrequest.result; // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['todolist'], 'readwrite'); // add a listener for `abort` transaction.addeventlistener('abort', () => { console.log('transaction was aborted'); }); // abort the transaction transaction.abort(); }; the same example, but assigning the event handler to the onabort property: // open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = event => { const db = event.target.result; db.onerror = () => { console.log('error creating database'); }; // create a...
...n objectstore for this database var objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = event => { const db = dbopenrequest.result; // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['todolist'], 'readwrite'); // add a listener for `abort` transaction.onabort = (event) => { console.log('transaction was aborted'...
IDBTransaction: complete event - Web APIs
bubbles no cancelable no interface event event handler property oncomplete examples using addeventlistener(): // open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = event => { const db = event.target.result; db.onerror = () => { console.log('error creating database'); }; // create an objectstore for this database var objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', '...
...month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = event => { const db = dbopenrequest.result; // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['todolist'], 'readwrite'); // add a listener for `complete` transaction.addeventlistener('complete', event => { console.log('transaction was competed'); }); const objectstore = transaction.objectstore('todolist'); const newitem = { tasktitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'january', year: 2019 }; const objectstorerequest = objectstore.add(newitem); }; using the oncomplete property: // open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradenee...
...ded = event => { const db = event.target.result; db.onerror = () => { console.log('error creating database'); }; // create an objectstore for this database var objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = event => { const db = dbopenrequest.result; // open a read/write db transaction, ready for adding the data const transaction = db.transaction([...
IDBTransaction: error event - Web APIs
roperty onerror examples this example opens a database and tries to add a record, listening for the error event for the add() operation (this will occur if, for example, a record with the given tasktitle already exists): // open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = (event) => { const db = event.target.result; // create an objectstore for this database const objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month',...
... 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = (event) => { const db = dbopenrequest.result; // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['todolist'], 'readwrite'); transaction.addeventlistener('error', () => { console.log(`error adding new item: ${newitem.tasktitle}`); }); const objectstore = transaction.objectstore('todolist'); const newitem = { tasktitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'january', year: 2020 }; const objectstorerequest = objectstore.add(newitem); }; the same example, using the onerror property instead of addeventlistener(): // open the database const dbopenrequest = window.indexeddb.open('todolist', 4); ...
... dbopenrequest.onupgradeneeded = (event) => { const db = event.target.result; // create an objectstore for this database const objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = (event) => { const db = dbopenrequest.result; // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['todolist'], 'readwrite'); transactio...
IDBTransaction.mode - Web APIs
versionchange allows any operation to be performed, including ones that delete and create object stores and indexes.
... // this is used a lot below db = dbopenrequest.result; // run the adddata() function to add the data to the database adddata(); }; function adddata() { // create a new object ready for being inserted into the idb var newitem = [ { tasktitle: "walk dog", hours: 19, minutes: 30, day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(e...
...duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of the request (this does not mean the item // has been stored successfully in the db - for that you need transaction.onsuccess) note.innerhtml += '<li>request successful.</li>'; }; // return the mode this transaction has been opened in (should be "readwr...
IDBTransactionSync - Web APIs
when an application creates an idbtransactionsync object, it blocks until the browser is able to reserve the require database objects.
...when this method is called, the browser ignores all the changes performed to the objects of this database since this transaction was created.
...when this method is called, the browser durably stores all the changes performed to the objects of the database since this transaction was created.
ImageCapture - Web APIs
constructor imagecapture() creates a new imagecapture object which can be used to capture still frames (photos) from a given mediastreamtrack which represents a video stream.
...the track is then used to create an imagecapture object so that takephoto() and grabframe() can be called.
...magecapture = new imagecapture(track); }) .catch(error => console.log(error)); } function ongrabframebuttonclick() { imagecapture.grabframe() .then(imagebitmap => { const canvas = document.queryselector('#grabframecanvas'); drawcanvas(canvas, imagebitmap); }) .catch(error => console.log(error)); } function ontakephotobuttonclick() { imagecapture.takephoto() .then(blob => createimagebitmap(blob)) .then(imagebitmap => { const canvas = document.queryselector('#takephotocanvas'); drawcanvas(canvas, imagebitmap); }) .catch(error => console.log(error)); } /* utils */ function drawcanvas(canvas, img) { canvas.width = getcomputedstyle(canvas).width.split('px')[0]; canvas.height = getcomputedstyle(canvas).height.split('px')[0]; let ratio = math.min(canvas.
IntersectionObserver - Web APIs
when an intersectionobserver is created, it's configured to watch for given ratios of visibility within the root.
... the configuration cannot be changed once the intersectionobserver is created, so a given observer object is only useful for watching for specific changes in degree of visibility; however, you can watch multiple target elements with the same observer.
... constructor intersectionobserver.intersectionobserver() creates a new intersectionobserver object which will execute a specified callback function when it detects that a target element's visibility has crossed one or more thresholds.
KeyboardEvent.initKeyEvent() - Web APIs
the keyboardevent.initkeyevent() method is used to initialize the value of an event created using document.createevent("keyboardevent").
... events initialized in this way must have been created with the document.createevent("keyboardevent") method.
... example var event = document.createevent('keyboardevent'); // create a key event // define the event event.initkeyevent("keypress", // typearg, true, // canbubblearg, true, // cancelablearg, null, // viewarg, specifies uievent.view.
KeyframeEffect.KeyframeEffect() - Web APIs
syntax var keyframes = new keyframeeffect(element, keyframeset, keyframeoptions); var keyframes = new keyframeeffect(sourcekeyframes); parameters the first type of constructor (see above) creates a completely new keyframeeffect object instance.
... the second type of constructor (see above) creates a clone of an existing keyframeeffect object instance.
... examples in the follow the white rabbit example, the keyframeeffect constructor is used to create a set of keyframes that dictate how the white rabbit should animate down the hole: var rabbitdownkeyframes = new keyframeeffect( whiterabbit, // element to animate [ { transform: 'translatey(0%)' }, // keyframe { transform: 'translatey(100%)' } // keyframe ], { duration: 3000, fill: 'forwards' } // keyframe options ); specifications specification status comment web animations level 2the definition of 'keyframeeffectoptions.iterationcomposite' in that specification.
LocalFileSystem - Web APIs
you can call the method more than once if you want to create two file systems: one that's temporary and one that's persistent.
... (to learn more about the storage types, see the basic concepts article.) in most cases, you need to create only one file system, but in a few cases, it might be useful to create a second one.
... for example, if you were to create a mail app, you might create a temporary storage for caching assets (like images and attachments) to speed up performance, while creating persistent storage for unique data—such as drafts of emails that were composed while offline—that should not be lost before they are backed up into the cloud.
MediaDevices.ondevicechange - Web APIs
example in this example, we create a function called updatedevicelist(), which is called once when mediadevices.getusermedia() successfully obtains a stream, and then is called any time the device list changes.
... function updatedevicelist() { navigator.mediadevices.enumeratedevices() .then(function(devices) { audiolist.innerhtml = ""; videolist.innerhtml = ""; devices.foreach(function(device) { let elem = document.createelement("li"); let [kind, type, direction] = device.kind.match(/(\w+)(input|output)/i); elem.innerhtml = "<strong>" + device.label + "</strong> (" + direction + ")"; if (type === "audio") { audiolist.appendchild(elem); } else if (type === "video") { videolist.appendchild(elem); } }); }); } updatedevicelist() consists entirely of a call to the f...
...for each device, we create a new <li> object to be used to display it to the user.
MediaRecorder() - Web APIs
the mediarecorder() constructor creates a new mediarecorder object that will record a specified mediastream.
...this source media can come from a stream created using navigator.mediadevices.getusermedia() or from an <audio>, <video> or <canvas> element.
... example this example shows how to create a media recorder for a specified stream, whose audio bit rate is set to 128 kbit/sec and whose video bit rate is set to 2.5 mbit/sec.
MediaRecorder.start() - Web APIs
then, each time that amount of media has been recorded, an event will be delivered to let you act upon the recorded media, while a new blob is created to record the next slice of the media assuming the mediarecorder's state is inactive, start() sets the state to recording, then begins capturing media from the input stream.
... a blob is created and the data is collected in it until the time slice period elapses or the source media ends.
...if the source is still playing, a new blob is created and recording continues into that, and so forth.
MediaRecorderErrorEvent() - Web APIs
the mediarecordererrorevent() constructor creates a new mediarecordererrorevent object that represents an error that occurred during the recording of media by the mediastream recording api.
... in general, you won't create these yourself; they are delivered to your implementation of mediarecorder.onerror when errors occur while recording media.
... syntax var errorevent = new mediarecordererrorevent(errorinfo) parameters errorinfo an object describing the error object to be created.
MediaRecorderErrorEvent.error - Web APIs
notsupportederror a mediarecorder couldn't be created because the specified options weren't valid.
... example this function creates and returns a mediarecorder for a given mediastream, configured to buffer data into an array and to watch for errors.
... 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.
MediaSource - Web APIs
mediasource.addsourcebuffer() creates a new sourcebuffer of the given mime type and adds it to the mediasource.sourcebuffers list.
... static methods mediasource.istypesupported() returns a boolean value indicating if the given mime type is supported by the current user agent — this is, if it can successfully create sourcebuffer objects for that mime type.
...cument.queryselector('video'); var asseturl = 'frag_bunny.mp4'; // need to be specific for blink regarding codecs // ./mp4info frag_bunny.mp4 | grep codec var mimecodec = 'video/mp4; codecs="avc1.42e01e, mp4a.40.2"'; if ('mediasource' in window && mediasource.istypesupported(mimecodec)) { var mediasource = new mediasource(); //console.log(mediasource.readystate); // closed video.src = url.createobjecturl(mediasource); mediasource.addeventlistener('sourceopen', sourceopen); } else { console.error('unsupported mime type or codec: ', mimecodec); } function sourceopen (_) { //console.log(this.readystate); // open var mediasource = this; var sourcebuffer = mediasource.addsourcebuffer(mimecodec); fetchab(asseturl, function (buf) { sourcebuffer.addeventlistener('updateend', fun...
MediaStream() - Web APIs
the mediastream() constructor returns a newly-created mediastream, which serves as a collection of media tracks, each represented by a mediastreamtrack object.
... syntax newstream = new mediastream(); newstream = new mediastream(stream); newstream = new mediastream(tracks[]); parameters stream a different mediastream object whose tracks are added to the newly-created stream automatically.
... return value a newly-created mediastream object, either empty, or containing the tracks provided, if any.
MediaStreamAudioSourceNode() - Web APIs
the web audio api's mediastreamaudiosourcenode() constructor creates and returns a new mediastreamaudiosourcenode object which uses the first audio track of a given mediastream as its source.
... note: another way to create a mediastreamaudiosourcenode is to call theaudiocontext.createmediastreamsource() method, specifying the stream from which you want to obtain audio.
... examples this example uses getusermedia() to obtain access to the user's camera, then creates a new mediastreamaudiosourcenode from its mediastream.
MediaStreamTrackAudioSourceNode() - Web APIs
the web audio api's mediastreamtrackaudiosourcenode() constructor creates and returns a new mediastreamtrackaudiosourcenode object whose audio is taken from the mediastreamtrack specified in the given options object.
... another way to create a mediastreamtrackaudiosourcenode is to call theaudiocontext.createmediastreamtracksource() method, specifying the mediastreamtrack from which you want to obtain audio.
... example this example uses getusermedia() to obtain access to the user's camera, then creates a new mediastreamaudiosourcenode from the first audio track provided by the device.
Media Source API - Web APIs
using mse, media streams can be created via javascript, and played using <audio> and <video> elements.
... extensions to other interfaces url.createobjecturl() creates an object url pointing to a mediasource object that can then be specified as the src value of an html media element to play a media stream.
... audiotrack.sourcebuffer, videotrack.sourcebuffer, texttrack.sourcebuffer returns the sourcebuffer that created the track in question.
MerchantValidationEvent() - Web APIs
the merchantvalidationevent() constructor creates a new merchantvalidationevent object.
... you should not have to create these events yourself; instead, just handle the merchantvalidation event.
... return value a newly-created merchantvalidationevent providing the information that needs to be delivered to the client-side code to present to the user agent by calling complete().
Microdata DOM API - Web APIs
getitems( [ types ] ) returns a nodelist of the elements in the document that create items, that are not part of other items, and that are of the types given in the argument, if any are listed.
... code example this example creates a big list with a nested list for each item on the page, each with all of the property names used in that item.
... var outer = document.createelement('ul'); var items = document.getitems(); for (var item = 0; item < items.length; item += 1) { var itemli = document.createelement('li'); var inner = document.createelement('ul'); for (var name = 0; name < items[item].properties.names.length; name += 1) { var propli = document.createelement('li'); propli.appendchild(document.createtextnode(items[item].properties.names[name])); inner.appendchild(propli); } itemli.appendchild(inner); outer.appendchild(itemli); } document.body.appendchild(outer); if faced with the following from an earlier example: <section itemscope itemtype="http://example.org/animals#cat"> <h1 itemprop="name http://example.com/fn">hedral</h1> <p itemprop="desc">hedral is a male american domestic shorthair, with a fluff...
MouseEvent.initMouseEvent() - Web APIs
the mouseevent.initmouseevent() method initializes the value of a mouse event once it's been created (normally using the document.createevent() method).
... events initialized in this way must have been created with the document.createevent() method.
... example html <div style="background:red; width:180px; padding:10px;"> <div id="out"></div> <input type="text"> </div> javascript document.body.onclick = function(){ e = arguments[0]; var dt = e.target,stag = dt.tagname.tolowercase(); document.getelementbyid("out").innerhtml = stag; }; var simulateclick = function(){ var evt = document.createevent("mouseevents"); evt.initmouseevent("click", true, true, window, 0, 0, 0, 80, 20, false, false, false, false, 0, null); document.body.dispatchevent(evt); } simulateclick(); result specifications specification status comment document object model (dom) level 3 events specificationthe definition of 'mouseevent.initmouseevent()' in that specification.
Node.insertBefore() - Web APIs
WebAPINodeinsertBefore
example example 1 <div id="parentelement"> <span id="childelement">foo bar</span> </div> <script> // create the new node to insert let newnode = document.createelement("span") // get a reference to the parent node let parentdiv = document.getelementbyid("childelement").parentnode // begin test case [ 1 ] : existing childelement (all works correctly) let sp2 = document.getelementbyid("childelement") parentdiv.insertbefore(newnode, sp2) // end test case [ 1 ] // begin test case [ 2 ] : childelement is...
...ynamic cast to type node // end test case [ 2 ] // begin test case [ 3 ] : childelement is of type "undefined" ( string ) let sp2 = "undefined" // non-existent node of id "childelement" parentdiv.insertbefore(newnode, sp2) // generates "type error: invalid argument" // end test case [ 3 ] </script> example 2 <div id="parentelement"> <span id="childelement">foo bar</span> </div> <script> // create a new, plain <span> element let sp1 = document.createelement("span") // get the reference element let sp2 = document.getelementbyid("childelement") // get the parent element let parentdiv = sp2.parentnode // insert the new element into before sp2 parentdiv.insertbefore(sp1, sp2) </script> note: there is no insertafter() method.
... // get the parent element let parentelement = document.getelementbyid('parentelement') // get the parent's first child let thefirstchild = parentelement.firstchild // create a new element let newelement = document.createelement("div") // insert the new element before the first child parentelement.insertbefore(newelement, thefirstchild) when the element does not have a first child, then firstchild is null.
Notification - Web APIs
constructor notification() creates a new instance of the notification object.
... notification.timestamp read only specifies the time at which a notification is created or applicable (past, present, or future).
... function notifyme() { // let's check if the browser supports notifications if (!("notification" in window)) { alert("this browser does not support desktop notification"); } // let's check whether notification permissions have already been granted else if (notification.permission === "granted") { // if it's okay let's create a notification var notification = new notification("hi there!"); } // otherwise, we need to ask the user for permission else if (notification.permission !== "denied") { notification.requestpermission().then(function (permission) { // if the user accepts, let's create a notification if (permission === "granted") { var notification = new notification("hi there!");...
OVR_multiview2 - Web APIs
currently, there is no way to use multiview to render to a multisampled backbuffer, so you should create contexts with antialias: false.
... const gl = document.createelement('canvas').getcontext( 'webgl2', { antialias: false } ); const ext = gl.getextension('ovr_multiview2'); const fb = gl.createframebuffer(); gl.bindframebuffer(gl.draw_framebuffer, fb); const colortex = gl.createtexture(); gl.bindtexture(gl.texture_2d_array, colortex); gl.texstorage3d(gl.texture_2d_array, 1, gl.rgba8, 512, 512, 2); ext.framebuffertexturemultiviewovr(gl.draw_framebuffer, gl.c...
...olor_attachment0, colortex, 0, 0, 2); const depthstenciltex = gl.createtexture(); gl.bindtexture(gl.texture_2d_array, depthstenciltex); gl.texstorage3d(gl.texture_2d_array, 1, gl.depth32f_stencil8, 512, 512, 2); ext.framebuffertexturemultiviewovr(gl.draw_framebuffer, gl.depth_stencil_attachment, depthstenciltex, 0, 0, 2); gl.drawelements(...); // draw will be broadcasted to the layers of colortex and depthstenciltex.
OfflineAudioContext.startRendering() - Web APIs
at this point we create another audio context, create an audiobuffersourcenode inside it, and set its buffer to be equal to the promise audiobuffer.
... note: for a working example, see our offline-audio-context-promise github repo (see the source code too.) // define online and offline audio context var audioctx = new audiocontext(); var offlinectx = new offlineaudiocontext(2,44100*40,44100); source = offlinectx.createbuffersource(); // use xhr to load an audio track, and // decodeaudiodata to decode it and offlineaudiocontext to render it function getdata() { request = new xmlhttprequest(); request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; source.c...
...onnect(offlinectx.destination); source.start(); //source.loop = true; offlinectx.startrendering().then(function(renderedbuffer) { console.log('rendering completed successfully'); var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var song = audioctx.createbuffersource(); song.buffer = renderedbuffer; song.connect(audioctx.destination); play.onclick = function() { song.start(); } }).catch(function(err) { console.log('rendering failed: ' + err); // note: the promise should reject when startrendering is called a second time on an offlineaudiocontext }); }); } request.send(); } // run getdata to start the process off getdata(); specifications ...
OscillatorNode.detune - Web APIs
syntax var oscillator = audioctx.createoscillator(); oscillator.detune.setvalueattime(100, audioctx.currenttime); // value in cents note: though the audioparam returned is read-only, the value it represents is not.
... example the following example shows basic usage of an audiocontext to create an oscillator node.
... // create web audio api context var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); // create oscillator node var oscillator = audioctx.createoscillator(); oscillator.type = 'square'; oscillator.frequency.setvalueattime(440, audioctx.currenttime); // value in hertz oscillator.detune.setvalueattime(100, audioctx.currenttime); // value in cents oscillator.start(); specifications specification status comment web audio apithe definition of 'detune' in that specification.
OscillatorNode.frequency - Web APIs
syntax var oscillator = audioctx.createoscillator(); oscillator.frequency.setvalueattime(440, audioctx.currenttime); // value in hertz note: though the audioparam returned is read-only, the value it represents is not.
... example the following example shows basic usage of an audiocontext to create an oscillator node.
... // create web audio api context var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); // create oscillator node var oscillator = audioctx.createoscillator(); oscillator.type = 'square'; oscillator.frequency.setvalueattime(440, audioctx.currenttime); // value in hertz oscillator.start(); specifications specification status comment web audio apithe definition of 'frequency' in that specification.
OscillatorNode.onended - Web APIs
syntax var oscillator = audioctx.createoscillator(); oscillator.onended = function() { ...
... }; example the following example shows basic usage of an audiocontext to create an oscillator node.
... // create web audio api context var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); // create oscillator node var oscillator = audioctx.createoscillator(); oscillator.type = 'square'; oscillator.frequency.value = 440; // value in hertz oscillator.start(); // start the tone playing oscillator.stop(5); // the tone will stop again in 5 seconds.
PannerNode.distanceModel - Web APIs
syntax var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.distancemodel = 'inverse'; value a enum — see distancemodeltype.
... example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
... // set up listener and panner position information var width = window.innerwidth; var height = window.innerheight; var xpos = math.floor(width/2); var ypos = math.floor(height/2); var zpos = 295; // define other variables var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.panningmodel = 'hrtf'; panner.distancemodel = 'inverse'; panner.refdistance = 1; panner.maxdistance = 10000; panner.rollofffactor = 1; panner.coneinnerangle = 360; panner.coneouterangle = 0; panner.coneoutergain = 0; if(panner.orientationx) { panner.orientationx.setvalueattime(1, audioctx.currenttime); panner.orientationy.setvalueattime(0, audioctx.currenttime); panner.orie...
PannerNode.maxDistance - Web APIs
syntax var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.maxdistance = 10000; value a double.
... example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
... // set up listener and panner position information var width = window.innerwidth; var height = window.innerheight; var xpos = math.floor(width/2); var ypos = math.floor(height/2); var zpos = 295; // define other variables var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.panningmodel = 'hrtf'; panner.distancemodel = 'inverse'; panner.refdistance = 1; panner.maxdistance = 10000; panner.rollofffactor = 1; panner.coneinnerangle = 360; panner.coneouterangle = 0; panner.coneoutergain = 0; if(panner.orientationx) { panner.orientationx.setvalueattime(1, audioctx.currenttime); panner.orientationy.setvalueattime(0, audioctx.currenttime); panner.orie...
PannerNode.panningModel - Web APIs
syntax var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.panningmodel = 'hrtf'; value a enum — see panningmodeltype.
... example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
... // set up listener and panner position information var width = window.innerwidth; var height = window.innerheight; var xpos = math.floor(width/2); var ypos = math.floor(height/2); var zpos = 295; // define other variables var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.panningmodel = 'hrtf'; panner.distancemodel = 'inverse'; panner.refdistance = 1; panner.maxdistance = 10000; panner.rollofffactor = 1; panner.coneinnerangle = 360; panner.coneouterangle = 0; panner.coneoutergain = 0; if(panner.orientationx) { panner.orientationx.setvalueattime(1, audioctx.currenttime); panner.orientationy.setvalueattime(0, audioctx.currenttime); panner.orie...
PannerNode.setOrientation() - Web APIs
syntax var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.setorientation(1,0,0); returns void.
... example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
... // set up listener and panner position information var width = window.innerwidth; var height = window.innerheight; var xpos = math.floor(width/2); var ypos = math.floor(height/2); var zpos = 295; // define other variables var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.panningmodel = 'hrtf'; panner.distancemodel = 'inverse'; panner.refdistance = 1; panner.maxdistance = 10000; panner.rollofffactor = 1; panner.coneinnerangle = 360; panner.coneouterangle = 0; panner.coneoutergain = 0; if(panner.orientationx) { panner.orientationx.setvalueattime(1, audioctx.currenttime); panner.orientationy.setvalueattime(0, audioctx.currenttime); panner.orie...
PannerNode.setPosition() - Web APIs
syntax var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.setposition(0,0,0); returns void.
... example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
... // set up listener and panner position information var width = window.innerwidth; var height = window.innerheight; var xpos = math.floor(width/2); var ypos = math.floor(height/2); var zpos = 295; // define other variables var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.panningmodel = 'hrtf'; panner.distancemodel = 'inverse'; panner.refdistance = 1; panner.maxdistance = 10000; panner.rollofffactor = 1; panner.coneinnerangle = 360; panner.coneouterangle = 0; panner.coneoutergain = 0; if(panner.orientationx) { panner.orientationx.setvalueattime(1, audioctx.currenttime); panner.orientationy.setvalueattime(0, audioctx.currenttime); panner.orie...
PannerNode.setVelocity() - Web APIs
syntax var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.setvelocity(0,0,17); returns void.
... example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
... // set up listener and panner position information var width = window.innerwidth; var height = window.innerheight; var xpos = math.floor(width/2); var ypos = math.floor(height/2); var zpos = 295; // define other variables var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.panningmodel = 'hrtf'; panner.distancemodel = 'inverse'; panner.refdistance = 1; panner.maxdistance = 10000; panner.rollofffactor = 1; panner.coneinnerangle = 360; panner.coneouterangle = 0; panner.coneoutergain = 0; if(panner.orientationx) { panner.orientationx.setvalueattime(1, audioctx.currenttime); panner.orientationy.setvalueattime(0, audioctx.currenttime); panner.orie...
PannerNode - Web APIs
number of inputs 1 number of outputs 1 channel count mode "clamped-max" channel count 2 channel interpretation "speakers" constructor pannernode.pannernode creates a new pannernode object instance.
... examples in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
... // set up listener and panner position information var width = window.innerwidth; var height = window.innerheight; var xpos = math.floor(width/2); var ypos = math.floor(height/2); var zpos = 295; // define other variables var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.panningmodel = 'hrtf'; panner.distancemodel = 'inverse'; panner.refdistance = 1; panner.maxdistance = 10000; panner.rollofffactor = 1; panner.coneinnerangle = 360; panner.coneouterangle = 0; panner.coneoutergain = 0; if(panner.orientationx) { panner.orientationx.setvalueattime(1, audioctx.currenttime); panner.orientationy.setvalueattime(0, audioctx.currenttime); panner.orie...
PasswordCredential - Web APIs
the passwordcredential constructor creates a new passwordcredential object.
... examples this example shows how to set up an htmlformelement to caputure data which we'll use to create a passwordcredential object.
... <form id="form" method="post"> <input type="text" name="id" autocomplete="username" /> <input type="password" name="password" autocomplete="current-password" /> <input type="hidden" name="csrf_token" value="*****" /> </form> then, a reference to this form element, using it to create a passwordcredential object, and storing it in the browser's password system.
Path2D.addPath() - Web APIs
WebAPIPath2DaddPath
html <canvas id="canvas"></canvas> javascript first, we create two separate path2d objects, each of which contains a rectangle made using the rect() method.
... we then create a matrix using document.createelementns() and createsvgmatrix().
... const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // create first path and add a rectangle let p1 = new path2d(); p1.rect(0, 0, 100, 150); // create second path and add a rectangle let p2 = new path2d(); p2.rect(0, 0, 100, 75); // create transformation matrix that moves 200 points to the right let m = document.createelementns('http://www.w3.org/2000/svg', 'svg').createsvgmatrix(); m.a = 1; m.b = 0; m.c = 0; m.d = 1; m.e = 200; m.f = 0; // add second path to the first path p1.addpath(p2, m); // draw the first path ctx.fill(p1); result specification...
performance.mark() - Web APIs
WebAPIPerformancemark
the mark() method creates a timestamp in the browser's performance entry buffer with the given name.
... return value void example the following example shows how to use mark() to create and retrieve performancemark entries.
... // create a bunch of marks.
Performance - Web APIs
if you create a mark on the main thread (or other worker), you cannot see it in a worker thread, and vice versa.
... performance.mark() creates a timestamp in the browser's performance entry buffer with the given name.
... performance.measure() creates a named timestamp in the browser's performance entry buffer between two specified marks (known as the start mark and end mark, respectively).
PerformanceEntry.entryType - Web APIs
mark performancemark domstring the name used when the mark was created by calling performance.mark().
... measure performancemeasure domstring name used when the measure was created by calling performance.measure().
... function run_performanceentry() { // check for feature support before continuing if (performance.mark === undefined) { console.log("performance.mark not supported"); return; } // create a performance entry named "begin" via the mark() method performance.mark("begin"); // check the entrytype of all the "begin" entries var entriesnamedbegin = performance.getentriesbyname("begin"); for (var i=0; i < entriesnamedbegin.length; i++) { var typeofentry = entriesnamedbegin[i].entrytype; console.log("entry is type: " + typeofentry); } } specifications sp...
PerformanceEntry.name - Web APIs
domstring performancemark mark the name used when the mark was created by calling performance.mark().
... domstring performancemeasure measure name used when the measure was created by calling performance.measure().
...performance.mark not supported"); return; } // create some performance entries via the mark() method performance.mark("begin"); do_work(50000); performance.mark("end"); // use getentries() to iterate through the each entry var p = performance.getentries(); for (var i=0; i < p.length; i++) { log("entry[" + i + "]"); check_performanceentry(p[i]); } } function check_performanceentry(obj) { var properties = ["name", "entrytype", "starttime", "duration"]; var m...
Performance API - Web APIs
if the scope is a window, the value is the time the browser context was created and if the scope is a worker, the value is the time the worker was created.
...entries of this type are created by calling performance.mark() to add a named domhighrestimestamp (the mark) to the browser's performance timeline.
...entries of this type are created by calling performance.measure() to add a nameddomhighrestimestamp (the measure) between two marks to the browser's performance timeline.
PeriodicWave.PeriodicWave() - Web APIs
the periodicwave() constructor of the web audio api creates a new periodicwave object instance.
... options optional a periodicwaveoptions dictionary object defining the properties you want the periodicwave to have (it also inherits the options defined in the periodicwaveconstraints dictionary.): real: a float32array containing the cosine terms that you want to use to form the wave (equivalent to the real parameter of audiocontext.createperiodicwave).
... imag: a float32array containing the sine terms that you want to use to form the wave (equivalent to the imag parameter of audiocontext.createperiodicwave).
ProgressEvent.initProgressEvent() - Web APIs
the progressevent.initprogressevent() method initializes an animation event created using the deprecated document.createevent("progressevent") method.
... progressevent created that way are untrusted.
...do not use it anymore, use the standard constructor, progressevent(), to create a synthetic progressevent syntax progress.initprogressevent(typearg, canbubblearg, cancelablearg, lengthcomputable, loaded, total); parameters typearg is a domstring identifying the specific type of animation event that occurred.
PublicKeyCredentialCreationOptions.excludeCredentials - Web APIs
syntax excludecredentials = publickeycredentialcreationoptions.excludecredentials value an array whose elements are objects with the following properties: type a string describing type of public-key credential to be created.
... if the authenticator already contains one of such a public key credential, the client will throw a domexception or asks the user if they want to create a new credential.
...* another id */ } ], challenge: new uint8array(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { // send attestation response and client extensions // to the server to proceed with the registration // of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the def...
PublicKeyCredentialCreationOptions.pubKeyCredParams - Web APIs
the pubkeycredparams property of the publickeycredentialcreationoptions dictionary is an array whose elements are objects describing the desired features of the credential to be created.
... syntax pubkeycredparams = publickeycredentialcreationoptions.pubkeycredparams value an array whose elements are objects with the following properties: type a string describing type of public-key credential to be created.
...will fallback on an rsa algorithm { type: "public-key", alg: -37 } ], challenge: new uint8array(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", } }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { // send attestation response and client extensions // to the server to proceed with the registration // of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the def...
PublicKeyCredentialCreationOptions - Web APIs
the publickeycredentialcreationoptions dictionary of the web authentication api holds options passed to navigators.credentials.create() in order to create a publickeycredential.
... examples // some examples of cose algorithms const cose_alg_ecdsa_w_sha256 = -7; const cose_alg_ecdsa_w_sha512 = -36; var createcredentialoptions = { // format of new credentials is publickey publickey: { // relying party rp: { name: "example corp", id: "login.example.com", icon: "https://login.example.com/login.ico" }, // cryptographic challenge from the server challenge: new uint8array(26), // user user: { id: ...
...e user excludecredentials: [ { type: "public-key", // the id for john.doe@example.com id : new uint8array(26) /* this actually is given by the server */ }, { type: "public-key", // the id for john-doe@example.com id : new uint8array(26) /* another id */ } ] } }; // create the new credential with the options above navigator.credentials.create(createcredentialoptions) .then(function (newcredentialinfo) { var attestationresponse = newcredentialinfo.response; var clientextensionsoutputs = newcredentialinfo.getclientextensionsresults(); // send the response to the relying party server // it will verify the content and integrity before // creating...
RTCDataChannel.maxRetransmits - Web APIs
the read-only rtcdatachannel property maxretransmits returns the maximum number of times the browser should try to retransmit a message before giving up, as set when the data channel was created, or null, which indicates that there is no maximum.
... this can only be set when the rtcdatachannel is created by calling rtcpeerconnection.createdatachannel(), using the maxretransmits field in the specified options.
... syntax var tries = adatachannel.maxretransmits; value the maximum number of times the browser will try to retransmit a message before giving up, or null if not set when rtcpeerconnection.createdatachannel() was called.
RTCDataChannel: message event - Web APIs
examples for a given rtcdatachannel, dc, created for a peer connection using its createdatachannel() method, this code sets up a handler for incoming messages and acts on them by adding the data contained within the message to the current document as a new <p> (paragraph) element.
... dc.addeventlistener("message", ev => { let newparagraph = document.createelement("p"); let textnode = document.createtextnode(event.data); newparagraph.appendchild(textnode); document.body.appendchild(newparagraph); }, false); lines 2-4 create the new paragraph element and add the message data to it as a new text node.
... you can also use an rtcdatachannel object's onmessage event handler property to set the event handler: dc.onmessage = ev => { let newparagraph = document.createelement("p"); let textnode = document.createtextnode(event.data); newparagraph.appendchild(textnode); document.body.appendchild(newparagraph); } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'the <code>message</code> event' in that specification.
RTCDataChannel.readyState - Web APIs
this is the state of a new rtcdatachannel after being created by rtcpeerconnection.createdatachannel() (on the peer which started the connection process).
...this is the default state of a new rtcdatachannel created by the webrtc layer when the remote peer created the channel and delivered to the site or app in a datachannel event of type rtcdatachannelevent.
... 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 closi...
RTCDataChannelEvent() - Web APIs
the rtcdatachannelevent() constructor creates a new rtcdatachannelevent.
... you will rarely if ever construct an rtcdatachannelevent by hand; these events are normally created and sent by the webrtc layer itself.
... example in this example, a new datachannel event is created.
RTCOfferAnswerOptions - Web APIs
it's used as the base type for the options parameter when calling createoffer() or createanswer() on an rtcpeerconnection.
... each of createoffer() and createanswer() use rtcofferansweroptions as the base type for their options parameter's dictionary.
... createoffer() uses rtcofferoptions and createanswer() uses rtcansweroptions.
RTCPeerConnection.ondatachannel - Web APIs
this event, of type rtcdatachannelevent, is sent when an rtcdatachannel is added to the connection by the remote peer calling createdatachannel().
... syntax rtcpeerconnection.ondatachannel = function; value set this property to be a function you provide which receives as input a single parameter: an rtcdatachannelevent which provides in its channel property the rtcdatachannel which has been created.
... example pc.ondatachannel = function(ev) { console.log('data channel is created!'); ev.channel.onopen = function() { console.log('data channel is open and ready to be used.'); }; }; specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnection.ondatachannel' in that specification.
RTCPeerConnection.setRemoteDescription() - Web APIs
this lets you simplify code such as the following: mypeerconnection.setremotedescription(new rtcsessiondescription(description)) .then(function () { return createmystream(); }) to simply be: mypeerconnection.setremotedescription(description) .then(function () { return createmystream(); }) using async/await syntax, you can further simplify this to: await mypeerconnection.setremotedescription(description); createmystream(); since it's unnecessary, the rtcsessiondescription() constructor is deprecated.
... function handleoffer(msg) { createmypeerconnection(); mypeerconnection.setremotedescription(msg.description).then(function () { return navigator.mediadevices.getusermedia(mediaconstraints); }) .then(function(stream) { document.getelementbyid("local_video").srcobject = stream; return mypeerconnection.addstream(stream); }) .then(function() { return mypeerconnection.createanswer(); }) .then(function(ans...
...when our promise fulfillment handler is called, indicating that this has been done, we create a stream, add it to the connection, then create an sdp answer and call setlocaldescription() to set that as the configuration at our end of the call before forwarding that answer to the caller.
RTCPeerConnection.signalingState - Web APIs
"have-local-offer" the local peer has called rtcpeerconnection.setlocaldescription(), passing in sdp representing an offer (usually created by calling rtcpeerconnection.createoffer()), and the offer has been applied successfully.
... "have-remote-offer" the remote peer has created an offer and used the signaling server to deliver it to the local peer, which has set the offer as the remote description by calling rtcpeerconnection.setremotedescription().
... "have-local-pranswer" the offer sent by the remote peer has been applied and an answer has been created (usually by calling rtcpeerconnection.createanswer()) and applied by calling rtcpeerconnection.setlocaldescription().
RTCSessionDescriptionCallback - Web APIs
the rtcsessiondescriptioncallback type is used to represent the callback function passed into the deprecated callback-based version of createoffer() or createanswer() when using them to create offers or answers.
... because this function type is part of the legacy webrtc api, you should avoid using it (and the callback-based forms of createoffer() and createanswer() that make use of it).
... example var pc = new rtcpeerconnection(); var descriptioncallback = function(offer) { pc.setlocaldescription(offer); } pc.createoffer(descriptioncallback); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcsessiondescriptioncallback' in that specification.
RTCTrackEvent - Web APIs
constructor rtctrackevent() creates and returns a new rtctrackevent object, initialized with properties taken from the specified rtctrackeventinit dictionary.
... you will probably not need to create new track events yourself, since they're typically created by the webrtc infrastructure and sent to the connection's ontrack event handler.
... example this simple example creates an event listener for the track event which sets the srcobject of the <video> element with the id videobox to the first stream in the list passed in the event's streams array.
Range() - Web APIs
WebAPIRangeRange
the range() constructor returns a newly created range object whose start and end is the global document object.
... syntax range = new range() example in this example we create a new range with the range() constructor, and set its beginning and end positions using the range.setstartbefore() and range.setendafter() methods.
... html <p>first paragraph.</p> <p>second paragraph.</p> <p>third paragraph.</p> <p>fourth paragraph.</p> javascript const paragraphs = document.queryselectorall('p'); // create new range const range = new range(); // start range at second paragraph range.setstartbefore(paragraphs[1]); // end range at third paragraph range.setendafter(paragraphs[2]); // get window selection const selection = window.getselection(); // add range to window selection selection.addrange(range); result specification specification status comment domthe definition of 'range.range()' in that specification.
Range.selectNodeContents() - Web APIs
example range = document.createrange(); referencenode = document.getelementsbytagname("div")[0]; range.selectnodecontents(referencenode); live sample this example lets the user select and deselect a paragraph with buttons.
... document.createrange(), range.selectnodecontents(), and selection.addrange() are used to select the content.
...raph</button> javascript const p = document.getelementbyid('p'); const selectbutton = document.getelementbyid('select-button'); const deselectbutton = document.getelementbyid('deselect-button'); selectbutton.addeventlistener('click', e => { // clear any current selection const selection = window.getselection(); selection.removeallranges(); // select paragraph const range = document.createrange(); range.selectnodecontents(p); selection.addrange(range); }); deselectbutton.addeventlistener('click', e => { const selection = window.getselection(); selection.removeallranges(); }); result specifications specification status comment domthe definition of 'range.selectnodecontents()' in that specification.
Range.setStart() - Web APIs
WebAPIRangesetStart
main st.<br> dodge city, ks<br> 67801<br> usa</p> <hr> <p>nodes in the original address:</p> <ol id="log"></ol> javascript const address = document.getelementbyid('address'); const log = document.getelementbyid('log'); // log info address.childnodes.foreach(node => { const li = document.createelement('li'); li.textcontent = `${node.nodename}, ${node.nodevalue}`; log.appendchild(li); }); // highlight the street and city const startoffset = 2; // start at third node: 101 e.
...const endoffset = 5; // end at fifth node: dodge city, ks const range = document.createrange(); range.setstart(address, startoffset); range.setend(address, endoffset); const mark = document.createelement('mark'); range.surroundcontents(mark); result get characters from a text node this example uses the range.setstart() and range.setend() methods to define the contents of a range.
... html <p id="content">0123456789</p> <p id="log"></p> javascript const element = document.getelementbyid('content'); const textnode = element.childnodes[0]; const range = document.createrange(); range.setstart(textnode, 0); // start at first character range.setend(textnode, 5); // end at fifth character document.getelementbyid('log').textcontent = range; result specifications specification status comment domthe definition of 'range.setstart()' in that specification.
Range - Web APIs
WebAPIRange
a range can be created by using the document.createrange() method.
... range.createcontextualfragment() returns a documentfragment created from a given string of code.
... working draft added the method createcontextualfragment().
ReadableStream.ReadableStream() - Web APIs
the readablestream() constructor creates and returns a readable stream object from the given handlers.
... examples in the following simple example, a custom readablestream is created using a constructor (see our simple random stream example for the full code).
... const stream = new readablestream({ start(controller) { interval = setinterval(() => { let string = randomchars(); // add the string to the stream controller.enqueue(string); // show it on the screen let listitem = document.createelement('li'); listitem.textcontent = string; list1.appendchild(listitem); }, 1000); button.addeventlistener('click', function() { clearinterval(interval); fetchstream(); controller.close(); }) }, pull(controller) { // we don't really need a pull in this example }, cancel() { // this is called if the reader cancels, // so we should sto...
ReadableStreamDefaultController - Web APIs
readablestreamdefaultcontroller instances are created automatically during readablestream construction.
... examples in the following simple example, a custom readablestream is created using a constructor (see our simple random stream example for the full code).
... const stream = new readablestream({ start(controller) { interval = setinterval(() => { let string = randomchars(); // add the string to the stream controller.enqueue(string); // show it on the screen let listitem = document.createelement('li'); listitem.textcontent = string; list1.appendchild(listitem); }, 1000); button.addeventlistener('click', function() { clearinterval(interval); fetchstream(); controller.close(); }) }, pull(controller) { // we don't really need a pull in this example }, cancel() { // this is called if the reader cancels, // so we should sto...
ReadableStreamDefaultReader.ReadableStreamDefaultReader() - Web APIs
the readablestreamdefaultreader() constructor creates and returns a readablestreamdefaultreader object instance.
... examples in the following simple example, a previously-created custom readablestream is read using a readablestreamdefaultreader created using getreader().
... if (done) { console.log("stream complete"); para.textcontent = result; return; } // value for fetch streams is a uint8array charsreceived += value.length; const chunk = value; let listitem = document.createelement('li'); listitem.textcontent = 'received ' + charsreceived + ' characters so far.
ReadableStreamDefaultReader.read() - Web APIs
in this example stream is a previously-created custom readablestream.
... it is read using a readablestreamdefaultreader created using getreader().
... if (done) { console.log("stream complete"); para.textcontent = result; return; } // value for fetch streams is a uint8array charsreceived += value.length; const chunk = value; let listitem = document.createelement('li'); listitem.textcontent = 'received ' + charsreceived + ' characters so far.
Report - Web APIs
WebAPIReport
examples in our deprecation_report.html example, we create a simple reporting observer to observe usage of deprecated features on our web page: let options = { types: ['deprecation'], buffered: true } let observer = new reportingobserver(function(reports, observer) { reportbtn.onclick = () => displayreports(reports); }, options); we then tell it to start observing reports using reportingobserver.observe(); this tells the observer to start collec...
... the report details are displayed via the displayreports() fuction, which takes the observer callback's reports parameter as its parameter: function displayreports(reports) { const outputelem = document.queryselector('.output'); const list = document.createelement('ul'); outputelem.appendchild(list); for(let i = 0; i < reports.length; i++) { let listitem = document.createelement('li'); let textnode = document.createtextnode('report ' + (i + 1) + ', type: ' + reports[i].type); listitem.appendchild(textnode); let innerlist = document.createelement('ul'); listitem.appendchild(innerlist); list.appendchild(listitem); for...
... (let key in reports[i].body) { let innerlistitem = document.createelement('li'); let keyvalue = reports[i].body[key]; innerlistitem.textcontent = key + ': ' + keyvalue; innerlist.appendchild(innerlistitem); } } } the reports parameter contains an array of all the reports in the observer's report queue.
Response.headers - Web APIs
WebAPIResponseheaders
example in our fetch response example (see fetch response live) we create a new request object using the request() constructor, passing it a jpg path.
... we then fetch this request using fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>.
... var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest).then(function(response) { console.log(response.headers); // returns a headers{} object response.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); }); specifications specification status comment fetchthe definition of 'headers' in that specification.
Response.ok - Web APIs
WebAPIResponseok
example in our fetch response example (see fetch response live) we create a new request object using the request() constructor, passing it a jpg path.
... we then fetch this request using fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>.
... var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest).then(function(response) { console.log(response.ok); // returns true if the response returned successfully response.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); }); specifications specification status comment fetchthe definition of 'ok' in that specification.
Response.status - Web APIs
WebAPIResponsestatus
example in our fetch response example (see fetch response live) we create a new request object using the request() constructor, passing it a jpg path.
... we then fetch this request using fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>.
... var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest).then(function(response) { console.log(response.status); // returns 200 response.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); }); specifications specification status comment fetchthe definition of 'status' in that specification.
Response.statusText - Web APIs
example in our fetch response example (see fetch response live) we create a new request object using the request() constructor, passing it a jpg path.
... we then fetch this request using fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>.
... var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest).then(function(response) { console.log(response.statustext); // returns "ok" if the response returned successfully response.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); }); specifications specification status comment fetchthe definition of 'statustext' in that specification.
Response.type - Web APIs
WebAPIResponsetype
example in our fetch response example (see fetch response live) we create a new request object using the request() constructor, passing it a jpg path.
... we then fetch this request using fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>.
... var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest).then(function(response) { console.log(response.type); // returns basic by default response.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); }); specifications specification status comment fetchthe definition of 'type' in that specification.
Response.url - Web APIs
WebAPIResponseurl
example in our fetch response example (see fetch response live) we create a new request object using the request() constructor, passing it a jpg path.
... we then fetch this request using fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>.
... var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest).then(function(response) { console.log(response.url); // returns /docs/web/api/response/flowers.jpg response.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); }); specifications specification status comment fetchthe definition of 'url' in that specification.
SharedWorker() - Web APIs
the sharedworker() constructor creates a sharedworker object that executes the script at the specified url.
...available properties are as follows: type: a domstring specifying the type of worker to create.
... return value the created worker.
StereoPannerNode.pan - Web APIs
syntax var audioctx = new audiocontext(); var pannode = audioctx.createstereopanner(); pannode.pan.value = -0.5; returned value an a-rate audioparam containing the panning to apply.
...in the javascript we create a mediaelementaudiosourcenode and a stereopannernode, and connect the two together using the connect() method.
... var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var myaudio = document.queryselector('audio'); var pancontrol = document.queryselector('.panning-control'); var panvalue = document.queryselector('.panning-value'); pre.innerhtml = myscript.innerhtml; // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a stereo panner var pannode = audioctx.createstereopanner(); // event handler function to increase panning to the right and left // when the slider is moved pancontrol.oninput = function() { pannode.pan.setvalueattime(pancontrol.value, audioctx.currenttime); ...
StereoPannerNode - Web APIs
number of inputs 1 number of outputs 1 channel count mode "clamped-max" channel count 2 channel interpretation "speakers" constructor stereopannernode() creates a new instance of a stereopannernode object.
...in the javascript we create a mediaelementaudiosourcenode and a stereopannernode, and connect the two together using the connect() method.
... var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var myaudio = document.queryselector('audio'); var pancontrol = document.queryselector('.panning-control'); var panvalue = document.queryselector('.panning-value'); pre.innerhtml = myscript.innerhtml; // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a stereo panner var pannode = audioctx.createstereopanner(); // event handler function to increase panning to the right and left // when the slider is moved pancontrol.oninput = function() { pannode.pan.setvalueattime(pancontrol.value, audioctx.currenttime); ...
Streams API concepts - Web APIs
only one reader can read a stream at a time; when a reader is created and starts reading a stream (an active reader), we say it is locked to it.
...which underlying stream (and by extension, reader and controller) your code will use depends on how the stream was created in the first place (see the readablestream() constructor page).
... when a writer is created and starts writing to a stream (an active writer), it is said to be locked to it.
SubtleCrypto - Web APIs
the subtlecrypto api provides the following cryptography functions: * sign() and verify(): create and verify digital signatures.
... * digest(): create a fixed-length, collision-resistant digest of some data.
... generating and deriving keys the generatekey() and derivekey() functions both create a new cryptokey object.
Text.isElementContentWhitespace - Web APIs
syntax b = textnode.iselementcontentwhitespace; example in the example below, we create a node with mixed display and whitespace characters and the attribute is false.
... var tn = document.createtextnode("hello world"); tn.iselementcontentwhitespace; /* evaluates to false */ for a node that is all whitespace characters, the iselementcontentwhitespace evaluates to true.
... var ws = document.createtextnode(" \t \r\n ") ws.iselementcontentwhitespace; /* evaluates to true */ ...
TransitionEvent.initTransitionEvent() - Web APIs
the transitionevent.inittransitionevent() method initializes a transition event created using the deprecated document.createevent("transitionevent") method.
... transitionevent created that way are untrusted.
...do not use it anymore, use the standard constructor, transitionevent(), to create a synthetic transitionevent syntax transitionevent.inittransitionevent(typearg, canbubblearg, cancelablearg, transitionnamearg, elapsedtimearg); parameters typearg is a domstring identifying the specific type of transition event that occurred.
TransitionEvent - Web APIs
constructor transitionevent() creates a transitionevent event with the given parameters.
... transitionrun an event fired when a css transition is created, when it is added to a set of running transitions, though not nessarilty started transitionstart an event fired when a css transition has started transitioning.
... transitionevent.inittransitionevent() initializes a transitionevent created using the deprecated document.createevent("transitionevent") method.
UIEvent.initUIEvent() - Web APIs
the uievent.inituievent() method initializes a ui event once it's been created.
... events initialized in this way must have been created with the document.createevent() method.
... example var e = document.createevent("uievent"); // creates a click event that bubbles, can be cancelled, // and with its view and detail property initialized to window and 1, // respectively e.inituievent("click", true, true, window, 1); specifications specification status comment document object model (dom) level 3 events specificationthe definition of 'uievent.inituievent()' in that specification.
WaveShaperNode.oversample - Web APIs
example the following example shows basic usage of an audiocontext to create a wave shaper node.
...their s-shape, for instance, helps create a smoother sounding result.
... var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var distortion = audioctx.createwaveshaper(); ...
WebGLRenderingContext.vertexAttribPointer() - Web APIs
for example, the following vertex: { "position": [1.0, 2.0, 1.5], "normal": [1.0, 0.0, 0.0], "texcoord": [0.5, 0.25] } will be stored in the array buffer as follows: 00 00 80 3f 00 00 00 40 00 00 0c 3f 7f 00 00 00 7f ff 3f ff creating the array buffer first, we dynamically create the array buffer from json data using a dataview.
... //load geometry with fetch() and response.json() const response = await fetch('assets/geometry.json'); const vertices = await response.json(); //create array buffer const buffer = new arraybuffer(20 * vertices.length); //fill array buffer const dv = new dataview(buffer); for (let i = 0; i < vertices.length; i++) { dv.setfloat32(20 * i, vertices[i].position[0], true); dv.setfloat32(20 * i + 4, vertices[i].position[1], true); dv.setfloat32(20 * i + 8, vertices[i].position[2], true); dv.setint8(20 * i + 12, vertices[i].normal[0] * 0x7f); dv.setint8(20 * i + 13, vertices[i].normal[1] * 0x7f); dv.setint8(20 * i + 14, vertices[i].normal[2] * 0x7f); dv.setint8(20 * i + 15, 0); dv.setuint16(20 * i + 16, vertic...
...then we could load the binary file and interpret it as an array buffer: const response = await fetch('assets/geometry.bin'); const buffer = await response.arraybuffer(); consume array buffer with webgl first, we create a new vertex buffer object (vbo) and supply it with our array buffer: //bind array buffer to a vertex buffer object const vbo = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, vbo); gl.bufferdata(gl.array_buffer, buffer, gl.static_draw); then, we specify the memory layout of the array buffer, either by setting the index ourselves: //describe the layout of the buffer: //1.
WebGLShader - Web APIs
description to create a webglshader use webglrenderingcontext.createshader, then hook up the glsl source code using webglrenderingcontext.shadersource(), and finally invoke webglrenderingcontext.compileshader() to finish and compile the shader.
... function createshader (gl, sourcecode, type) { // compiles either a shader of type gl.vertex_shader or gl.fragment_shader var shader = gl.createshader( type ); gl.shadersource( shader, sourcecode ); gl.compileshader( shader ); if ( !gl.getshaderparameter(shader, gl.compile_status) ) { var info = gl.getshaderinfolog( shader ); throw 'could not compile webgl program.
... var vertexshadersource = 'attribute vec4 position;\n' + 'void main() {\n' + ' gl_position = position;\n' + '}\n'; //use the createshader function from the example above var vertexshader = createshader(gl, vertexshadersource, gl.vertex_shader) creating a fragment shader var fragmentshadersource = 'void main() {\n' + ' gl_fragcolor = vec4(1.0, 1.0, 1.0, 1.0);\n' + '}\n'; //use the createshader function from the example above var fragmentshader = createshader(gl, fragmentshadersource, gl.fragment_shader) specificat...
Scissor animation - Web APIs
in contrast, the color of the square (set with clearcolor) is only updated when a new square is created.
...the clear color state of webgl remains at the set value, until we change it again when a new square is created.
...var size = [60, 60], velocity = 3.0; function drawanimation () { gl.scissor(position[0], position[1], size[0] , size[1]); gl.clear(gl.color_buffer_bit); // every frame the vertical position of the square is // decreased, to create the illusion of movement.
Matrix math for the web - Web APIs
this article explores how to create matrices and how to use them with css transforms and the matrix3d transform type.
...these functions create a lot of new arrays, which can be particularly expensive for real-time operations due to garbage collection.
... // create the matrix3d style property from a matrix array function matrixarraytocssmatrix(array) { return 'matrix3d(' + array.join(',') + ')'; } // grab the dom element let moveme = document.getelementbyid('move-me'); // returns a result like: "matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 50, 100, 0, 1);" let matrix3drule = matrixarraytocssmatrix(translationmatrix); // set the transform moveme.style.
WebGL tutorial - Web APIs
in order to draw graphics on the canvas we use a javascript context object, which creates graphics on the fly.
... animating objects with webgl shows how to rotate and translate objects to create simple animations.
... creating 3d objects using webgl shows how to create and animate a 3d object (in this case, a cube).
WebGL best practices - Web APIs
however, for 2d resources that are never "zoomed out", don't pay the 30% memory surcharge for mipmaps: const tex = gl.createtexture(); gl.bindtexture(gl.texture_2d, tex); gl.texparameterf(gl.texture_2d, gl.texture_min_filter, gl.linear); // defaults to nearest_mipmap_linear, for mipmapping!
... webgl 2 use texstorage to create textures the teximage* api lets you define each mip level independently and at any size, even the mis-matching mips sizes are not an error until draw time which means there is no way the driver can actually prepare the texture in gpu memory until the first time the texture is drawn.
... length) { const sync = gl.fencesync(gl.sync_gpu_commands_complete, 0); gl.flush(); await clientwaitasync(gl, sync, 0, 10); gl.deletesync(sync); gl.bindbuffer(target, buffer); gl.getbuffersubdata(target, srcbyteoffset, dstbuffer, dstoffset, length); gl.bindbuffer(target, null); return dest; } async function readpixelsasync(gl, x, y, w, h, format, type, dest) { const buf = gl.createbuffer(); gl.bindbuffer(gl.pixel_pack_buffer, buf); gl.bufferdata(gl.pixel_pack_buffer, dest.bytelength, gl.stream_read); gl.readpixels(x, y, w, h, format, type, 0); gl.bindbuffer(gl.pixel_pack_buffer, null); await getbuffersubdataasync(gl, gl.pixel_pack_buffer, buf, 0, dest); gl.deletebuffer(buf); return dest; } canvas and webgl-related some tips are relevent to webgl, but deal...
Lifetime of a WebRTC session - Web APIs
the signaling process there's a sequence of things that have to happen in order to make it possible to begin a webrtc session: each peer creates an rtcpeerconnection object representing their end of the webrtc session.
... the caller creates and shares with the receiving peer a unique identifier or token of some kind so that the call between them can be identified by the code on the signaling server.
... to explicitly trigger ice restart, simply start the renegotiation process by calling rtcpeerconnection.createoffer(), specifying the icerestart option with a value of true.
Writing a WebSocket server in C# - Web APIs
to create an ipaddress object from a string, use the parse static method of ipaddress.
...ons.regex("^get").ismatch(data)) { const string eol = "\r\n"; // http/1.1 defines the sequence cr lf as the end-of-line marker byte[] response = encoding.utf8.getbytes("http/1.1 101 switching protocols" + eol + "connection: upgrade" + eol + "upgrade: websocket" + eol + "sec-websocket-accept: " + convert.tobase64string( system.security.cryptography.sha1.create().computehash( encoding.utf8.getbytes( new system.text.regularexpressions.regex("sec-websocket-key: (.*)").match(data).groups[1].value.trim() + "258eafa5-e914-47da-95ca-c5ab0dc85b11" ) ) ) + eol + eol); stream.write(response, 0, response.length); } decoding messages after a successful handshake, the client wil...
...write the hash back as the value of "sec-websocket-accept" response header in an http response string swk = regex.match(s, "sec-websocket-key: (.*)").groups[1].value.trim(); string swka = swk + "258eafa5-e914-47da-95ca-c5ab0dc85b11"; byte[] swkasha1 = system.security.cryptography.sha1.create().computehash(encoding.utf8.getbytes(swka)); string swkasha1base64 = convert.tobase64string(swkasha1); // http/1.1 defines the sequence cr lf as the end-of-line marker byte[] response = encoding.utf8.getbytes( "http/1.1 101 switching protocols\r\n" + "connection: upgrade\r\n" + "upgrade: w...
Rendering and the WebXR frame animation callback - Web APIs
once your webxr environment has been set up and an xrsession created to represent an ongoing xr environment session, you need to provide frames of the scene to the xr device for rendering.
...n runxr(xrsession) { worldrefspace = await xrsession.requestreferencespace("immersive-vr"); if (worldrefspace) { viewerrefspace = worldrefspace.getoffsetreferencespace( new xrrigidtransform(viewerstartposition, viewerstartorientation)); animationframerequestid = xrsession.requestanimationframe(mydrawframe); } } after getting a reference space for the immersive world, this creates an offset reference space representing the position and orientation of the viewer by creating an xrrigidtransform representing that position and orientation, then calling the xrreferencespace method getoffsetreferencespace().
... to create the illusion of three dimensions when rendering graphics, we need to simulate as many of these factors as we can.
Window.devicePixelRatio - Web APIs
javascript the javascript code creates the media query that monitors the device resolution and checks the value of devicepixelratio any time it changes.
... then the updatepixelratio() function is called once to display the starting value, after which the media query is created using matchmedia() and addeventlistener() is called to set up updatepixelratio() as a handler for the change event.
... html the html creates the boxes containing the instructions and the pixel-ratio box that will display the current pixel ratio information.
Window.resizeBy() - Web APIs
WebAPIWindowresizeBy
creating and resizing an external window for security reasons, it's no longer possible in firefox for a website to change the default size of a window in a browser if the window wasn’t created by window.open(), or contains more than one tab.
... even if you create window by window.open() it is not resizable by default.
... // create resizable window myexternalwindow = window.open("http://myurl.domain", "mywindowname", "resizable"); // resize window to 500x500 myexternalwindow.resizeto(500, 500); // make window relatively smaller to 400x400 myexternalwindow.resizeby(-100, -100); the window you create must respect the same origin policy.
WindowOrWorkerGlobalScope.fetch() - Web APIs
examples in our fetch request example (see fetch request live) we create a new request object using the relevant constructor, then fetch it using a fetch() call.
... since we are fetching an image, we run body.blob() on the response to give it the proper mime type so it will be handled properly, then create an object url of it and display it in an <img> element.
...status: ${response.status}`); } return response.blob(); }) .then(function(response) { let objecturl = url.createobjecturl(response); myimage.src = objecturl; }); in the fetch with init then request example (see fetch request init live), we do the same thing except that we pass in an init object when we invoke fetch(): const myimage = document.queryselector('img'); let myheaders = new headers(); myheaders.append('content-type', 'image/jpeg'); const myinit = { method: 'get', headers: myheaders, mode: 'cors', cache: 'default' }; let myrequest = new request('flowers.jpg'); fetch(myreques...
WindowOrWorkerGlobalScope - Web APIs
note: windoworworkerglobalscope is a mixin and not an interface; you can't actually create an object of type windoworworkerglobalscope.
... windoworworkerglobalscope.btoa() creates a base-64 encoded ascii string from a string of binary data.
... windoworworkerglobalscope.createimagebitmap() accepts a variety of different image sources, and returns a promise which resolves to an imagebitmap.
Worker - Web APIs
WebAPIWorker
the worker interface of the web workers api represents a background task that can be created via script, which can send messages back to its creator.
... constructors worker() creates a dedicated web worker that executes the script at the specified url.
... example the following code snippet creates a worker object using the worker() constructor, then uses the worker object: var myworker = new worker('/worker.js'); var first = document.queryselector('input#number1'); var second = document.queryselector('input#number2'); first.onchange = function() { myworker.postmessage([first.value, second.value]); console.log('message posted to worker'); } for a full example, see ourbasic dedicated...
WritableStream.WritableStream() - Web APIs
the writablestream() constructor creates a new writablestream object instance.
...it then calls a function called sendmessage(), passing the newly created stream and a string.
...trategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) { return new promise((resolve, reject) => { var buffer = new arraybuffer(2); var view = new uint16array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listitem = document.createelement('li'); listitem.textcontent = "chunk decoded: " + decoded; list.appendchild(listitem); result += decoded; resolve(); }); }, close() { var listitem = document.createelement('li'); listitem.textcontent = "[message received] " + result; list.appendchild(listitem); }, abort(err) { console.log("sink error:", err); } }, queuingstrategy); sen...
WritableStream.getWriter() - Web APIs
exceptions typeerror the stream you are trying to create a writer for is not a writablestream.
...it then calls a function called sendmessage(), passing the newly created stream and a string.
...trategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) { return new promise((resolve, reject) => { var buffer = new arraybuffer(2); var view = new uint16array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listitem = document.createelement('li'); listitem.textcontent = "chunk decoded: " + decoded; list.appendchild(listitem); result += decoded; resolve(); }); }, close() { var listitem = document.createelement('li'); listitem.textcontent = "[message received] " + result; list.appendchild(listitem); }, abort(err) { console.log("sink error:", err); } }, queuingstrategy); sen...
WritableStream - Web APIs
constructor writablestream() creates a new writablestream object.
...it then calls a function called sendmessage(), passing the newly created stream and a string.
...trategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) { return new promise((resolve, reject) => { var buffer = new arraybuffer(2); var view = new uint16array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listitem = document.createelement('li'); listitem.textcontent = "chunk decoded: " + decoded; list.appendchild(listitem); result += decoded; resolve(); }); }, close() { var listitem = document.createelement('li'); listitem.textcontent = "[message received] " + result; list.appendchild(listitem); }, abort(err) { console.log("sink error:", err); } }, queuingstrategy); sen...
WritableStreamDefaultWriter.WritableStreamDefaultWriter() - Web APIs
the writablestreamdefaultwriter() constructor creates a new writablestreamdefaultwriter object instance.
...it then calls a function called sendmessage(), passing the newly created stream and a string.
...trategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) { return new promise((resolve, reject) => { var buffer = new arraybuffer(2); var view = new uint16array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listitem = document.createelement('li'); listitem.textcontent = "chunk decoded: " + decoded; list.appendchild(listitem); result += decoded; resolve(); }); }, close() { var listitem = document.createelement('li'); listitem.textcontent = "[message received] " + result; list.appendchild(listitem); }, abort(err) { console.log("sink error:", err); } }, queuingstrategy); sen...
XPathEvaluator - Web APIs
methods xpathevaluator.createexpression() creates a parsed xpath expression with resolved namespaces.
... xpathevaluator.creatensresolver() adapts any dom node to resolve namespaces allowing the xpath expression to be evaluated relative to the context of the node where it appeared within the document.
... html <div>xpath example</div> <div>number of &lt;div&gt;s: <output></output></div> javascript var xpath = "//div"; var evaluator = new xpathevaluator(); var expression = evaluator.createexpression("//div"); var result = expression.evaluate(document, xpathresult.ordered_node_snapshot_type); document.queryselector("output").textcontent = result.snapshotlength; result specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathevaluator' in that specification.
XRReferenceSpace - Web APIs
getoffsetreferencespace() creates and returns a new reference space object as the same type as the one on which you call the method (so, either xrreferencespace or xrboundedreferencespace).
... xrboundedreferencespace local a tracking space whose native origin is located near the viewer's position at the time the session was created.
...however, xrreferencespace is immutable, so you need to instead create a new reference space representing the changed viewpoint.
XRRigidTransform.position - Web APIs
example to create a reference space which can be used to place an object at eye level (assuming eye level is 1.5 meters): function onsessionstarted(xrsession) { xrsession.addeventlistener("end", onsessionended); gl = initgraphics(xrsession); let gllayer = new xrwebgllayer(xrsession, gl); xrsession.updaterenderstate({ baselayer: gllayer }); if (immersivesession) { xrsession.requestreferencespace("...
...bounded-floor").then((refspace) => { refspacecreated(refspace); }).catch(() => { session.requestreferencespace("local-floor").then(refspacecreated); }); } else { session.requestreferencespace("viewer").then(refspacecreated); } } function refspacecreated(refspace) { if (immersivesession) { xrreferencespace = refspace; } else { xrreferencespace = refspace.getoffsetreferencespace( new xrrigidtransform({y: -1.5}); ); } xrsession.requestanimationframe(onframe); } after setting up the graphics context for webxr use, this begins by looking to see if a variable immersivesession is true; if so, we first request a bounded-floor reference space.
... in all cases, once the space has been obtained, it gets passed into the refspacecreated() function.
XRSession.updateRenderState() - Web APIs
the baselayer specified in newstate was created by an xrsession other than the one on which updaterenderstate() was called.
... examples this example creates a webgl context that is compatible with an immersive xr device and then uses it to create an xrwebgllayer.
... function onxrsessionstarted(xrsession) { let glcanvas = document.createelement("canvas"); let gl = glcanvas.getcontext("webgl", { xrcompatible: true }); loadwebglresources(); xrsession.updaterenderstate({ baselayer: new xrwebgllayer(xrsession, gl) }); } specifications specification status comment webxr device apithe definition of 'xrsession.updaterenderstate()' in that specification.
XRWebGLLayer() - Web APIs
the webxr device api xrwebgllayer() constructor creates and returns a new xrwebgllayer object, providing the linkage between the webxr device and the webgl graphics layer used to render the 3d scene.
... return value a newly-created xrwebgllayer which links the specified xrsession to the webgl context given by context, which will be used as the renderer for the session.
... exceptions invalidstateerror the new xrwebgllayer could not be created due to one of a number of possible state errors: the xrsession specified by session has already been stopped.
XRWebGLLayerInit.depth - Web APIs
when using the xrwebgllayer() constructor to create a new webgl rendering layer for webxr, providing as the layerinit parameter an object whose depth property is false will request that the new layer be created without a depth buffer.
... usage notes this property differs from ignoredepthvalues in that a layer created with ignoredepthvalues set to true may still have a depth buffer, but will not make use of it.
... if (gllayer.ignoredepthvalues) { /* not using the depth buffer */ } example in this example, a new xrwebgllayer is created for a webxr session, xrsession, without a depth buffer.
Generating HTML - Web APIs
since there is no html namespace, and using the xhtml namespace would force the xsl to create an xml document that would not behave like a html document, the xsl:output in the xsl stylesheet will make sure the resulting document will be handled as html.
... </xsl:stylesheet version="1.0"> a template matching the root node of the xml document is created and used to create the basic structure of the html page.
...it is needed in order to preserve the html elements in the xml document, since it matches all of them and copies them out into the html document the transformation creates.
Introduction - Web APIs
however, it has several limitations, such as lack of programming structures and ability to create complex layout models.
...xslt takes an xml document (the content) and creates a brand new document based on the rules in the xsl stylesheet.
...each template matches (using xpath) a certain fragment of the input xml document and then applies the substitution part on that fragment to create the new resulting document.
Using the link role - Accessibility
the link role is used to identify an element that creates a hyperlink to a resource that is in the application or external.
... this is a huge amount of work just to recreate something you've get for free using the <a> element, so you should really use that if possible.
... html <h1>role="link" example</h1> <span data-href="https://mozilla.org" tabindex="0" id="link1" role="link" class="link"> fake accessible link created using a span </span> <p><a href="https://mozilla.org" target="_blank">actual real link</a></p> css span[role="link"] { color: blue; text-decoration: underline; cursor: pointer; } span[role="link"]:focus { outline: 1px dotted black; } javascript const spanelem = document.queryselector('span'); //handles clicks and keydowns on the link function navigatelink(e) { if (e.type === ...
Alerts - Accessibility
below is example javascript code which could be inserted above the closing “head” tag: <script type="application/javascript"> function removeoldalert() { var oldalert = document.getelementbyid("alert"); if (oldalert){ document.body.removechild(oldalert); } } function addalert(amsg) { removeoldalert(); var newalert = document.createelement("div"); newalert.setattribute("role", "alert"); newalert.setattribute("id", "alert"); var msg = document.createtextnode(amsg); newalert.appendchild(msg); document.body.appendchild(newalert); } function checkvalidity(aid, asearchterm, amsg) { var elem = document.getelementbyid(aid); var invalid = (elem.value.indexof(asearchterm) < 0); if (invalid) { elem.set...
... next, the function creates a div element to hold the alert text.
...the alert we just created does not have any buttons to press, it just tells us what’s wrong.
Web Accessibility: Understanding Colors and Luminance - Accessibility
luminance and contrast contrast contrast between colors ("hues") is a critical component, but the use of color ("hues") alone is not enough to create accessible content.
... colors perception when it comes to "perceiving" colors, not all colors are created equal.
...ing that a contrast ratio of 3:1 is provided for icons understanding success criterion 1.4.3: contrast (minimum) wcag working group's wiki page on relative luminance contributers many, many thanks to wayne dick of the low vision task force of the w3c and the intense discussions on luminance; to teal for his help and discussions on human perception of the color blue and how software companies create algorithms for image output based on it; and to tom jewett from knowbility; for the tools and educational resources he developed, that help us all.
Perceivable - Accessibility
guideline 1.3 — create content that can be presented in different ways this guideline refers to the ability of content to be consumed by users in multiple ways, accomodating their differing needs.
...the order should be made obvious by use of correct semantic elements (e.g., headings, paragraphs), with css being used to create any unusual layout styles, irrespective of the markup.
... understanding identify purpose note: also see the wcag description for guideline 1.3: adaptable: create content that can be presented in different ways without losing information or structure.
@supports - CSS: Cascading Style Sheets
WebCSS@supports
the following example returns true if the browser supports the child combinator: @supports selector(a > b) {} the not operator the not operator can precede any expression to create a new expression, resulting in the negation of the original one.
... the and operator the and operator creates a new expression from the conjunction of two shorter expressions.
...the following are both equivalent: @supports (display: table-cell) and (display: list-item) and (display:run-in) {} @supports (display: table-cell) and ((display: list-item) and (display:run-in)) {} the or operator the or operator creates a new expression from the disjunction of two shorter expressions.
Using CSS animations - CSS: Cascading Style Sheets
there are three key advantages to css animations over traditional script-driven animation techniques: they’re easy to use for simple animations; you can create them without even having to know javascript.
... configuring the animation to create a css animation sequence, you style the element you want to animate with the animation property or its sub-properties.
... function listener(event) { var l = document.createelement("li"); switch(event.type) { case "animationstart": l.innerhtml = "started: elapsed time is " + event.elapsedtime; break; case "animationend": l.innerhtml = "ended: elapsed time is " + event.elapsedtime; break; case "animationiteration": l.innerhtml = "new loop started at time " + event.elapsedtime; break; } document.getelementbyid("outp...
CSS Backgrounds and Borders - CSS: Cascading Style Sheets
border-image generator this interactive tool lets you visually create border images (the border-image property).
... border-radius generator this interactive tool lets you visually create rounded corners (the border-radius property).
... box-shadow generator this interactive tool lets you visually create shadows behind elements (the box-shadow property).
Basic concepts of flexbox - CSS: Cascading Style Sheets
to create a flex container, we set the value of the area's container's display property to flex or inline-flex.
...this is why when we just declare display: flex on the parent to create flex items, the items all move into a row and take only as much space as they need to display their contents.
... using flex: none will create fully inflexible flex items.
Controlling Ratios of Flex Items Along the Main Axis - CSS: Cascading Style Sheets
we will be calculating the positive and negative free space created by comparing the total width of all the items with the container width.
... in this example i have created a series of inflexible boxes, with both flex-grow and flex-shrink set to 0.
...you can also use auto margins on flex items to absorb space and create gaps between items.
Block and inline layout in normal flow - CSS: Cascading Style Sheets
as defined in the specification, the margins between two block boxes are what creates separation between the elements.
...the lines created are known as line boxes.
... in the following example, we have three inline boxes created by a paragraph with a <strong> element inside it.
Flow Layout and Overflow - CSS: Cascading Style Sheets
giving an element a fixed height and width, then adding significant content to the box, creates a basic overflow example: the content goes into the box.
... as we have already learned, using any of these values, other than the default of visible, will create a new block formatting context.
...in addition it does not create a block formatting context.
Subgrid - CSS: Cascading Style Sheets
introduction to subgrid when you add display: grid to a grid container, only the direct children become grid items and can then be placed on the grid that you have created.
... no implicit grid in a subgridded dimension if you need to autoplace items, and do not know how many items you will have, take care when creating a subgrid, as it will prevent additional rows being created to hold those items.
... if we remove the grid-template-rows value we enable regular creation of implicit tracks and, although these won't line up with the tracks of the parent, as many as are required will be created.
Stacking context example 1 - CSS: Cascading Style Sheets
it happens that, since div #1 and div #3 are not assigned any z-index value, they do not create a stacking context.
...it is important to remember that assigning an opacity less than 1 to a positioned element implicitly creates a stacking context, just like adding a z-index value.
... and this example shows what happens when a parent element does not create a stacking context.
Using media queries - CSS: Cascading Style Sheets
although websites are commonly designed with screens in mind, you may want to create styles that target special devices such as printers or audio-based screenreaders.
...} if you create a media feature query without specifying a value, the nested styles will be used as long as the feature's value is not zero (or none, in level 4).
... creating complex media queries sometimes you may want to create a media query that depends on multiple conditions.
<color> - CSS: Cascading Style Sheets
hsl can also make it easier to create a set of matching colors (such as when you want multiple shades of a single hue).
...pe="text" id="color"> css div { width: 100%; height: 200px; } javascript const inputelem = document.queryselector('input'); const divelem = document.queryselector('div'); function validtextcolor(stringtotest) { if (stringtotest === "") { return false; } if (stringtotest === "inherit") { return false; } if (stringtotest === "transparent") { return false; } const image = document.createelement("img"); image.style.color = "rgb(0, 0, 0)"; image.style.color = stringtotest; if (image.style.color !== "rgb(0, 0, 0)") { return true; } image.style.color = "rgb(255, 255, 255)"; image.style.color = stringtotest; return image.style.color !== "rgb(255, 255, 255)"; } inputelem.addeventlistener('change', () => { if(validtextcolor(inputelem.value)) { divelem.style.background...
...color = inputelem.value; divelem.textcontent = ''; } else { divelem.style.backgroundcolor = 'white'; divelem.textcontent = 'invalid color value'; } }); result rgb syntax variations this example shows the many ways in which a single color can be created with the various rgb color syntaxes.
filter - CSS: Cascading Style Sheets
WebCSSfilter
the value of radius defines the value of the standard deviation to the gaussian function, or how many pixels on the screen blend into each other, so a larger value will create more blur.
...a value of 0% will create an image that is completely black.
...a value of 0% will create an image that is completely gray.
isolation - CSS: Cascading Style Sheets
WebCSSisolation
the isolation css property determines whether an element must create a new stacking context.
... values auto a new stacking context is created only if one of the properties applied to the element requires it.
... isolate a new stacking context must be created.
order - CSS: Cascading Style Sheets
WebCSSorder
accessibility concerns using the order property will create a disconnect between the visual presentation of content and dom order.
...adrian roselli mdn understanding wcag, guideline 1.3 explanations understanding success criterion 1.3.2 | w3c understanding wcag 2.0 formal definition initial value0applies toflex items and absolutely-positioned flex container childreninheritednocomputed valueas specifiedanimation typean integer formal syntax <integer> examples ordering items in a flex container this example uses css to create a classic two-sidebar layout surrounding a content block.
... the flexible box layout module automatically creates blocks of equal vertical size and uses as much horizontal space as available.
perspective - CSS: Cascading Style Sheets
using this property with a value different than 0 and none creates a new stacking context.
... formal definition initial valuenoneapplies totransformable elementsinheritednocomputed valuethe absolute length or noneanimation typea lengthcreates stacking contextyes formal syntax none | <length> examples setting perspective this example shows a cube with the perspective set at different positions.
... html the html below creates four copies of the same box, with the perspective set at different values.
radial-gradient() - CSS: Cascading Style Sheets
the radial-gradient() css function creates an image consisting of a progressive transition between two or more colors that radiate from an origin.
... to create a radial gradient that repeats so as to fill its container, use the repeating-radial-gradient() function instead.
... to create a smooth gradient, the radial-gradient() function draws a series of concentric shapes radiating out from the center to the ending shape (and potentially beyond).
translateZ() - CSS: Cascading Style Sheets
in the above interactive examples, perspective: 550px; (to create a 3d space) and transform-style: preserve-3d; (so the children, the 6 sides of the cube, are also positioned in the 3d space), have been set on the cube.
... 10000100001t0001 examples in this example, two boxes are created.
...the second is altered by applying perspective to create a 3d space, then moved towards the user.
Rich-Text Editing in Mozilla - Developer guides
d) { setdocmode(true); } } function formatdoc(scmd, svalue) { if (validatemode()) { document.execcommand(scmd, false, svalue); odoc.focus(); } } function validatemode() { if (!document.compform.switchmode.checked) { return true ; } alert("uncheck \"show html\"."); odoc.focus(); return false; } function setdocmode(btosource) { var ocontent; if (btosource) { ocontent = document.createtextnode(odoc.innerhtml); odoc.innerhtml = ""; var opre = document.createelement("pre"); odoc.contenteditable = false; opre.id = "sourcetext"; opre.contenteditable = true; opre.appendchild(ocontent); odoc.appendchild(opre); } else { if (document.all) { odoc.innerhtml = odoc.innertext; } else { ocontent = document.createrange(); ocontent.selec...
...onclick="formatdoc('indent');" src="data:image/gif;base64,r0lgodlhfgawaomiaaaaadljwl9vj1ie35gjuaezxtdv3nha7p///////////////////////////////yh5baeaaagalaaaaaawabyaaaq7emljq704650b/x8gemmpgugwhjnzxodkso5oquogo5khbwwesymqscrdhu9voyk5tm9zspfsr9gsjwiaow==" /> <img class="intlink" title="hyperlink" onclick="var slnk=prompt('write the url here','http:\/\/');if(slnk&&slnk!=''&&slnk!='http://'){formatdoc('createlink',slnk)}" src="data:image/gif;base64,r0lgodlhfgawaomkab1chdrly19vj3morpgjuaezxrcztb/i19ha7pv8/f///////////////////////yh5baekaa8alaaaaaawabyaaary8mljq7046827/2byiqvhhg9pegvgiklydeuby/rle4fqf4dcj2aqxaijqdcwqcaebwiioemqbgsafhdagghgi9xghahmnoszgjkjei33uesv2+/4vd4taqa7" /> <img class="intlink" title="cut" onclick="formatdoc('cut');" src="data:image/gif;base64,r0lgodlhfgawaiqsab1chbfnsrjtysjywjljwk...
... resources mozilla.org's rich-text editing specification mozilla.org's rich-text editing demo converting an app using document.designmode from ie to mozilla at mozilla.org designmode msdn: how to create an html editor application a closed source, cross-browser rich-text editing demo xbdesignmode; a javascript helper class for easier cross-browser development using designmode.
HTML5 Parser - Developer guides
WebGuideHTMLHTML5HTML5 Parser
in html5, document.write() can only be called from a script that is created by a <script> tag that does not have the async or defer attributes set.
... some contexts from which you should not call document.write() include: scripts created using document.createelement() event handlers settimeout() setinterval() <script async src="..."> <script defer src="..."> if you use the same mechanism for loading script libraries for all browsers including ie, then your code probably will not be affected by this change.
...this behavior created a security vulnerability.
Parsing and serializing XML - Developer guides
creating an xml document using one of the following approaches to create an xml document (which is an instance of document.
... use the following approaches to serialize the contents of the xml document you created in the previous section.
... serializing dom trees to strings first, create a dom tree as described in how to create a dom tree.
<br>: The Line Break element - HTML: Hypertext Markup Language
WebHTMLElementbr
note: do not use <br> to create margins between paragraphs; wrap them in <p> elements and use the css margin property to control their size.
... styling with css the <br> element has a single, well-defined purpose — to create a line break in a block of text.
... examples simple br in the following example we use <br> elements to create line breaks between the different lines of a postal address: mozilla<br> 331 e.
<details>: The Details disclosure element - HTML: Hypertext Markup Language
WebHTMLElementdetails
the html details element (<details>) creates a disclosure widget in which information is visible only when the widget is toggled into an "open" state.
... css details { font: 16px "open sans", calibri, sans-serif; width: 620px; } details > summary { padding: 2px 6px; width: 15em; background-color: #ddd; border: none; box-shadow: 3px 3px 4px black; cursor: pointer; } details > p { border-radius: 0 0 10px 10px; background-color: #ddd; padding: 2px 6px; margin: 0; box-shadow: 3px 3px 4px black; } this css creates a look similar to a tabbed interface, where clicking the tab opens it to reveal its contents.
...h: 620px; } details > summary { padding: 2px 6px; width: 15em; background-color: #ddd; border: none; box-shadow: 3px 3px 4px black; cursor: pointer; list-style: none; } details > summary::-webkit-details-marker { display: none; } details > p { border-radius: 0 0 10px 10px; background-color: #ddd; padding: 2px 6px; margin: 0; box-shadow: 3px 3px 4px black; } this css creates a look similar to a tabbed interface, where activating the tab expands and opens it to reveal its contents.
<input type="email"> - HTML: Hypertext Markup Language
WebHTMLElementinputemail
when you create an email input with the proper type value, email, you get automatic validation that the entered text is at least in the correct form to potentially be a legitimate e-mail address.
... the example below creates a 32 character-wide e-mail address entry box, requiring that the contents be no shorter than 3 characters and no longer than 64 characters.
...quest</label><br> <textarea id="message" cols="80" rows="8" required placeholder="my shoes are too tight, and i have forgotten how to dance."></textarea> </div> <input type="submit" value="send request"> </form> our <form> contains one <input> of type email for the user's e-mail address, a <textarea> to enter their message for it into, and an <input> of type "submit", which creates a button to submit the form.
<input type="file"> - HTML: Hypertext Markup Language
WebHTMLElementinputfile
generate a thumbnail preview of the image by calling url.createobjecturl(curfiles[i]).
... function updateimagedisplay() { while(preview.firstchild) { preview.removechild(preview.firstchild); } const curfiles = input.files; if(curfiles.length === 0) { const para = document.createelement('p'); para.textcontent = 'no files currently selected for upload'; preview.appendchild(para); } else { const list = document.createelement('ol'); preview.appendchild(list); for(const file of curfiles) { const listitem = document.createelement('li'); const para = document.createelement('p'); if(validfiletype(file)) { para.textcontent = `file ...
...name ${file.name}, file size ${returnfilesize(file.size)}.`; const image = document.createelement('img'); image.src = url.createobjecturl(file); listitem.appendchild(image); listitem.appendchild(para); } else { para.textcontent = `file name ${file.name}: not a valid file type.
<input type="image"> - HTML: Hypertext Markup Language
WebHTMLElementinputimage
<input> elements of type image are used to create graphical submit buttons, i.e.
...use the <img> element to create image maps instead usemap if usemap is specified, it must be the name of an image map element, <map>, that defines an image map to use with the image.
... using the x and y data points when you submit a form using a button created with <input type="image">, two extra data points are submitted to the server automatically by the browser — x and y.
<input type="radio"> - HTML: Hypertext Markup Language
WebHTMLElementinputradio
for example, if your form needs to ask the user for their preferred contact method, you might create three radio buttons, each with the name property set to contact but one with the value email, one with the value phone, and one with the value mail.
...by specifying appearance: none, you can remove the native styling altogether, and create your own styles for them.
... here we've used a border along with border-radius and a transition to create a nice animating radio selection.
<kbd>: The Keyboard Input element - HTML: Hypertext Markup Language
WebHTMLElementkbd
html <p>you can also create a new document using the keyboard shortcut <kbd><kbd>ctrl</kbd>+<kbd>n</kbd></kbd>.</p> this wraps the entire key sequence in an outer <kbd> element, then each individual key within its own, in order to denote the components of the sequence.
...is without a style sheet applied: with custom styles we can make more sense of this by adding some css: css we add a new style for <kbd> elements, key, which we can apply when rendering keyboard keys: kbd.key { border-radius: 3px; padding: 1px 2px 0; border: 1px solid black; } html then we update the html to use this class on the keys in the output to be presented: <p>you can also create a new document by pressing <kbd><kbd class="key">ctrl</kbd>+<kbd class="key">n</kbd></kbd>.</p> result the result is just what we want!
... for example, you can explain how to choose the "new document" option in the "file" menu using html that looks like this: <p>to create a new file, choose the menu option <kbd><kbd><samp>file</samp></kbd>⇒<kbd><samp>new document</samp></kbd></kbd>.</p> <p>don't forget to click the <kbd><samp>ok</samp></kbd> button to confirm once you've entered the name of the new file.</p> this does some interesting nesting.
<tbody>: The Table Body element - HTML: Hypertext Markup Language
WebHTMLElementtbody
basic example in this relatively simple example, we create a table listing information about a group of students with a <thead> and a <tbody>, with a number of rows in the body.
... result the resulting table looks like this: multiple bodies you can create multiple sections within a table by using multiple <tbody> elements.
...because of that, you need to use a <tr> filled with <th> elements to create headers within each <tbody>.
CSP: script-src - HTTP
the use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the base64-encoded hash of the script or style.
... 'unsafe-inline'; the above content security policy will allow inline <script> elements <script> var inline = 1; </script> you can use a nonce-source to only allow specific inline script blocks: content-security-policy: script-src 'nonce-2726c7f26c' you will have to set the same nonce on the <script> element: <script nonce="2726c7f26c"> var inline = 1; </script> alternatively, you can create hashes from your inline scripts.
... <script>var inline = 1;</script> unsafe eval expressions the 'unsafe-eval' source expression controls several script execution methods that create code from strings.
CSP: style-src - HTTP
the use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the base64-encoded hash of the script or style.
...ttribute on any element: <style> #inline-style { background: red; } </style> <div style="display:none">foo</div> you can use a nonce-source to only allow specific inline style blocks: content-security-policy: style-src 'nonce-2726c7f26c' you will have to set the same nonce on the <style> element: <style nonce="2726c7f26c"> #inline-style { background: red; } </style> alternatively, you can create hashes from your inline styles.
... <style>#inline-style { background: red; }</style> unsafe style expressions the 'unsafe-eval' source expression controls several style methods that create style declarations from strings.
Location - HTTP
WebHTTPHeadersLocation
it only provides a meaning when served with a 3xx (redirection) or 201 (created) status response.
... in cases of resource creation, it indicates the url to the newly created resource.
... location and content-location are different: location indicates the target of a redirection (or the url of a newly created resource), while content-location indicates the direct url to use to access the resource when content negotiation happened, without the need of further content negotiation.
PUT - HTTP
WebHTTPMethodsPUT
the http put request method creates a new resource or replaces a representation of the target resource with the request payload.
... response has body no safe no idempotent yes cacheable no allowed in html forms no syntax put /new.html http/1.1 example request put /new.html http/1.1 host: example.com content-type: text/html content-length: 16 <p>new file</p> responses if the target resource does not have a current representation and the put request successfully creates one, then the origin server must inform the user agent by sending a 201 (created) response.
... http/1.1 201 created content-location: /new.html if the target resource does have a current representation and that representation is successfully modified in accordance with the state of the enclosed representation, then the origin server must send either a 200 (ok) or a 204 (no content) response to indicate successful completion of the request.
Concurrency model and the event loop - JavaScript
function foo(b) { let a = 10 return a + b + 11 } function bar(x) { let y = 3 return foo(x * y) } console.log(bar(7)) //returns 42 when calling bar, a first frame is created containing bar's arguments and local variables.
... when bar calls foo, a second frame is created and pushed on top of the first one containing foo's arguments and local variables.
...as always, calling a function creates a new stack frame for that function's use.
Expressions and operators - JavaScript
x = 42; // implicitly creates window.x var y = 43; var myobj = {h: 4}; // create object with property h delete x; // returns true (can delete if created implicitly) delete y; // returns false (cannot delete if declared with var) delete math.pi; // returns false (cannot delete non-configurable properties) delete myobj.h; // returns true (can delete user-defined properties) deleting array elements since arrays ...
...[] call / create instance () new negation/increment !
... new you can use the new operator to create an instance of a user-defined object type or of one of the built-in object types.
Public class fields - JavaScript
syntax class classwithinstancefield { instancefield = 'instance field' } class classwithstaticfield { static staticfield = 'static field' } class classwithpublicinstancemethod { publicmethod() { return 'hello world' } } examples public static fields public static fields are useful when you want a field to exist only once per class, not on every class instance you create.
...ic method output' } } class subclasswithstaticfield extends classwithstaticfield { static substaticfield = super.basestaticmethod() } console.log(classwithstaticfield.anotherbasestaticfield) // expected output: "base static field" console.log(subclasswithstaticfield.substaticfield) // expected output: "base static method output" public instance fields public instance fields exist on every created instance of a class.
...these are often utility functions, such as functions to create or clone objects.
SyntaxError: invalid regular expression flag "x" - JavaScript
/foo/bar; // syntaxerror: invalid regular expression flag "b" did you intend to create a regular expression?
... let obj = { url: /docs/web }; // syntaxerror: invalid regular expression flag "w" or did you mean to create a string instead?
... add single or double quotes to create a string literal.
TypeError: invalid arguments - JavaScript
typed array constructors require either a length, another typed array, array-like objects, iterable objects or an arraybuffer object to create a new typed array.
... other constructor arguments will not create a valid typed array.
... var ta = new uint8array("nope"); // typeerror: invalid arguments different ways to create a valid uint8array: // from a length var uint8 = new uint8array(2); uint8[0] = 42; console.log(uint8[0]); // 42 console.log(uint8.length); // 2 console.log(uint8.bytes_per_element); // 1 // from an array var arr = new uint8array([21,31]); console.log(arr[1]); // 31 // from another typedarray var x = new uint8array([21, 31]); var y = new uint8array(x); console.log(y[0]); // 21 // from an arraybuffer var buffer = new arraybuffer(8); var z = new uint8array(buffer, 1, 4); // from an iterable var iterable = function*(){ yield* [1,2,3]; }(); ...
Array.prototype.filter() - JavaScript
the filter() method creates a new array with all elements that pass the test implemented by the provided function.
...se{ while (++i !== len){ // checks to see if the key was set if (i in this){ kvalue = t[i]; if (func.call(thisarg, t[i], i, t)){ res[c++] = kvalue; } } } } res.length = c; // shrink down array to proper size return res; }; } examples filtering out all small values the following example uses filter() to create a filtered array that has all elements with values less than 10 removed.
...owing example returns all prime numbers in the array: const array = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]; function isprime(num) { for (let i = 2; num > i; i++) { if (num % i == 0) { return false; } } return num > 1; } console.log(array.filter(isprime)); // [2, 3, 5, 7, 11, 13] filtering invalid entries from json the following example uses filter() to create a filtered json of all elements with non-zero, numeric id.
Array.prototype.forEach() - JavaScript
an object copy function the following code creates a copy of a given object.
... there are different ways to create a copy of an object.
... function copy(obj) { const copy = object.create(object.getprototypeof(obj)) const propnames = object.getownpropertynames(obj) propnames.foreach((name) => { const desc = object.getownpropertydescriptor(obj, name) object.defineproperty(copy, name, desc) }) return copy } const obj1 = { a: 1, b: 2 } const obj2 = copy(obj1) // obj2 looks like obj1 now modifying the array during iteration the following example logs one, two, four.
Array.prototype.push() - JavaScript
this includes the possibility of length being nonexistent, in which case length will also be created.
... examples adding elements to an array the following code creates the sports array containing two elements, then appends two elements to it.
... note that we don't create an array to store a collection of objects.
ArrayBuffer() constructor - JavaScript
the arraybuffer() constructor is used to create arraybuffer objects.
... syntax new arraybuffer(length) parameters length the size, in bytes, of the array buffer to create.
... var dv = arraybuffer(10); // typeerror: calling a builtin arraybuffer constructor // without new is forbidden var dv = new arraybuffer(10); examples creating an arraybuffer in this example, we create a 8-byte buffer with a int32array view referring to the buffer: var buffer = new arraybuffer(8); var view = new int32array(buffer); specifications specification ecmascript (ecma-262)the definition of 'arraybuffer' in that specification.
Date() constructor - JavaScript
creates a javascript date instance that represents a single moment in time in a platform-independent format.
... parameters there are four basic forms for the date() constructor: no parameters when no parameters are provided, the newly-created date object represents the current date and time as of the time of instantiation.
... examples several ways to create a date object the following examples show several ways to create javascript dates: note: parsing of date strings with the date constructor (and date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies.
Date - JavaScript
constructor date() creates a new date object.
... examples several ways to create a date object the following examples show several ways to create javascript dates: note: parsing of date strings with the date constructor (and date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies.
...e month is 0-indexed let birthday = new date(1995, 11, 17, 3, 24, 0) let birthday = new date(628021800000) // passing epoch timestamp to get date, month and year or time let [month, date, year] = ( new date() ).tolocaledatestring().split("/") let [hour, minute, second] = ( new date() ).tolocaletimestring().slice(0,7).split(":") two digit years map to 1900 – 1999 in order to create and get dates between the years 0 and 99 the date.prototype.setfullyear() and date.prototype.getfullyear() methods should be used.
FinalizationRegistry - JavaScript
you create the registry passing in the callback: const registry = new finalizationregistry(heldvalue => { // ....
...registry.unregister(tokenobject); constructor finalizationregistry() creates a new finalizationregistry object.
... examples creating a new registry you create the registry passing in the callback: const registry = new finalizationregistry(heldvalue => { // ....
Function.prototype.apply() - JavaScript
concat does have the desired behaviour in this case, but it does not append to the existing array—it instead creates and returns a new array.
... in the following example we will create a global function method called construct, which will enable you to use an array-like object with a constructor instead of an arguments list.
... function.prototype.construct = function(aargs) { let onew = object.create(this.prototype); this.apply(onew, aargs); return onew; }; note: the object.create() method used above is relatively new.
Function.name - JavaScript
a function object's read-only name property indicates the function's name as specified when it was created, or it may be rather anonymous or ''(an empty string) for functions created anonymously.
... function dosomething() {} dosomething.name; // "dosomething" function constructor name functions created with the syntax new function(...) or just function(...) create function objects and their name is "anonymous".
... (new function).name; // "anonymous" anonymous function expression anonymous function expressions that were created using the keyword function or arrow functions would have ""(an empty string) as their name.
Intl.ListFormat - JavaScript
constructor intl.listformat() creates a new listformat object.
... examples using format the following example shows how to create a list formatter using the english language.
...rmat('en-gb', { style: 'long', type: 'conjunction' }).format(list)); // > motorcycle, bus and car console.log(new intl.listformat('en-gb', { style: 'short', type: 'disjunction' }).format(list)); // > motorcycle, bus or car console.log(new intl.listformat('en-gb', { style: 'narrow', type: 'unit' }).format(list)); // > motorcycle bus car using formattoparts the following example shows how to create a list formatter returning formatted parts const list = ['motorcycle', 'bus', 'car']; console.log(new intl.listformat('en-gb', { style: 'long', type: 'conjunction' }).formattoparts(list)); // [ { "type": "element", "value": "motorcycle" }, // { "type": "literal", "value": ", " }, // { "type": "element", "value": "bus" }, // { "type": "literal", "value": ", and " }, // { "type": "element...
Intl.RelativeTimeFormat.prototype.format() - JavaScript
examples basic format usage the following example shows how to create a relative time formatter using the english language.
... // create a relative time formatter in your locale // with default values explicitly passed in.
... // create a relative time formatter in your locale // with numeric: "auto" option value passed in.
Intl.RelativeTimeFormat - JavaScript
constructor intl.relativetimeformat.relativetimeformat() creates a new intl.relativetimeformat object.
... // create a relative time formatter in your locale // with default values explicitly passed in.
...rtf.format(1, "day"); // > "in 1 day" using formattoparts the following example shows how to create a relative time formatter returning formatted parts const rtf = new intl.relativetimeformat("en", { numeric: "auto" }); // format relative time using the day unit.
Map - JavaScript
note: as of es5, this can be bypassed by using object.create(null), but this is seldom done.
...sie', {phone: "213-555-1234", address: "123 n 1st ave"}) contacts.has('jessie') // true contacts.get('hilary') // undefined contacts.set('hilary', {phone: "617-555-4321", address: "321 s 2nd st"}) contacts.get('jessie') // {phone: "213-555-1234", address: "123 n 1st ave"} contacts.delete('raymond') // false contacts.delete('jessie') // true console.log(contacts.size) // 1 constructor map() creates a new map object.
... static properties get map[@@species] the constructor function that is used to create derived objects.
Object.prototype.toString() - JavaScript
examples overriding the default tostring method you can create a function to be called in place of the default tostring() method.
...the tostring() method you create can be any value you want, but it will be most useful if it carries information about the object.
... the following code defines the dog object type and creates thedog, an object of type dog: function dog(name, breed, color, sex) { this.name = name; this.breed = breed; this.color = color; this.sex = sex; } thedog = new dog('gabby', 'lab', 'chocolate', 'female'); if you call the tostring() method on this custom object, it returns the default value inherited from object: thedog.tostring(); // returns [object object] the following code creates and assigns dogtostring() to override the default tostring() method.
Object.prototype.valueOf() - JavaScript
when you create a custom object, you can override object.prototype.valueof() to call a custom method instead of the default object method.
... overriding valueof for custom objects you can create a function to be called in place of the default valueof method.
... suppose you have an object type mynumbertype and you want to create a valueof method for it.
Proxy.revocable() - JavaScript
the proxy.revocable() method is used to create a revocable proxy object.
... return value a newly created revocable proxy object is returned.
... proxy a proxy object created with new proxy(target, handler) call.
RegExp() constructor - JavaScript
the regexp constructor creates a regular expression object for matching text with a pattern.
... examples literal notation and constructor there are two ways to create a regexp object: a literal notation and a constructor.
... the following three expressions create the same regular expression: /ab+c/i new regexp(/ab+c/, 'i') // literal notation new regexp('ab+c', 'i') // constructor the literal notation results in compilation of the regular expression when the expression is evaluated.
Planned changes to shared memory - JavaScript
there is standardization work ongoing that enables developers to create sharedarraybuffer objects again, but changes are needed in order to be use these across threads (i.e., postmessage() for sharedarraybuffer objects throws by default).
... these changes provide further isolation between sites and help reduce the impact of attacks with high-resolution timers, which can be created with shared memory.
... webassembly shared memory the webassembly threads proposal allows webassembly.memory objects to be created with a new shared constructor flag.
SharedArrayBuffer() constructor - JavaScript
the sharedarraybuffer() constructor is used to create a sharedarraybuffer object representing a generic, fixed-length raw binary data buffer, similar to the arraybuffer object.
... syntax new sharedarraybuffer([length]) parameters length the size, in bytes, of the array buffer to create.
... examples always use the new operator to create a sharedarraybuffer sharedarraybuffer constructors are required to be constructed with a new operator.
String.prototype.anchor() - JavaScript
the anchor() method creates a string beginning with an <a name="..."> start tag, then some text, and then an </a> end tag.
...also, the html specification no longer allows the <a> element to have a name attribute, so this method doesn't even create valid markup.
...also, the html specification no longer allows the <a> element to have a name attribute, so this method doesn't even create valid markup.
String.fromCodePoint() - JavaScript
the static string.fromcodepoint() method returns a string created by using the specified sequence of code points.
... return value a string created by using the specified sequence of code points.
... because fromcodepoint() is a static method of string, you must call it as string.fromcodepoint(), rather than as a method of a string object you created.
String.prototype.link() - JavaScript
the link() method creates a string representing the code for an <a> html element to be used as a hypertext link to another url.
... description use the link() method to create an html snippet for a hypertext link.
... links created with the link() method become elements in the links array of the document object.
Symbol() constructor - JavaScript
examples creating symbols to create a new primitive symbol, you write symbol() with an optional string as its description: let sym1 = symbol() let sym2 = symbol('foo') let sym3 = symbol('foo') the above code creates three new symbols.
...it creates a new symbol each time: symbol('foo') === symbol('foo') // false new symbol(...) the following syntax with the new operator will throw a typeerror: let sym = new symbol() // typeerror this prevents authors from creating an explicit symbol wrapper object instead of a new symbol value and might be surprising as creating explicit wrapper objects around primitive data types is generally possible (for example, new boolean, new string and new number).
... if you really want to create a symbol wrapper object, you can use the object() function: let sym = symbol('foo'); let symobj = object(sym); typeof sym // => "symbol" typeof symobj // => "object" specifications specification ecmascript (ecma-262)the definition of 'symbol constructor' in that specification.
TypedArray.of() - JavaScript
the typedarray.of() method creates a new typed array from a variable number of arguments.
... syntax typedarray.of(element0[, element1[, ...[, elementn]]]) where typedarray is one of: int8array uint8array uint8clampedarray int16array uint16array int32array uint32array float32array float64array bigint64array biguint64array parameters elementn elements of which to create the typed array.
...hence, when working with proxy objects, it calls handler.set to create new elements rather than handler.defineproperty.
WebAssembly.Global - JavaScript
constructor webassembly.global() creates a new global object.
... instance properties global.prototype.constructor returns the function that created this object's instance.
... examples creating a new global instance the following example shows a new global instance being created using the webassembly.global() constructor.
WebAssembly.Table() constructor - JavaScript
the webassembly.table() constructor creates a new table object of the given size and element type.
... examples creating a new webassembly table instance the following example (see table2.html source code and live version) creates a new webassembly table instance with an initial size of 2 elements.
... var tbl = new webassembly.table({initial:2, element:"anyfunc"}); console.log(tbl.length); // "2" console.log(tbl.get(0)); // "null" console.log(tbl.get(1)); // "null" we then create an import object that contains the table: var importobj = { js: { tbl:tbl } }; finally, we load and instantiate a wasm module (table2.wasm) using the webassembly.instantiatestreaming() method.
WebAssembly.instantiate() - JavaScript
importobject optional an object containing the values to be imported into the newly-created instance, such as functions or webassembly.memory objects.
... importobject optional an object containing the values to be imported into the newly-created instance, such as functions or webassembly.memory objects.
...when the module is received, we create an instance from it using the webassembly.instantiate() method and invoke an exported function from inside it.
Spread syntax (...) - JavaScript
ds = [1970, 0, 1]; // 1 jan 1970 const d = new date(...datefields); to use new with an array of parameters without spread syntax, you would have to do it indirectly through partial application: function applyandnew(constructor, args) { function partial () { return constructor.apply(this, args); }; if (typeof constructor.prototype === "object") { partial.prototype = object.create(constructor.prototype); } return partial; } function myconstructor () { console.log("arguments.length: " + arguments.length); console.log(arguments); this.prop1="val1"; this.prop2="val2"; }; const myarguments = ["hi", "how", "are", "you", "mr", null]; const myconstructorwitharguments = applyandnew(myconstructor, myarguments); console.log(new myconstructorwitharguments); // ...
...(internal log of myconstructor): arguments.length: 6 // (internal log of myconstructor): ["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.
...without spread syntax, this is done as: const arr1 = [0, 1, 2]; const arr2 = [3, 4, 5]; // prepend all items from arr2 onto arr1 array.prototype.unshift.apply(arr1, arr2) // arr1 is now [3, 4, 5, 0, 1, 2] with spread syntax, this becomes: let arr1 = [0, 1, 2]; let arr2 = [3, 4, 5]; arr1 = [...arr2, ...arr1]; // arr1 is now [3, 4, 5, 0, 1, 2] note: unlike unshift(), this creates a new arr1, and does not modify the original arr1 array in-place.
instanceof - JavaScript
however, objects created with the object literal notation are an exception here: although the prototype is undefined, instanceof object returns true.
... let simplestr = 'this is a simple string' let mystring = new string() let newstr = new string('string created with constructor') let mydate = new date() let myobj = {} let mynonobj = object.create(null) simplestr instanceof string // returns false, string literal is not an object mystring instanceof string // returns true newstr instanceof string // returns true mystring instanceof object // returns true myobj instanceof object // returns true, every object literal has object.prototype as prototype ({}) instanceof object // returns true, same case as above mynonobj instanceof object // returns false, prototype is end of prototype chain (null) mystring instanceof date // returns false mydate instanceof date // returns true mydate instanceof object ...
... // returns true mydate instanceof string // returns false demonstrating that mycar is of type car and type object the following code creates an object type car and an instance of that object type, mycar.
const - JavaScript
description this declaration creates a constant whose scope can be either global or local to the block in which it is declared.
...(this makes sense, given that it can't be changed later.) the const declaration creates a read-only reference to a value.
... if (my_fav === 7) { // this is fine and creates a block scoped my_fav variable // (works equally well with let to declare a block scoped non const variable) let my_fav = 20; // my_fav is now 20 console.log('my favorite number is ' + my_fav); // this gets hoisted into the global context and throws an error var my_fav = 20; } // my_fav is still 7 console.log('my favorite number is ' + my_fav); const needs to be initialized // ...
function declaration - JavaScript
description a function created with a function declaration is a function object and has all the properties, methods and behavior of function objects.
... a function can also be created using an expression (see function expression).
... conditionally created functions functions can be conditionally declared, that is, a function statement can be nested within an if statement, however the results are inconsistent across implementations and therefore this pattern should not be used in production code.
Statements and declarations - JavaScript
iterations do...while creates a loop that executes a specified statement until the test condition evaluates to false.
... for creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement executed in the loop.
... while creates a loop that executes a specified statement as long as the test condition evaluates to true.
Transitioning to strict mode - JavaScript
in strict mode, the arguments object is created and initialized with the same values than the named arguments, but changes to either the arguments object or the named arguments aren't reflected in one another.
... change to eval in strict mode code, eval doesn't create a new variable in the scope from which it was called.
... stay away from semantic differences eval: use it only if you know what you're doing arguments: always access function arguments via their name or perform a copy of the arguments object using: var args = array.prototype.slice.call(arguments) as the first line of your function this: only use this when it refers to an object you created.
Media container formats (file types) - Web media technologies
created by the moving picture experts group (mpeg), these formats are widely used in physical media, including as the format of the video on dvd media.
... safari theora yes vp8 yes vp9 yes audio codecs supported by ogg codec browser support chrome edge firefox safari flac yes opus yes vorbis yes quicktime the quicktime file format (qtff, qt, or mov) was created by apple for use by its media framework of the same name.
... to do this, you create a <video> (or <audio>) element with no src attribute.
Image file type and format guide - Web media technologies
it is technically possible to tile multiple image blocks, each with its own color palette, to create truecolor images, but in practice this is rarely done.
... svg (scalable vector graphics) svg is an xml-based vector graphics format that specifies the contents of an image as a set of drawing commands that create shapes, lines, apply colors, filters, and so forth.
... tiff (tagged image file format) tiff is a raster graphics file format which was created to store scanned photos, although it can be any kind of image.
Animation performance and frame rate - Web Performance
we'll also discuss some tips to create and maintain a fast and steady frame rate.
...the browser creates the animation as a transition from each keyframe to the next.
... compared with animating elements using javascript, css animations can be easier to create.
Critical rendering path - Web Performance
the document object model is created as the html is parsed.
...the browser engine combines the two to create the render tree.
...once the render tree is created and layout occurs, the pixels can be painted to the screen.
Populating the page: how browsers work - Web Performance
in terms of web performance optimization, there are lower hanging fruit, as the total time to create the cssom is generally less than the time it takes for one dns lookup.
... other processes javascript compilation while the css is being parsed and the cssom created, other assets, including javascript files, are downloading (thanks to the preload scanner).
...the cssom and dom trees created in the parsing step are combined into a render tree which is then used to compute the layout of every visible element, which is then painted to the screen.
Progressive web app structure - Progressive web apps (PWAs)
you can <a href="https://github.com/mdn/pwa-examples/blob/master/js13kpwa">fork js13kpwa on github</a> to check its source code.</p> <button id="notifications">request dummy notifications</button> <section id="content"> // content inserted in here </section> </main> <footer> <p>© js13kgames 2012-2018, created and maintained by <a href="http://end3r.com">andrzej mazur</a> from <a href="http://enclavegames.com">enclave games</a>.</p> </footer> </body> </html> the <head> section contains some basic info like title, description and links to css, web manifest, games content js file, and app.js — that's where our javascript application is initialized.
...egister('/pwa-examples/js13kpwa/sw.js'); }; the next code block requests permission for notifications when a button is clicked: var button = document.getelementbyid("notifications"); button.addeventlistener('click', function(e) { notification.requestpermission().then(function(result) { if(result === 'granted') { randomnotification(); } }); }); the last block creates notifications that display a randomly-selected item from the games list: function randomnotification() { var randomitem = math.floor(math.random()*games.length); var notiftitle = games[randomitem].name; var notifbody = 'created by '+games[randomitem].author+'.'; var notifimg = 'data/img/'+games[randomitem].slug+'.jpg'; var options = { body: notifbody, icon: n...
...otifimg } var notif = new notification(notiftitle, options); settimeout(randomnotification, 30000); } the service worker the last file we will quickly look at is the service worker: sw.js — it first imports data from the games.js file: self.importscripts('data/games.js'); next, it creates a list of all the files to be cached, both from the app shell and the content: var cachename = 'js13kpwa-v1'; var appshellfiles = [ '/pwa-examples/js13kpwa/', '/pwa-examples/js13kpwa/index.html', '/pwa-examples/js13kpwa/app.js', '/pwa-examples/js13kpwa/style.css', '/pwa-examples/js13kpwa/fonts/graduate.eot', '/pwa-examples/js13kpwa/fonts/graduate.ttf', '/pwa-examples/js13kpwa/fonts/graduate.woff', '/pwa-examples/js13kpwa/favicon.ico', '/pwa-examples/js13kpwa/img/js13kgames.p...
Introduction to progressive web apps - Progressive web apps (PWAs)
pwas give us the ability to create web apps that can enjoy these same advantages.
... as we hinted at above, pwas are not created with a single technology.
... offering these features and making use of all the advantages offered by web applications can create a compelling, highly flexible offering for your users and customers.
Progressive web apps (PWAs)
with service workers, web developers can create reliably fast web pages and offline experiences.
... instant loading web apps with an application shell architecture — a guide to using the app shell coding pattern to create apps that load quickly.
... mobile first — often when creating responsive application layouts, it makes sense to create the mobile layout as the default, and build wider layouts on top.
Basic shapes - SVG: Scalable Vector Graphics
basic shapes to insert a shape, you create an element in the document.
...some are slightly redundant in that they can be created by other shapes, but they're all there for your convenience and to keep your svg documents as short and as readable as possible.
... note: a rectangle is a type of polygon, so a polygon can be used to create a <rect/> element in cases where you need a little more flexibility.
Clipping and masking - SVG: Scalable Vector Graphics
« previousnext » erasing part of what one has created might at first sight look contradictory.
... but when you try to create a semicircle in svg, you will find out the use of the following properties quickly.
... creating clips we create the above mentioned semicircle based on a circle element: <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <defs> <clippath id="cut-off-bottom"> <rect x="0" y="0" width="200" height="100" /> </clippath> </defs> <circle cx="100" cy="100" r="100" clip-path="url(#cut-off-bottom)" /> </svg> centered at (100,100) a circle with radius 100 is painted.
XPath snippets - XPath
function evaluatexpath(anode, aexpr) { var xpe = new xpathevaluator(); var nsresolver = xpe.creatensresolver(anode.ownerdocument == null ?
...scripts in a web document which might be accessed by edge or internet explorer users should replace the call to new xpathevaluator() with the following fragment: // xpathevaluator is implemented on objects that implement document var xpe = anode.ownerdocument || anode; in that case the creation of the xpathnsresolver can be simplified as: var nsresolver = xpe.creatensresolver(xpe.documentelement); note however that creatensresolver should only be used if you are sure the namespace prefixes in the xpath expression match those in the document you want to query (and that no default namespace is being used (though see document.creatensresolver for a workaround)).
... sample usage assume we have the following xml document (see also how to create a dom tree and parsing and serializing xml): example: an xml document to use with the custom evaluatexpath() utility function <?xml version="1.0"?> <people> <person first-name="eric" middle-initial="h" last-name="jung"> <address street="321 south st" city="denver" state="co" country="usa"/> <address street="123 main st" city="arlington" state="ma" country="usa"/> </person> <person first-name="jed" last-name="brown"> <address st...
Index - XSLT: Extensible Stylesheet Language Transformations
WebXSLTIndex
22 <xsl:attribute-set> element, reference, xslt, attribute-set the <xsl:attribute-set> element creates a named set of attributes, which can then be applied as whole to the output document, in a manner similar to named styles in css.
... 23 <xsl:attribute> attribute, element, reference, xslt the <xsl:attribute> element creates an attribute in the output document, using any values that can be accessed from the stylesheet.
... 30 <xsl:element> element, reference, xslt the <xsl:element> element creates an element in the output document.
JavaScript/XSLT Bindings - XSLT: Extensible Stylesheet Language Transformations
to process part of a page's dom, it is necessary to first create an xml document in memory.
... figure 2 : creating an xml document based on part of a document's dom // create a new xml document in memory var xmlref = document.implementation.createdocument("", "", null); // we want to move a part of the dom from an html document to an xml document.
...you must use the domparser.no to create any document, as this is handled by the domparser.
Loading and running WebAssembly code - WebAssembly
the older webassembly.compile/webassembly.instantiate methods require you to create an arraybuffer containing your webassembly module binary after fetching the raw bytes, and then compile/instantiate it.
...the object looks like this: { module : module // the newly compiled webassembly.module object, instance : instance // a new webassembly.instance of the module object } note: usually we only care about the instance, but it’s useful to have the module in case we want to cache it, share it with another worker or window via postmessage(), or simply create more instances.
...again, assuming our module is called simple.wasm: create a new xmlhttprequest() instance, and use its open() method to open a request, setting the request method to get, and declaring the path to the file we want to fetch.
WebAssembly
webassembly.compileerror() creates a new webassembly compileerror object.
... webassembly.linkerror() creates a new webassembly linkerror object.
... webassembly.runtimeerror() creates a new webassembly runtimeerror object.
Navigator.mozNotification - Archive of obsolete content
method overview notification createnotification(in domstring title, in domstring description, in domstring iconurl optional); methods createnotification() creates and returns a notification object that can be used to display the specified message with an optional url.
... notification createnotification( in domstring title, in domstring description, in domstring iconurloptional ); parameters title the notification title.
XUL Migration Guide - Archive of obsolete content
you can keep the "chrome.manifest" file in your add-on's root directory and create a directory there called "chrome".
... using third party packages the sdk is extensible by design: developers can create new modules filling gaps in the sdk, and package them for distribution and reuse.
request - Archive of obsolete content
globals constructors request(options) this constructor creates a request object that can be used to make network requests.
... once a request object has been created a get request can be executed by calling its get() method, a post request by calling its post() method, and so on.
ui - Archive of obsolete content
from firefox 30 onwards, you can attach panels to toggle buttons, by passing the button into the panel's constructor or its show() method: frame a frame enables you to create an html iframe, using bundled html, css and javascript.
...once you've created a frame you need to add it to a toolbar.
url - Archive of obsolete content
globals constructors url(source, base) the url constructor creates an object that represents a url, verifying that the provided string is a valid url in the process.
... dataurl(uri) the dataurl constructor creates an object that represents a data: url, verifying that the provided string is a valid data: url in the process.
content/worker - Archive of obsolete content
globals constructors worker(options) creates a content worker.
... parameters options : object required options: name type window object the content window to create javascript sandbox for communication with.
core/promise - Archive of obsolete content
this is the common case, but every once in a while, you will need to create a promise from scratch.
... treat errors as promises now that we can create all kinds of eventual values, it's useful to have a way to create eventual errors.
frame/utils - Archive of obsolete content
usage module exports create function that takes the nsidomdocument of a privileged document and creates a browser element in its documentelement: let { open } = require('sdk/window/utils'); let { create } = require('sdk/frame/utils'); let window = open('data:text/html,foo'); let frame = create(window.document); optionally create can be passed set of options to configure created frame even further.
... execution of scripts may easily be enabled: let { open } = require('sdk/window/utils'); let { create } = require('sdk/frame/utils'); let window = open('data:text/html,top'); let frame = create(window.document, { uri: 'data:text/html,<script>console.log("running");</script>', allowjavascript: true }); } globals functions create(document, options) creates a xul browser element in a privileged document.
lang/functional - Archive of obsolete content
arguments : mixed additional arguments to pass to fn upon execution once(fn) creates a version of the input function that can only be called one time.
... chain(fn) creates a version of the input function that will return this.
loader/sandbox - Archive of obsolete content
experimental create javascript sandboxes and execute scripts in them.
... usage create a sandbox to create a sandbox: const { sandbox, evaluate, load } = require("sdk/loader/sandbox"); let scope = sandbox('http://example.com'); the argument passed to the sandbox defines its privileges.
remote/child - Archive of obsolete content
listen to attach and detach events to hear as frames are created and destroyed.
... methods forevery calls the callback for every existing frame and any new frames created in the future.
stylesheet/style - Archive of obsolete content
globals constructors style(options) the style constructor creates an object that represents style modifications via stylesheet file(s) or/and css rules.
... the style created can be applied to a content by calling attach, and removed using detach.
test/assert - Archive of obsolete content
for example: var a = 1; exports["test value of a"] = function(assert) { assert.ok(a == 1, "test that a is 1"); } require("sdk/test").run(exports); globals constructors assert(logger) create a new assert object.
... notdeepequal(actual, expected, message) tests that two objects do not have a deep equality relation, using the negation of the test for deep equality: assert.notdeepequal({ a: "foo" }, object.create({ a: "foo" }), "object's inherit from different prototypes"); parameters actual : object the actual result.
ui/id - Archive of obsolete content
experimental create ui component ids.
...*/); identify.define(thingy, thing => thing.guid); parameters object : object object to create an id for.
jpmignore - Archive of obsolete content
use .jpmignore to ignore files from your xpi builds created via jpm.
... here is an example: # ignore .ds_store files created by mac .ds_store # ignore any zip or xpi files *.zip *.xpi # ignore specific directory # you can start patterns with a forward slash (/) to avoid recursivity.
Using third-party modules (jpm) - Archive of obsolete content
the add-on sdk is extensible by design: you can use the modules that ship inside firefox, but you can also create your own modules and make them available for anyone else to use.
...in your add-on code, you can require() modules by passing a path to the module starting from, but not including "node_modules": var menuitems = require("menuitem"); details create a new directory called, for example, "my-menuitem", navigate to it, type "jpm init" and accept all the defaults: mkdir my-menuitem cd my-menuitem jpm init install the menuitem package from npm: npm install menuitem --save this will install the package in the current directory, under a directory called "node_modules".
Bootstrapped extensions - Archive of obsolete content
backward compatibility because older versions of firefox don't know about the bootstrap property or bootstrap.js file, it's not overly difficult to create an xpi that will work on both as a bootstrappable extension and as a traditional extension.
... create your extension as a bootstrappable extension, then add the traditional overlays as well.
Downloading Files - Archive of obsolete content
downloading files to download a file, create an instance of nsiwebbrowserpersist and call its nsiwebbrowserpersist.saveuri() method, passing it a url to download and an nsifile instance representing the local file name/path.
...nts.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); var channel = ioserv.newchannel(url, 0, null); var stream = channel.open(); if (channel instanceof components.interfaces.nsihttpchannel && channel.responsestatus != 200) { return ""; } var bstream = components.classes["@mozilla.org/binaryinputstream;1"] .createinstance(components.interfaces.nsibinaryinputstream); bstream.setinputstream(stream); var size = 0; var file_data = ""; while(size = bstream.available()) { file_data += bstream.readbytes(size); } return file_data; } see also nsidownloadprogresslistener saving an arbitrary url to a local file customizing the download progress bar appearance ...
Drag & Drop - Archive of obsolete content
var _ios = components.classes['@mozilla.org/network/io-service;1'].getservice(components.interfaces.nsiioservice); var uris = new array(); // if sourcenode is not null, then the drop was from inside the application if (dragsession.sourcenode) return; // setup a transfer item to retrieve the file data var trans = components.classes["@mozilla.org/widget/transferable;1"].createinstance(components.interfaces.nsitransferable); trans.adddataflavor("text/x-moz-url"); trans.adddataflavor("application/x-moz-file"); for (var i=0; i<dragsession.numdropitems; i++) { var uri = null; dragsession.getdata(trans, i); var flavor = {}, data = {}, length = {}; trans.getanytransferdata(flavor, data, length); if (data) { try { ...
...the _dragdrop function retrieves the file uri data from the drag session and creates an array of file uris that the xul application can use.
SVG General - Archive of obsolete content
svg requires you to use setattributens to add attributes to a newly created svg dom element.
...here is the script: var svgns = "http://www.w3.org/2000/svg"; var xlinkns = "http://www.w3.org/1999/xlink"; var attr_map = { "classname": "class", "svghref": "href" } var ns_map = { "svghref": xlinkns }; function makesvg(tag, attributes) { var elem = document.createelementns(svgns, tag); for (var attribute in attributes) { var name = (attribute in attr_map ?
Sidebar - Archive of obsolete content
a web page can use window.sidebar to create bookmark with that property.
...for example, use this in your sidebar's unload event handler: mainwindow.document.getelementbyid("sidebar-splitter").hidden = mainwindow.document.getelementbyid("sidebar-box").hidden; see also bootstrap demo addon that creates a sidebar with html content: https://gist.github.com/noitidart/8728393 ...
Windows - Archive of obsolete content
each time a new window is created, it gets assigned an id one greater than the last created window.
... var hr = document.createelementns("http://www.w3.org/1999/xhtml", "html:hr"); document.getelementbyid("id1").appendchild(hr); ...
Communication between HTML and your extension - Archive of obsolete content
what i tried my first attempt was trying to create an xbl component.
...after the html component was update with the result of the ajax request, i created and dispatched the event like this: var event = document.createevent("events"); event.initevent("my-custom-event", true, true); document.body.dispatchevent(event); in the code of the extension that catches the loading of a new page i added this code: var doc = aevent.originaltarget; // doc is document that triggered "onload" event // do something with the loaded page.
Custom about: URLs - Archive of obsolete content
this example creates an about page with url about:myaboutpage which takes a user to a page that writes some text out.
...security_or_aloadinfo is aloadinfo channel = services.io.newchannelfromuriwithloadinfo(uri, asecurity_or_aloadinfo); } else { channel = services.io.newchannel(aboutpage_uri, null, null); } channel.originaluri = auri; return channel; } } class factory { constructor(component) { this.component = component; this.register(); object.freeze(this); } createinstance(outer, iid) { if (outer) { throw cr.ns_error_no_aggregation; } return new this.component(); } register() { cm.registerfactory(this.component.classid, this.component.classdescription, this.component.contractid, this); } unregister() { cm.unregisterfactory(this.component.prototype.classi...
Deploying a Plugin as an Extension - Archive of obsolete content
in this article, we will create an extension for the rhapsody player engine.
...simply use the zip utility to create the xpi file.
Developing add-ons - Archive of obsolete content
this page will help guide you to the information you need in order to create add-ons for firefox, thunderbird, or other software based on the mozilla platform, as well as how to distribute your add-ons.
... plugins information about how to create plugins, which are binary components that let mozilla based software display content they can't handle natively.
Adding Events and Commands - Archive of obsolete content
the dom createevent function allows you to create custom events that you can dispatch and capture.
...you can create an extension that adds toolbar buttons, statusbar buttons and menu items, all with equivalent behavior, and without having to repeat lots of xul code in the process.
Adding Toolbars and Toolbar Buttons - Archive of obsolete content
with this knowledge you should be able to create simple toolbars and toolbar buttons you can add to firefox.
...the menu and menu-button types allow you to create buttons that open popup menus beneath them.
Adding menus and submenus - Archive of obsolete content
the separator is usually displayed as a horizontal line that creates a logical division between different types of menuitem elements, keeping everything more organized.
...dom functions like createelement and appendchild can be used to accomplish this.
Intercepting Page Loads - Archive of obsolete content
you can create an xpcom component that extends nsiwebprogresslistener and use the addprogresslistener method in the service to include it.
...you can create an xpcom component that extends nsicontentpolicy and register it to the "content-policy" category using the nsicategorymanager.
Introduction - Archive of obsolete content
xul school was created by appcoast (formerly glaxstar), one of the few companies dedicated to building high-quality firefox extensions.
... a team of over a dozen xul developers conformed glaxstar at the time this tutorial was created, and the combined experiences of years creating firefox extensions are reflected here.
JavaScript Object Management - Archive of obsolete content
for example: _stringbundle, _createusernode().
...but it is sometimes necessary to define classes and be able to create multiple instances.
Observer Notifications - Archive of obsolete content
to create an observer, you need to implement the nsiobserver interface.
... createinstance(components.interfaces.nsisupportsstring); // assign some text to data attribute subject.data = "this is a test."; // notify all registered observers observerservice.notifyobservers( subject, "xulschoolhello-test-topic", "hello"); } in the notifytest method, the notifyobservers call is used to notify all registered observers about the notification topic "xulschoolhello-tes...
The Box Model - Archive of obsolete content
complex elements are created from simpler ones through xbl, which will be covered later on.
... text links xul makes it very easy for you to create a label that is also a link.
Promises - Archive of obsolete content
let download_2 = yield downloads.createdownload({ source: url_2, target: path_2, }); // add it to the downloads list used by the download manager ui.
... try { this.data = json.parse( yield os.file.read(this.path, { encoding: "utf-8" })); } catch (e if e.becausenosuchfile) { this.data = json.parse(json.stringify(default_)); } // create a saver to write our json-stringified data to our // path, at 1000ms minimum intervals.
An Interview With Douglas Bowman of Wired News - Archive of obsolete content
but adding a third column to the mix created too many width variables for some browsers to dynamically calculate a total.
...however, since some of our stories are broken up into 2 or 3 pages, we created a slightly altered template for print versions which pulls the entire text of the story into one (web) page.
CSS3 - Archive of obsolete content
css color module level 3 recommendation since june 7th, 2011 adds the opacity property, and the hsl(), hsla(), rgba() and rgb() functions to create <color> values.
...though changes are still expected, they shouldn't create incompatibilities with current implementations; they should mainly define behavior in edge cases.
Creating a dynamic status bar extension - Archive of obsolete content
« previousnext » this article builds upon the article creating a status bar extension, which creates a static status bar panel in the firefox status bar, by dynamically updating its content with information fetched from the web every few minutes.
...the first thing we do is create a new xmlhttprequest object to use for processing our request.
Getting the page URL in NPAPI plugin - Archive of obsolete content
npn_getvalue( m_pnpinstance, npnvwindownpobject, &swindowobj ); // create a "location" identifier.
...npobject *locationobj = variantvalue.value.objectvalue; // create a "href" identifier.
Creating a Web based tone generator - Archive of obsolete content
this example creates a simple tone generator, and plays the resulting tone.
...in order to always have samples to play, a buffer of 500 ms is created.
Source code directories overview - Archive of obsolete content
it forms the c substructure which creates, destroys and manipulates built-in and user-defined objects according to the javascript script.
...document.goofy = 1), this code will create the "goofy" node, put it on the "document" node and manipulate it according to any later javascript commands.
Working with BFCache - Archive of obsolete content
when the user hits the 'back' button, either the window in bfcache is thawed or a new inner window is created, depending on whether there's a window in the bfcache.
...the dom is recreated during the parsing process, and scripts are recompiled (and also reloaded, probably from the http cache).
Creating a hybrid CD - Archive of obsolete content
the utility mkhybrid lets you create hybrid cds that work with all three filesystems.
...here's what i did to create the cd for the second anniversary party.
In-Depth - Archive of obsolete content
mozilla css properties mozilla.org created their own css properties to allow them to use the technology for the ui of mozilla.
...place this xml file in \classic\skin\classic\communicator\toolbar\toolbarbindings.xml (you will need to create the sub directory).
Creating a Skin for Firefox/Getting Started - Archive of obsolete content
so create a new directory called my_theme.
... repackaging jar now all you need to do is repackage a jar file with the following directory structure, using your favorite archive manager to create a zip archive: /browser/* /communicator/* /global/* /help/* /mozapps/* /contents.rdf /install.rdf /icon.png /preview.png make sure not to just zip up the my_theme parent directory since that will cause the drag and drop install in the next section to fail without error messages.
Drag and Drop - Archive of obsolete content
note that drag sessions can be created from within mozilla itself or from other applications.
... nsidragservice.dragdrop_action_link a link (or shortcut or alias) to the item being dragged should be created in the dropped location.
Helper Apps (and a bit of Save As) - Archive of obsolete content
the nsexternalhelperappservice looks up the nsimimeinfo for the load and creates an nsihelperapplauncher to manage the load.
... nsexternalapphandler::onstartrequest creates a temporary file with a salted name to hold the data.
JavaScript crypto - Archive of obsolete content
the generatecrmfrequest() function generates a key and creates a crmf request object.
...on private key, and text string from the script (possibly containing naming or enrollment info) are signed by the user signed blob is returned to the script script submits signed blob and any other necessary info to the ca/ra ca/ra verifies signature on signed blob ca/ra validates identity of user ca/ra sends wrapped encryption private key to kra kra sends escrow verification back to ca ca creates and signs certificates ca sends certificates back to the user (importusercertificates) typical use the ca's enrollment page could look something like this: <!doctype html> <h2>request a cert</h2> <form name="reqform" method="post" action="http://your.ra.site.org"> <p><input type=hidden name=cert_request value=""> <p>name: <input type=text name=name value=""> <p>password: <input type=passwor...
Simple Storage - Archive of obsolete content
note that these examples create a mystorage variable to emphasize the fact that jetpack.storage.simple is just a normal javascript object.
...jetpack.future.import("menu");jetpack.future.import("selection");jetpack.future.import("storage.simple");// create the persistent notes array if it doesn't already exist.jetpack.storage.simple.notes = jetpack.storage.simple.notes || [];var notes = jetpack.storage.simple.notes;// updates the jetpack menu with the current notes.
Simple Storage - Archive of obsolete content
note that these examples create a mystorage variable to emphasize the fact that jetpack.storage.simple is just a normal javascript object.
...jetpack.future.import("menu"); jetpack.future.import("selection"); jetpack.future.import("storage.simple"); // create the persistent notes array if it doesn't already exist.
Microsummary topics - Archive of obsolete content
warning: microsummary support was removed in gecko 6.0 (firefox 6.0 / thunderbird 6.0 / seamonkey 2.3) programmatically installing a microsummary generator to programmatically install a microsummary generator -- for example, in an extension that helps users create custom generators for their favorite sites -- obtain a reference to the nsimicrosummaryservice interface implemented by the nsimicrosummaryservice component, then call its installgenerator() method, passing it an xml document containing the generator.
... createinstance(components.interfaces.nsidomparser); var generatordoc = domparser.parsefromstring(generatortext, "text/xml"); var microsummaryservice = components.classes["@mozilla.org/microsummary/service;1"].
Overview of how downloads work - Archive of obsolete content
downloads via the helper app service this diagram is an uml sequence diagram, and was created using dia.
... get the .dia file here: mozilla_downloads.dia downloads via "save link target as" and friends this diagram is an uml sequence diagram, and was created using dia.
Plugin Architecture - Archive of obsolete content
sequence of events in content a content node for a plugin dom element gets created in bindtotree (usually) or another function, it calls loadobject loadobject either notices directly that it is dealing with a plugin, or it starts a network request and notices this in onstartrequest when it realizes that, it tries to create a frame, if anotify is true and no frame exists yet if a frame exists now, it is asked to instantiate the plugin that was the normal case.
...(the event is necessary because by the time hasnewframe is called, the frame isn't fully set up yet) in layout note: some of this should move to content an instance owner is created the window passed to the plugin is adjusted (the npwindow, http://devedge-temp.mozilla.org/libr...nt.html#999221) the plugin host is asked to instantiate the plugin this will call back to the instance owner / the object frame in order to create a widget to draw to (if the plugin is not windowless) nsplugininstanceowner::setwindow setwindow is called on the plugin ...
Styling - Archive of obsolete content
it is also possible to create platform-specific styles.
...to use platform-specific styles, create a folder in the bundle archive for each supported os and place a webapp.css file in the folder.
Hacking wiki - Archive of obsolete content
once you're done with the configuration script, copy the <tt>config/localsettings.php</tt> file it created to the parent directory and navigate to the location you installed mediawiki to.
...the title-override / breadcrumbs extensions need an additional table created.
RDF Datasource How-To - Archive of obsolete content
this document is a cookbook that describes how to create a native, client-side datasource that works with mozilla's rdf implementation.
...although this is more work, it is really the only way to create a "live" datasource that may be changed by some outside agent.
Table Layout Regression Tests - Archive of obsolete content
for appendcells1.html a file appendcells1.rgd will be created in the baseline or verify subdirectory.
... e:\moz_src\mozilla\layout\html\tests\block\base\baseline\width-percent_html.rgd writing regression data to e:\moz_src\mozilla\layout\html\tests\block\base\baseline\margin1_html.rgd writing regression data to e:\moz_src\mozilla\layout\html\tests\block\base\baseline\pre_html.rgd writing regression data to e:\moz_src\mozilla\layout\html\tests\block\base\baseline\pre1_html.rgd the second verify run creates first the frame dumps in the verify subdirectories (verify) and compares each frame dump with the corresponding reference frame dump.
TraceVis - Archive of obsolete content
these directions create an optimized build, because optimized builds are usually better for performance analysis.
...visualization python vis.py /tmp/tracevis.log /tmp/tracevis.png this creates a png format visualization of tracemonkey activities.
URIs and URLs - Archive of obsolete content
the protocol handler provides scheme specific information and methods to create new uris of the schemes it supports.
...normally, the only time escape encodings can safely be made is when the uri is being created from its component parts; each component may have its own set of characters that are reserved, so only the mechanism responsible for generating or interpreting that component can determine whether or not escaping a character will change its semantics.
Venkman Internals - Archive of obsolete content
scriptmanager in initdebugger() the previous loaded scripts are passed to an onscriptcreated() method which binds them to a scriptmanager.
...this method is set into jsdiscripthook.onscriptcreated venkman-views.js views are the panels shown within the venkman window.
Venkman Introduction - Archive of obsolete content
you can then access the debugger via a new, dynamically created menuitem in the tools menu of that browser, or else restart the browser with a special debugger option.
...the debugger is built on top of an application framework that allows you to drag and drop, resize, and toggle all the available views, and even to create new views or modules for the debugger if you choose—though this latter is an advanced topic and a subject for a future article.
Elements - Archive of obsolete content
for example, use the value 'xul:button' to create an element that is displayed like a button.
...its value can be any legal dom event name (including custom events created using the documentevent interface of the dom).
Mac stub installer - Archive of obsolete content
build the mac installer (debug or non-debug target) using miw.mcp grab a nightly build, say from <http://ftp.mozilla.org/pub/mozilla/n...taller.sea.bin> drop in the installer binary next to the "mozilla installer" in the "mozilla installer" folder created by unstuffing the opt build.
...to do this, in addition to the above steps to set up the mac installer to debug you will need to do the following: create a file named xpcom.xpi with the shared libraries in the structure described under the [xpcom] section in: <http://lxr.mozilla.org/seamonkey/sou...ackages-mac#33> note that if you are using the debug target of the installer binary all shared libraries are expected to have the name format <libname>debug.shlb now set a break point at xpi_init() in the mac installer code and step into xpistub and e...
patch - Archive of obsolete content
you create this object by passing a string representing the directory to the getfolder method.
...the set of differences is in gdiff format and is created by the nsdiff utility.
Methods - Archive of obsolete content
methods createkey adds a key.
... the winregvalue constructor creates a winregvalue object.
XPInstall API reference - Archive of obsolete content
or setpackagefolder installtrigger no properties methods compareversion enabled getversion install installchrome startsoftwareupdate installversion properties methods compareto init tostring file no properties methods copy dircreate dirgetparent dirremove dirrename diskspaceavailable execute exists isdirectory isfile macalias moddate moddatechanged move remove rename size windowsgetshortname windowsregisterserver windowsshortcut winprofile no properties methods ...
... getstring writestring winreg no properties methods createkey deletekey deletevalue enumkeys enumvaluenames getvalue getvaluenumber getvaluestring iskeywritable keyexists setrootkey setvalue setvaluenumber setvaluestring valueexists winregvalue constructor other information return codes see complete list examples trigger scripts and install scripts code samples file.macalias file.windowsshortcut install.adddirectory install.addfile installtrigger.installchrome installtrigger.startsoftwareupdate windows install ...
Getting File Information - Archive of obsolete content
var lastmod = new date(file.lastmodifiedtime); in this example, a date object is created using the modification time of a file.
... the default permissions for files when created through an output stream is 0644, which means that the file is readable and writable by the owner of the file and read only for others.
IO - Archive of obsolete content
ArchiveMozillaXULFileGuideIO
files and streams this section describes how to access and get information about files, read from files and create and write files.
...specifically, to create a directory, see creating directories and to retrieve a list of files or subdirectories within a directory, see iterating over the files in a directory.
Introduction to XUL - Archive of obsolete content
ui designers will be able to create ui descriptions which will work on multiple platforms.
...the resulting ui will be created using an xml content model.
appendItem - Archive of obsolete content
« xul reference home appenditem( label, value ) return type: element creates a new item and adds it to the end of the existing list of items.
...the function returns the newly created element.
appendNotification - Archive of obsolete content
« xul reference home appendnotification( label , value , image , priority , buttons, eventcallback ) return type: element create a new notification and display it.
... example: function testnotificationboxwithbuttons() { //create some common variables if they do not exist.
insertItem - Archive of obsolete content
some special ids may also be used to create special spacing items: separator: a separator, which is drawn as a vertical bar.
... the method returns the dom element for the created item.
Panels - Archive of obsolete content
the panel element the panel element is used to create panels.
... letting panels be dragged by grabbing the background requires gecko 7.0(firefox 7.0 / thunderbird 7.0 / seamonkey 2.4) starting in gecko 7.0 (firefox 7.0 / thunderbird 7.0 / seamonkey 2.4), you can use the backdrag attribute to create panels that the user can drag by clicking and dragging anywhere on their backgrounds.
Tooltips - Archive of obsolete content
this default tooltip is created automatically, so you don't normally need to use a tooltip element.
... the tooltip can be created using the tooltip element, the contents of which appear inside the tooltip.
Attribute Substitution - Archive of obsolete content
however, the textnode element is not copied into the generated content, but instead a dom text node is created with the value of the value attribute as its contents.
...this causes rules to create matches as the data loads.
Building Hierarchical Trees - Archive of obsolete content
each level of the tree is created using a successive iteration of the template build process.
...the tree builder creates rows lazily, so a closed container will not have any data generated inside in it until the row is opened.
RDF Query Syntax - Archive of obsolete content
the seed result will be created like this: (?start = http://www.xulplanet.com/rdf/a) the variable ?start is determined from the tag's 'uri' attribute.
...recall the data in the potential results set: (?start = http://www.xulplanet.com/rdf/a) this was the seed data created by the content statement.
Simple Example - Archive of obsolete content
a template which displays this information is very simple to create.
...this will result in the following: <member container="http://www.xulplanet.com/rdf/myphotos" child="?photo"/> as with processing a triple, the builder will now try to find as many values for the ?photo variable as possible and create potential results using them.
Using Multiple Queries to Generate More Results - Archive of obsolete content
to do this, we create one query to generate one set of results and a second query to generate another set of results.
... if a result from the second query wasn't also matched by the first query, it will have content created for it.
Using Recursive Templates - Archive of obsolete content
for the outermost iteration, a vbox is created with a child label.
...box id="row6" class="indent"><label value="ferdinand magellan"/></vbox> </vbox> <vbox id="row3" container="true" empty="false" class="indent"> <label value="female"/> <vbox id="row7" class="indent"><label value="cleopatra"/></vbox> <vbox id="row8" class="indent"><label value="laura secord"/></vbox> </vbox> </groupbox> note how similar content corresponding to the action body is created for both the groups as well as the people.
Adding Properties to XBL-defined Elements - Archive of obsolete content
with xbl, you can define your own properties for the elements you create.
...the example below creates a button which generates and stores a random number.
Creating a Window - Archive of obsolete content
if it does not exist, then it needs to be created and set to |true|.
...create a file called findfile.xul and put it in the content directory specified in the findfile.manifest file (we've created in the previous section).
Document Object Model - Archive of obsolete content
<button id="find-button" label="find" oncommand="dofind();"/> now, create another file called findfile.js in the same directory as findfile.xul.
...this causes an xhtml button to be created for this case.
Features of a Window - Archive of obsolete content
creating another window you can create a second window for your application in the same manner as you would create the first one.
... just create a second xul file with the window code in it.
Grids - Archive of obsolete content
ArchiveMozillaXULTutorialGrids
it creates an effect much like a grid of stack elements.
... flexibility of grids one advantage that grids have over a set of nested boxes is that you can create cells that are flexible both horizontally and vertically.
Groupboxes - Archive of obsolete content
you can create a caption for your groupbox by inserting a caption element as the first child.
...more complex captions you can also add child elements inside the caption element to create a more complex caption.
Install Scripts - Archive of obsolete content
you should create a install.rdf instead.
...you don't need to know much about it to create xul applications unless you are creating your own xpcom components.
More Button Features - Archive of obsolete content
for example, the following will create a button where two of the words are red: example 4 : source view <button> <description value="this is a"/> <description value="rather strange" style="color: red;"/> <description value="button"/> </button> any xul element may be placed inside the button.
...this also creates a button with a menu, but the appearance will be different.
RDF Datasources - Archive of obsolete content
you can also create rdf files that are hierarchical.
...the second rule applies to all other resources and creates a row in a popup menu.
The Chrome URL - Archive of obsolete content
when creating your own applications, you will want to create a file for your main window with the same name as the package, so it can be referred to using this shorter form.
...in the next section, we will look at how to create .manifest files and packages.
Tree Selection - Archive of obsolete content
getrangeat example var start = new object(); var end = new object(); var numranges = tree.view.selection.getrangecount(); for (var t = 0; t < numranges; t++){ tree.view.selection.getrangeat(t,start,end); for (var v = start.value; v <= end.value; v++){ alert("item " + v + " is selected."); } } we create two objects called 'start' and 'end'.
...tree.view.selection.clearrange(2,7); next, we'll find out how to create a custom view for a tree.
Trees and Templates - Archive of obsolete content
this means that elements will not be created for every row in the tree, making it more efficient.
...cols> <template> <rule> <treechildren> <treeitem uri="rdf:*"> <treerow> <treecell label="rdf:http://home.netscape.com/nc-rdf#name"/> <treecell label="rdf:http://home.netscape.com/web-rdf#lastmodifieddate"/> </treerow> </treeitem> </treechildren> </rule> </template> </tree> here, a tree is created with two columns, for the name and date of a file.
XBL Attribute Inheritance - Archive of obsolete content
however, with the features mentioned so far, the anonymous content is always created in the same way.
...for example, to create a labeled textbox (a textbox with a text description beside it) out of a label and a textbox element, the label will need to inherit its text from the value attribute and the textbox will also need to inherit its default value from the value attribute as well.
XUL Tutorial - Archive of obsolete content
this language was created for the mozilla application and is used to describe its user interface.
...ties adding methods adding event handlers xbl inheritance creating reusable content using css and xbl xbl example specialized window types features of a window creating dialogs open and save dialogs creating a wizard more wizards overlays cross package overlays installation creating an installer install scripts additional install features this xul tutorial was originally created by neil deakin.
Using the standard theme - Archive of obsolete content
you can either add multiple <tt>xml-stylesheet</tt> processing instructions to your xul file, or create an <tt>@import</tt> chain.
...for this to work, you need to create an approriate directory structure, with directory names corresponding to the names of the themes you want to extend, and of course, your adapted custom style sheets.
XUL Template Primer - Bindings - Archive of obsolete content
the <bindings> element is used to create additional,optional variable bindings, in addition to those that are specified in a rule's <conditions>.
...ame="jack"> <nc:address resource="#doghouse"/> </rdf:description> </rdf:li> <rdf:li> <rdf:description nc:name="lumpy"/> </rdf:li> </rdf:seq> </nc:friends> </rdf:description> <rdf:description id="home" nc:street="437 hoffman"/> <rdf:description id="doghouse" nc:street="435 hoffman"/> </rdf:rdf> the rdf model that this file creates can be represented with the following graph.
XUL controls - Archive of obsolete content
button reference related elements: menupopup menuitem <checkbox> a control that may be turned on and off, typically used to create options which may be enabled or disabled.
... listbox reference related elements: listcell listcols listcol listhead listheader listitem <menulist> a menulist (or combobox) is used to create a control with a drop down to select a value.
listcols - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] a container for the columns of a listbox, each of which are created with the listcol element.
... example <!-- creates a two column listbox --> <listbox> <listcols> <listcol flex="1"/> <listcol flex="1"/> </listcols> <listitem> <listcell label="buck"/> <listcell label="rogers"/> </listitem> <listitem> <listcell label="john"/> <listcell label="painter"/> </listitem> </listbox> attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, or...
menupopup - Archive of obsolete content
there are several ways in which a menupopup may be used: it may be placed inside a menu, menulist, toolbarbutton, or a button with the type attribute set to "menu" to create a popup that will open when the menu or button is pressed.
...unanchored popups may be created by supplying null as the anchor node.
notificationbox - Archive of obsolete content
the notification element is used for each notification, and will be created automatically for each item.
... lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata appendnotification( label , value , image , priority , buttons, eventcallback ) return type: element create a new notification and display it.
scrollbox - Archive of obsolete content
<vbox> <label value="01 four score and seven years ago "/> <label value="02 our fathers brought forth on "/> <label value="03 this continent, a new nation, "/> <label value="04 conceived in liberty, and "/> <label value="05 dedicated to the proposition "/> <label value="06 that all men are created equal."/> </vbox> the next bunch of labels is similar, but if the container doesn't give enough room for it, scroll bars will sprout out of nowhere and allow the user to scroll around the big content in the small view space.
... <vbox flex="1" style="overflow:auto"> <label value="01 four score and seven years ago "/> <label value="02 our fathers brought forth on "/> <label value="03 this continent, a new nation, "/> <label value="04 conceived in liberty, and "/> <label value="05 dedicated to the proposition "/> <label value="06 that all men are created equal."/> </vbox> the flex="1" above may or may not be needed, or even desired.
wizardpage - Archive of obsolete content
this can be used to create wizards that do not have a linear sequence.
...this can be used to create wizards that do not have a linear sequence.
Building XULRunner with Python - Archive of obsolete content
xpcom components can also be created in python.
... set cvsroot=:pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot having created amozilla project directory (e.g.c:\projects\mozilla or/c/projects/mozilla in msys) create the following .mozconfig file.
Creating XULRunner Apps with the Mozilla Build System - Archive of obsolete content
in some cases, however, you may want to use the mozilla build system to create your application.
...so for most xulrunner apps that use the mozilla build system, the top-level makefile will contain: dirs = components chrome app the installer/ subdirectory the installer/ makefile lets you create a setup program for distributing your application.
Custom app bundles for Mac OS X - Archive of obsolete content
a xul application for mac os x should follow something similar to this basic directory structure: example.app/ contents/ info.plist (application bundle properties are specified in this xml file.) pkginfo (this is a simple text file and is created along with the info.plist file) macos/ (the macos folder will contain your xulrunner executable) xulrunner (this is the xulrunner stub) resources/ (this is where you place your xul application code and support files) application.ini (xulrunner-related application settings) example.icns (this is the icon which will be used by you...
... examples these example files are taken from a port of webrunner which was created to illustrate one method of mac os x application packaging.
Deploying XULRunner - Archive of obsolete content
it may turn out to be easier to create a self contained portable application, as described here, and deploy it with a generic installer that would create shortcuts to scripts that launch your application in the unregistered bundled xulrunner.
... finally : you can use any paint or graphics utility to create your application's icon, which should be provided as a 512 by 512 pixel png file.
Dialogs in XULRunner - Archive of obsolete content
in an effort to make things easier for developers and more consistent for users, xul has a mechanism to automatically create and position the core dialog buttons ("ok," "cancel," and "help" for example).
...the xul filepickers are xpcom components and must be instantiated before using, like this: function dofileopen() { /* see: http://developer.mozilla.org/en/docs/xul_tutorial:open_and_save_dialogs */ var nsifilepicker = components.interfaces.nsifilepicker; var fp = components.classes["@mozilla.org/filepicker;1"].createinstance(nsifilepicker); fp.init(window, "open file", nsifilepicker.modeopen); fp.appendfilters(nsifilepicker.filtertext | nsifilepicker.filterall); var res = fp.show(); if (res == nsifilepicker.returnok) { var thefile = fp.file; alert(thefile.leafname); // --- do something with the file here --- } } xul does not currently support any other common dialogs.
XULRunner Hall of Fame - Archive of obsolete content
it's possible to create your own python web browser with hulahop, and much much more besides.
... xuljet a framework that helps to create platform independent desktop applications directly in javascript ...
Windows and menus in XULRunner - Archive of obsolete content
this time i want to add some of the things common to a desktop application user interface: windows and dialogs menus and toolbars os common dialogs controls or widgets windows each window or dialog should be created in its own xul file.
...the dtd is used to create entity references so strings for titles and labels are not stored directly in the xul file; this makes updating the text -- and localization of the application -- much easier.
ant script to assemble an extension - Archive of obsolete content
this ant script helps to package an extension <?xml version="1.0"?> this build file was written by régis décamps <decamps@users.sf.net> <project name="blogmark" default="createxpi"> <property name="version" value="1.3-rc1"/> <property name="description" value="new context-menu item to add the current page in your blogmarks"/> xpi file is created after "chrome/blogmark.jar" is created, which is then stuffed into "blogmark.xpi" <target name="createxpi" depends="createjar" description="assemble the final build blogmark.xpi"> <zip destfile="blogmark-${version}.xpi"> <zipfileset dir="." includes="chrome/blogmark.jar" /> <zipfile...
...set dir="." includes="install.rdf" /> </zip> </target> everything inside the chrome directory is zipped into chrome/blogmark.jar <target name="createjar" depends="templates" description="assemble the jar"> <jar destfile="chrome/blogmark.jar"> <fileset dir="chrome/"> <include name="**/*"/> <exclude name="**/*~"/> <exclude name="**/*.tpl.*"/> <exclude name="blogmark.jar"/> </fileset> </jar> </target> <target name="templates" description="generate files from templates."> <copy file="chrome/content/blogmark/contents.rdf.tpl.xml" ...
mozilla.dev.platform FAQ - Archive of obsolete content
0x00016b50 in xre_createappdata () a: when you <tt>--disable-libxul</tt>, the xpcom glue doesn't have information about how to load all the dependent libraries like <tt>libgfx.dylib</tt>.
...took an foo.app directory created with xulrunner-bin --install-app and tried to copy (using rsync -rl) the xul.framework directory into a frameworks directory in the .app bundle and then deleting the xul.framework directory from /library/frameworks, my running my app fails silently.
reftest opportunities files - Archive of obsolete content
for now, create a bug in the core product, testing component in the bugzilla, if you can point to a file in this list and can attach the html reference that can be used to compare the output.
...if you create a reftest for any of these bugs please attach the reftest to the bug and ask for review from the assignee (or anyone else that seems appropriate judging from comments in the bug).
2006-11-10 - Archive of obsolete content
harry is looking for help with create thread in javascript using nsithread.
... he wants to know how to create new threads using javascript for background download operations.
NPClass - Archive of obsolete content
called by npn_createobject() if non-null, otherwise the browser calls malloc().
... this function is expected to allocate and return enough storage to hold the npobject that is being created.
NPN_RequestRead - Archive of obsolete content
for multiple requests, the function creates a linked list of npbyterange structures, each of which represents a separate request.
...seekable streams are created by calling npp_newstream() with np_seek as the stype mode.
NPN_Write - Archive of obsolete content
example this example pushes a snippet of html over a newly created stream, then destroys the stream when it's done.
...npstream* stream; char* mydata = "<html><b>this is a message from my plug-in!</b></html>"; int32 mylength = strlen(mydata) + 1; /* create the stream.
NPObject - Archive of obsolete content
to aid with the reference counting and ownership management in general, the functions npn_createobject(), npn_retainobject(), npn_releaseobject(), and npn_releasevariantvalue() are provided as part of this api.
... functions npn_createobject() npn_retainobject() npn_releaseobject() npn_invoke() npn_invokedefault() npn_evaluate() npn_getproperty() npn_setproperty() npn_removeproperty() npn_hasproperty() npn_hasmethod() npn_setexception() see also npclass ...
NPP_Destroy - Archive of obsolete content
upon the user's return to the page, this information is passed to the new plug-in instance when it is created with npp_new.
... mac os if you want to restore state information if this plug-in is later recreated, use np_memalloc to create an npsaveddata structure.
NPStream - Archive of obsolete content
streams produced by the browser: the browser creates the npstream object and passes it to the plug-in initially as a parameter to npp_newstream.
...streams produced by the plug-in: the browser creates the npstream object and returns it as an output parameter when the plug-in calls npp_newstream.
Adobe Flash - Archive of obsolete content
example 1 also creates a constant flashversionosxscriptable that declares (arbitrarily) that macromedia will fix flash to be scriptable in mach-o browsers (on os x) by version 12.
... var myflash = document.getelementbyid("myflash").setvariable("myvar", sendtext); a more expanded code example that shows how example 2 was created is shown in this source listing.
XEmbed Extension for Mozilla Plugins - Archive of obsolete content
the general idea is that you use the xid that was passed into your npp_setwindow() call and create a gtkplug to host inside of that socket.
...just create a gtkplug that is the child of the xid passed in and it's just like using a standard gtk widget.
Getting Started - Archive of obsolete content
it is not mandatory to create rss files in this tutorial (you can just read on), but this would be a less effective way for you to learn.
... you'll retain the information more and absorb it better if you create the rss files yourself.
0.90 - Archive of obsolete content
ArchiveRSSVersion0.90
it was created by netscape to be a metadata format providing a summary of a website.
... when rss 0.90 was created, the rss initialization stood for rich site summary and not really simple syndication.
Digital Signatures - Archive of obsolete content
if they don't match, the data may have been tampered with since it was signed, or the signature may have been created with a private key that doesn't correspond to the public key presented by the signer.
... if the two hashes match, the recipient can be certain that the public key used to decrypt the digital signature corresponds to the private key used to create the digital signature.
SSL and TLS - Archive of obsolete content
using ecc elliptic curve cryptography (ecc) is a cryptographic system that uses elliptic curves to create keys for encrypting data.
... ecc creates cryptographically-stronger keys with shorter key lengths than rsa, which makes it faster and more efficient to implement.
Introduction - Archive of obsolete content
var a = 2; var b = <foo>{a}</foo>; creates an xml document that reads <foo>2</foo>.
...for example, var a = 2; var b = 'bar'; var c = <foo {b}={a}>"hi"</foo>; creates a slightly different xml document: <foo bar="2">"hi"</foo>.
Array comprehensions - Archive of obsolete content
the following comprehension takes an array of numbers and creates a new array of the double of each of those numbers.
...here is one that filters just the even numbers, then creates an array containing their doubles: var numbers = [1, 2, 3, 21, 22, 30]; var doubledevens = [for (i of numbers) if (i % 2 === 0) i * 2]; console.log(doubledevens); // logs 4,44,60 the square brackets of an array comprehension introduce an implicit block for scoping purposes.
@set - Archive of obsolete content
the @set statement creates variables used with conditional compilation statements.
...variables created using @set are generally used in conditional compilation statements, but can be used anywhere in javascript code.
New in JavaScript 1.2 - Archive of obsolete content
--> new features in javascript 1.2 new objects you can create objects using literal notation (inspired by dictionary literal syntax from python 1.x).
... arrays can now be created using literal notation (inspired by list literal syntax from python 1.x).
New in JavaScript 1.8.5 - Archive of obsolete content
new features in javascript 1.8.5 new functions function description object.create() creates a new object with the specified prototype object and properties.
... function.prototype.bind() creates a new function that, when called, itself calls this function in the context provided (with a given sequence of arguments).
New in JavaScript 1.8 - Archive of obsolete content
allowing you to simply create generators (which were introduced in javascript 1.7).
... typically you would have to create a custom function which would have a yield in it, but this addition allows you to use array comprehension-like syntax to create an identical generator statement.
JavaPackage - Archive of obsolete content
created by a reference to the package name used with the packages keyword: packages.javapackage javapackageis the name of the object's java package.
...the following code creates the javapackage red: var red = packages.redwood; see also javaarray, javaclass, javaobject, packages ...
Packages - Archive of obsolete content
created by the packages object is a top-level, predefined javascript object.
... examples example: javascript function to create a java dialog box the following javascript function creates a java dialog box: function createwindow() { var theowner = new packages.java.awt.frame(); var thewindow = new packages.java.awt.dialog(theowner); thewindow.setsize(350, 200); thewindow.settitle("hello, world"); thewindow.setvisible(true); } in the previous example, the function instantiates thewindow as a new packages...
Standards-Compliant Authoring Tools - Archive of obsolete content
if you're using older versions of tools that rely on old browser bugs or generate browser-specific code, it may be time to upgrade: nvu is a standalone editor created from the remains of mozilla composer.
...some versions of microsoft word create invalid html code that only works with internet explorer.
Choosing Standards Compliance Over Proprietary Practices - Archive of obsolete content
when this happens, a development standard is created and is expected to be followed.
...this also creates issues in regard to authoring tools for these various applications.
Mozilla's DOCTYPE sniffing - Archive of obsolete content
almost standards mode was created after 1.0 and 1.1alpha, but before 1.0.1 and 1.1beta.
... before almost standards mode was created these doctypes triggered full standards mode.
Popup Window Controls - Archive of obsolete content
replacements for popup windows if your popup was created during the time the web page was loading, you may consider using document.write() to emit appropriate html which will contain the same information as the popup window.
... you can also use either the advanced features in the document object model (dom) or innerhtml to create the appropriate html.
The Business Benefits of Web Standards - Archive of obsolete content
dynamic effects such as those created by javascript are not taken into account, and text rendered with graphics cannot be read and parsed either.
... coding with standards (particularly css for positioning, and strict html) makes accessibility an easier goal to achieve, as standards have been created with accessibility in mind.
Using the Right Markup to Invoke Plugins - Archive of obsolete content
for example, on browsers that support activex, such as ie, create an object element with a classid attribute, and on browsers that support the netscape plugin architecture, use a mime type.
... here is an example of some javascript which does this: if (window.activexobject) { // browser supports activex // create object element with // download url for ie ocx document.write('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"'); document.write(' codebase="http://download.macromedia.com'); document.write('/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0"'); document.write(' width="366" height="142" id="myflash">'); document.write(' <param name="movie" value="javascript-to-flash.swf" />'); document.write(' <param name="quality" value="high" />'); document.write(' <param name="swliveconnect" value="true" />'); document.write('<\/object>'); } else { // browser supports netscape plugin api document.write('<object id="myflash" data="javascript-to-flash.swf"'); document.
Obsolete: XPCOM-based scripting for NPAPI plugins - Archive of obsolete content
for the purpose of this example to keep things simple // we just assign it to instance->pdata after we create it.
... nsitestplugin *scriptablepeer = (nsitestplugin *)instance->pdata; // see if this is the first time and we haven't created it yet if (!scriptablepeer) { nsitestplugin *scriptablepeer = new nsscriptablepeer(); if (scriptablepeer) ns_addref(scriptablepeer); // addref for ourself, // don't forget to release on // shutdown to trigger its destruction } // add reference for the caller requesting the object ns_addref(scriptablepeer); *(nsisupports **)value = scriptablepeer; } else if (variable == nppvpluginscriptableiid) { nsiid* ptr = (nsiid *)npn_memalloc(sizeof(nsiid)); *ptr = scriptableiid; ...
XUL Booster - Archive of obsolete content
create an extension you'll need an extension id; see generating guids.
...learn more at creating_a_mozilla_extension:finding_the_file_to_modify to create an xul:overlay, create a xul fragment with a top level node that has an id matching an existing element, ex.
XUL Parser in Python - Archive of obsolete content
if you want to look for certain widgets within the xul files, you can get the filename from the calling method p.feed(data) and create a condition that only gets the elements specified in sys.argv[1].
...ribute in sys.argv[1]: for attr in a.keys(): if strip(attr) == sys.argv[1]: el_list[name][strip(attr)] = strip(a[attr]) and writing thevalues to the html results file instead of thekeys: for item in elements: w.write('<tr><td class="head">' + item + '</td></tr>\n') for a in el_list[item].values(): w.write('<tr><td class="at">' + a + '</td>') with these modifications, the script creates an output more like a periodic table of xul elements.
Archive of obsolete content
try to create subtrees for categories of material.
...we'll build upon the stock watcher extension created in earlier articles in this series, updating it so it can also be used in thunderbird and sunbird (previous versions worked only in firefox).
Anatomy of a video game - Game development
the first statement creates a function as a global variable called main().
...for the first issue, if you want the main loop to just run and you do not need easy (direct) access to it, you could create it as an immediately-invoked function expression (iife).
Publishing games - Game development
game distribution so you've followed a tutorial or two and created an html5 game — that's great!
... game distribution provides all you need to know about the ways you can distribute your newly created game into the wild — including hosting it yourself online, submitting it to open marketplaces, and submitting it to closed ones like google play or the ios app store.
Explaining basic 3D theory - Game development
the camera has three parameters — location, direction, and orientation — which have to be defined for the newly created scene.
...if you want to move on to practice and see some demos in action, follow up with the tutorials below: building up a basic demo with three.js building up a basic demo with babylon.js building up a basic demo with playcanvas building up a basic demo with a-frame go ahead and create some cool cutting-edge 3d experiments yourself!
Building up a basic demo with PlayCanvas - Game development
playcanvas is a popular 3d webgl game engine, originally created by will eastcott and dave evans.
... engine vs editor the engine itself can be used as a standard library by including its javascript file directly in your html, so you can start coding right away; in addition the playcanvas toolset comes with an online editor that you can use to drag and drop components onto the scene — a great way to create games and other apps requiring scenes if you're more of a designer than a coder.
Desktop mouse and keyboard controls - Game development
in phaser the buttons you create will take any type of input, whether it's a touch on mobile or a click on desktop.
... controlling the game we can support keyboard input in games built with phaser by enabling the basic cursor keys in the create() function using the createcursorkeys() function: this.cursors = this.input.keyboard.createcursorkeys(); this creates four directional arrow keys for us: this.cursors.left; this.cursors.right; this.cursors.up; this.cursors.down; you can also define the keys on your own and offer an alternative, w a s d control mechanism for example: this.keyleft = this.input.keyboard.addkey(phaser.keycode.a)...
Unconventional controls - Game development
captain rogers had the keyboard controls implemented already: this.cursors = this.input.keyboard.createcursorkeys(); //...
... this can be accomplished using a small library created by daniel rapp — it can be as simple as calculating the difference between two frequencies: doppler.init(function(bandwidth) { var diff = bandwidth.left - bandwidth.right; }); the diff would be the difference between the initial position of the hand and the final one.
Implementing controls using the Gamepad API - Game development
it features a case study game — hungry fridge, created by enclave games.
... demo the full version of the hungry fridge game was built first, and then to showcase the gamepad api in action and show the javascript source code, a simple demo was created.
Game over - Game development
10); with: var interval = setinterval(draw, 10); then replace the second if statement with the following: if(y + dy < ballradius) { dy = -dy; } else if(y + dy > canvas.height-ballradius) { alert("game over"); document.location.reload(); clearinterval(interval); // needed for chrome to end game } letting the paddle hit the ball the last thing to do in this lesson is to create some kind of collision detection between the ball and the paddle, so it can bounce off it and get back into the play area.
...let's move on to the sixth chapter — build the brick field — and create some bricks for the ball to destroy.
Buttons - Game development
add the following lines to the bottom of your create() function: startbutton = game.add.button(game.world.width*0.5, game.world.height*0.5, 'button', startgame, this, 1, 0, 2); startbutton.anchor.set(0.5); the button() method's parameters are as follows: the button's x and y coordinates the name of the graphic asset to be displayed for the button a callback function that will be executed when the button is pressed a reference to this to sp...
... finally for this section, go back into your create() function, find the ball.body.velocity.set(150, -150); line, and remove it.
Extra lives - Game development
add the following lines below the existing scoretext definition inside your create() function: livestext = game.add.text(game.world.width-5, 5, 'lives: '+lives, { font: '18px arial', fill: '#0095dd' }); livestext.anchor.set(1,0); lifelosttext = game.add.text(game.world.width*0.5, game.world.height*0.5, 'life lost, click to continue', { font: '18px arial', fill: '#0095dd' }); lifelosttext.anchor.set(0.5); lifelosttext.visible = false; the livestext and lifelosttext objects lo...
...to make it easier for us to maintain in the future we can create a separate variable that will hold our styling, let's call it textstyle and place it before the text definitions: textstyle = { font: '18px arial', fill: '#0095dd' }; we can now use this variable when stlying our text labels — update your code so that the multiple instances of the text styling are replaced with the variable: scoretext = game.add.text(5, 5, 'points: 0', textstyle); livestext...
Load the assets and print them on screen - Game development
to load the asset, we will use the game object created by phaser, executing its load.image() method.
... now, to show it on the screen we will use another phaser method called add.sprite(); add the following new code line inside the create() function as shown: function create() { ball = game.add.sprite(50, 50, 'ball'); } this will add the ball to the game and render it on the screen.
Tutorials - Game development
2d maze game with device orientation this tutorial shows how to create a 2d maze game using html5, incorporating fundamentals such as collision detection and sprite placement on a <canvas>.
... 2d platform game with phaser this tutorial series shows how to create a simple platform game using phaser, covering fundamentals such as sprites, collisions, physics, collectables, and more.
Computer Programming - MDN Web Docs Glossary: Definitions of Web-related terms
using an appropriate language, you can program/create all sorts of software.
... for example, a program that helps scientists with complex calculations, a database that stores huge amounts of data, a web site that allows people to download music, or animation software that allows people to create animated movies.
Global object - MDN Web Docs Glossary: Definitions of Web-related terms
in a web browser, when scripts create global variables, they're created as members of the global object.
...we created a global function called greeting, then invoked it using the window object.
Grid Cell - MDN Web Docs Glossary: Definitions of Web-related terms
additional row or column tracks will be created to create enough cells to hold all items.
... in the example we have created a three column track grid.
Grid Tracks - MDN Web Docs Glossary: Definitions of Web-related terms
tracks are also created in the implicit grid by positioning a grid item outside of the tracks created in the explicit grid.
...#fff4e6; } .wrapper > div { border: 2px solid #ffa94d; border-radius: 5px; background-color: #ffd8a8; padding: 1em; color: #d9480f; } .wrapper { display: grid; grid-template-columns: 200px 1fr 3fr; } <div class="wrapper"> <div>one</div> <div>two</div> <div>three</div> <div>four</div> <div>five</div> </div> track sizing in the implicit grid tracks created in the implicit grid are auto-sized by default, however you can define a size for these tracks using the grid-auto-rows and grid-auto-columns properties.
IIFE - MDN Web Docs Glossary: Definitions of Web-related terms
the second part creates the immediately invoked function expression () through which the javascript engine will directly interpret the function.
... var result = (function () { var name = "barry"; return name; })(); // immediately creates the output: result; // "barry" ...
Symbol - MDN Web Docs Glossary: Definitions of Web-related terms
in a javascript runtime environment, a symbol value is created by invoking the function symbol, which dynamically produces an anonymous, unique value.
...// even if we create many symbols with the same description, // they are different values.
Application Context - MDN Web Docs Glossary: Definitions of Web-related terms
if an application context is created as a result of the user agent being asked to navigate to a deep link, the user agent must immediately navigate to the deep link with replacement enabled.
... otherwise, when the application context is created, the user agent must immediately navigate to the start url with replacement enabled.
Test your skills: WAI-ARIA - Learn web development
try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
Accessibility - Learn web development
note: if you are working on a computer/tablet/other devices where you don't have the ability to create your own files, you can try out most of the code examples in an online coding program such as jsbin or glitch.
... accessible multimedia another category of content that can create accessibility problems is multimedia — video, audio, and image content need to be given proper textual alternatives, so they can be understood by assistive technologies and their users.
A cool-looking box - Learn web development
in this assessment, you'll get some more practice in creating cool-looking boxes by trying to create an eye-catching box.
... project brief your task is to create a cool, fancy box and explore the fun we can have with css.
Advanced styling effects - Learn web development
gba(0,0,0,0.25)); } .multiple { box-shadow: 1px 1px 1px black, 2px 2px 1px black, 3px 3px 1px red, 4px 4px 1px red, 5px 5px 1px black, 6px 6px 1px black; } now we get this result: we've done something fun here by creating a raised box with multiple coloured layers, but you could use it in any way you want, for example to create a more realistic look with shadows based on multiple light sources.
... the circle() function is just one of a few basic shapes that are defined, however there are a number of different ways to create shapes.
Debugging CSS - Learn web development
the best thing to do at this point is to create something known as a reduced test case.
... to create a reduced test case: if your markup is dynamically generated — for example via a cms — make a static version of the output that shows the problem.
Fundamental CSS comprehension - Learn web development
the final step before you move on is to attempt the assessment for the module — this involves a number of related exercises that must be completed in order to create the final design — a business card/gamer card/social media profile.
... basic setup: first of all, create a new file in the same directory as your html and image files.
Images, media, and form elements - Learn web development
you could create a form input with no borders and background that is almost indistinguishable from the content around it, but this would make it very hard to recognise and fill in.
...this includes all the items mentioned in the last three sections: button, input, select, textarea { font-family: inherit; font-size: 100%; box-sizing: border-box; padding: 0; margin: 0; } textarea { overflow: auto; } note: normalizing stylesheets are used by many developers to create a set of baseline styles to use on all projects.
Test your skills: Overflow - Learn web development
try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the example as displayed in the image: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor.
Type, class, and ID selectors - Learn web development
in the live example below we have created a class called .highlight, and have applied it to several places in my document.
... targeting classes on particular elements you can create a selector that will target specific elements with the class applied.
Styling tables - Learn web development
next, create a new file called style.css and save it in the same directory as your other files.
... use table-layout: fixed to create a more predictable table layout that allows you to easily set column widths by setting width on their headings (<th>).
Test your skills: backgrounds and borders - Learn web development
try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... the finished example should look like the image below: try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
Test your skills: position - Learn web development
try updating the live code below to recreate the finished example: as an extra challenge, can you change the target to display underneath the text?
... try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor.
Practical positioning examples - Learn web development
you might be thinking "why not just create the separate tabs as separate webpages, and just have the tabs clicking through to the separate pages to create the effect?" this code would be simpler, yes, but then each separate "page" view would actually be a newly-loaded webpage, which would make it harder to save information across views, and integrate this feature into a larger ui design.
... so there you have it — a rather clever javascript-free way to create a toggling button effect.
Test your skills: Media Queries and Responsive Design - Learn web development
your task is to create a desktop version of this layout which displays when there is enough screen width to accomodate it.
... there are a number of ways that you could create the desktop layout, enjoy experimenting.
CSS layout - Learn web development
note: if you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as jsbin or glitch.
...media queries are a key part of responsive web design, as they allow you to create different layouts depending on the size of the viewport, but they can also be used to detect other things about the environment your site is running on, for example whether the user is using a touchscreen rather than a mouse.
What is CSS? - Learn web development
overview: first steps next css (cascading style sheets) allows you to create great-looking web pages, but how does it work under the hood?
...it can be used to create layout — for example turning a single column of text into a layout with a main content area and a sidebar for related information.
Web fonts - Learn web development
fonts are created by font foundries and are stored in different file formats.
...because different fonts are created at different sizes, you may have to adjust the size, spacing, etc., to sort out the look and feel.
How do I start to design my website? - Learn web development
(should i implement these features, use these services, create these designs?) so now that you have a prioritized list of goals, let's move on to the next question.
...mail?) define how people will find those contact channels from your website sell goodies create the goodies store the goodies find a way to handle shipping find a way to handle payment make a mechanism on your site for people to place orders teach music through videos record video lessons prepare video files viewable online (again, could you do this with existing web services?) give people access to your videos on some part of your websit...
What are browser developer tools? - Learn web development
this will give you a window like the following: to see what happens, try entering the following snippets of code into the console one by one (and then pressing enter): alert('hello!'); document.queryselector('html').style.backgroundcolor = 'purple'; const mywordmark = document.createelement('img'); mywordmark.setattribute('src','https://blog.mozilla.org/press/wp-content/themes/onemozilla/img/mozilla-wordmark.png'); document.queryselector('h1').appendchild(mywordmark); now try entering the following incorrect versions of the code and see what you get.
... alert('hello!); document.cheeseselector('html').style.backgroundcolor = 'purple'; const mywordmark = document.createelement('img'); mybanana.setattribute('src','https://blog.mozilla.org/press/wp-content/themes/onemozilla/img/mozilla-wordmark.png'); document.queryselector('h1').appendchild(mywordmark); you'll start to see the kind of errors that the browser returns.
What is a Domain Name? - Learn web development
mozilla.org), you can create "subdomains" with different content located at each, like developer.mozilla.org, iot.mozilla.org, or wiki.developer.mozilla.org.
... whenever your registrar creates or updates any information for a given domain, the information must be refreshed in every dns database.
What is a web server? - Learn web development
unless you want to learn web server programming (which is an exciting area in itself!), you don't need to create your own application server.
... next steps now that you are familiar with web servers, you could: read up on how much it costs to do something on the web learn more about various software you need to create a website move on to something practical like how to upload files on a web server.
Test your skills: Advanced styling - Learn web development
try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
Publishing your website - Learn web development
next, you need to create a repository to store files.
...then click create repository.
Use JavaScript within a webpage - Learn web development
prerequisites: you need to be familiar with how to create a basic html document.
...you can create amazing webpages without javascript, but javascript opens up a whole new level of possibilities.
Debugging HTML - Learn web development
note: html is parsed permissively because when the web was first created, it was decided that allowing people to get their content published was more important than making sure the syntax was absolutely correct.
... the best strategy is to start by running your html page through the markup validation service — created and maintained by the w3c, the organization that looks after the specifications that define html, css, and other web technologies.
Test your skills: Advanced HTML text - Learn web development
try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
HTML table advanced features and accessibility - Learn web development
the id and headers attributes an alternative to using the scope attribute is to use id and headers attributes to create associations between headers and cells.
... </tbody> note: this method creates very precise associations between headers and data cells but it uses a lot more markup and does not leave any room for errors.
Structuring the web with HTML - Learn web development
you should have a basic work environment set up as detailed in installing basic software, and understand how to create and manage files, as detailed in dealing with files — both are parts of our getting started with the web complete beginner's module.
... introduction to html this module sets the stage, getting you used to important concepts and syntax, looking at applying html to text, how to create hyperlinks, and how to use html to structure a webpage.
Introduction to events - Learn web development
each available event has an event handler, which is a block of code (usually a javascript function that you as a programmer create) that runs when the event fires.
...in the following example (see useful-eventtarget.html for the full source code; also see it running live here), we create 16 <div> elements using javascript.
JavaScript First Steps - Learn web development
note: if you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as jsbin or glitch.
...here we look at why this is useful, then explore how to create an array, retrieve, add, and remove items stored in an array, and more besides.
Adding features to our bouncing balls demo - Learn web development
first of all, create a new evil circle object instance (specifying the necessary parameters), then call its setcontrols() method.
... in your css file, add the following rule at the bottom: p { position: absolute; margin: 0; top: 35px; right: 5px; color: #aaa; } in your javascript, make the following updates: create a variable that stores a reference to the paragraph.
JavaScript — Dynamic client-side scripting - Learn web development
you can even create your own objects to encapsulate related functions and variables into efficient packages.
...here we teach object theory and syntax in detail, look at how to create your own objects, and explain what json data is and how to work with it.
CSS performance optimization - Learn web development
browsers follow a specific rendering path: paint only occurs after layout, which occurs after the render tree is created, which in turn requires both the dom and the cssom trees.
...to create a non-blocking css link, move the not-immediately used styles, such as print styles, into separate file, add a <link> to the html mark up, and add a media query, in this case stating it's a print stylesheet.
Multimedia: Images - Learn web development
other formats improve on jpeg's capabilities in regards to compression, but are not available on every browser: webp — created by google and nowadays supported by all major browsers except safari.
... jpeg-xr — created by microsoft and only available in internet explorer and edgehtml based edge.
Web performance - Learn web development
to build websites and applications people want to use, which attract and retain users, you need to create a good user experience.
...this is known as web performance, and in this module you'll focus on the fundamentals of how to create performant websites.
Server-side website programming first steps - Learn web development
note: this topic deals with server-side frameworks, and how to use them to create websites.
...we do hope that at this point you have a good understanding of what sorts of functionality you can deliver using server-side programming, and that you have made a decision about what server-side web framework you will use to create your first website.
Ember Interactivity: Footer functionality, conditional rendering - Learn web development
enter the following terminal command to do so: ember generate component-class footer next, go and find the newly-created todomvc/app/components/footer.js file and update it to the following: import component from '@glimmer/component'; import { inject as service } from '@ember/service'; export default class footercomponent extends component { @service('todo-data') todos; } now we need to go back to our todo-data.js file and add some functionality that will allow us to return the number of incomplete tod...
... creating a todo class run the following command in your terminal: ember generate component-class todo now go to the newly-created todomvc/app/components/todo.js file and update the contents to look like so, to give the todo component access to the service: import component from '@glimmer/component'; import { inject as service } from '@ember/service'; export default class todocomponent extends component { @service('todo-data') todos; } next, go back again to our todo-data.js service file and add the following ac...
Componentizing our React app - Learn web development
make a <todo /> before we can make a component, we should create a new file for it.
... </label> </h2> <input type="text" id="new-todo-input" classname="input input__lg" name="text" autocomplete="off" /> <button type="submit" classname="btn btn__primary btn__lg"> add </button> </form> ); } export default form; the <filterbutton /> do the same things you did to create form.js inside filterbutton.js, but call the component filterbutton() and copy the html for the first button inside the <div> element with the class of filters from app.js into the return statement.
Vue conditional rendering: editing existing todos - Learn web development
in your components directory, create a new file called todoitemeditform.vue.
...we create a form with an <input> field for editing the name of our to-do.
Styling Vue components with CSS - Learn web development
to start with, create a file called reset.css in the src/assets directory.
... to use the scoped modifier, create a <style> element inside todoitem.vue, at the bottom of the file, and give it a scoped attribute: <style scoped> </style> next, copy the following css into the newly created <style> element: .custom-checkbox > .checkbox-label { font-family: arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; font-weight: 400; font-size: 16px; font-size: 1rem;...
Handling common HTML and CSS problems - Learn web development
the use case we mentioned earlier (making modern semantic elements styleable in old versions of ie) can be achieved easily using conditional comments, for example you could put something like this in your ie stylesheet: aside, main, article, section, nav, figure, figcaption { display: block; } it isn't that simple, however — you also need to create a copy of each element you want to style in the dom via javascript, for them to be styleable; this is a strange quirk, and we won't bore you with the details here.
... for example: const asideelem = document.createelement('aside'); ...
Software accessibility: Where are we today?
in answer to this problem, many small accessibility hardware and software vendors created products and software which helped people who could not perform one of the four basic tasks to use common computer applications.
... follow the accessible toolkit checklist whenever using xbl to create a new widget.
Index
679 promoting your extension or theme add-ons, extensions, promotion, themes, webextensions, distribution so you’ve written a great extension, but only a few people have found and installed it from addons.mozilla.org—despite your efforts to create an appealing listing.
...learn how to create and share themes!
Themes
learn how to create and share themes!
... browser themes browser theme concepts get an introduction to creating themes for the latest versions of firefox using the amo theme generator use the theme generator to create and submit a new theme to amo lightweight themes lightweight themes have been deprecated and are no longer accepted by amo.
Chrome registration
resource aliases can be created using the resource instruction: resource aliasname uri/to/files/ [flags] this will create a mapping for resource://<aliasname>/ uris to the path given.
...to update your add-on to work without this flag: if your add-on depends upon xbl bindings attached to content objects (that is, it needs to be able to call functions or get and set properties created by the xbl binding), you'll need to use the object's wrappedjsobject property to obtain a wrapped object.
Capturing a minidump
minidumps are files created by various windows tools which record the complete state of a program as it's running, or as it was at the moment of a crash.
... small minidumps are created by the breakpad crash reporting tool, but sometimes that's not sufficient to diagnose a problem.
Debugging Frame Reflow
create a text file (for instance reflow_rules.txt).
... log file analysis the log file for a simple table like <!doctype html public "-//w3c//dtd html 4.01 transitional//en"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1"> </head> <body> <table width="100"> <tbody> <tr> <td>foo</td> </tr> </tbody> </table> </body> </html> will create the following log: vp 00b97c30 r=0 a=9180,4470 c=9180,4470 cnt=856 scroll 00b97ee0 r=0 a=9180,4470 c=9180,4470 cnt=857 scroll 00b97ee0 r=0 a=9180,4470 c=9180,4470 cnt=858 canvas 00b97c6c r=0 a=9180,uc c=9180,4470 cnt=859 area 02d7afe4 r=0 a=9180,uc c=9180,uc cnt=860 text 02d7b150 r=0 a=9180,uc c=uc,uc cnt=861 text 02d7b150 d=0,0 block 02d7b210 r=0 a=9180,uc c=8940,uc cnt=862 ...
Simple SeaMonkey build
to avoid that, create a directory without spaces in its path (e.g.
... on windows, the above commands will create the comm-central directory in %userprofile% which may be some subfolder of c:\documents and settings\ on systems upgraded from xp or below.
Simple Thunderbird build
build configuration to build thunderbird, you need to add a file named mozconfig to the root directory of the mozilla-central checkout that contains the following line: ac_add_options --enable-application=comm/mail you can create a file with this line by doing this in the source/ directory: echo 'ac_add_options --enable-application=comm/mail' > mozconfig if you omit this line, the build system will build firefox instead.
...for example, to create a debug build instead of a release build, that file would also contain the line: ac_add_options --enable-debug each of these ac_add_options entries needs to be on its own line.
SVG Guidelines
this flexibility depends on doing computations for svg images at the time they're displayed, rather than at the time the author creates them.
...metadata can mean many things, including: the typical "created with editor" comments non-standard editor specific tags and attributes (sketch:foo, illustrator:foo, sopodi:foo, …) the xml namespace definition that comes with the latter (xmlns:sketch, xmlns:sopodi, …) other metadata in addition to non-standard editor metadata, standard compliant metadata also exists.
Working with Mozilla source code
interface development guide guidelines and documentation for how to create and update xpcom interfaces.
... creating a patch once you've made a change to the mozilla code, the next step (after making sure it works) is to create a patch and submit it for review.
mach
it's a python script that creates an instance of the mach core, registers commands with it, then tells the mach core to execute.
...implementing new commands is as simple as writing a few lines of python and registering the created file with mach.
Security best practices for Firefox front-end engineers
existing security controls sanitizing all strings that enter the dom through apis such as innerhtml when running system-privileged chrome code, we sanitize all html fragments that are created for chrome-privileged documents.
... appendix list of disallowed dom apis innerhtml outerhtml insertadjacenthtml() createcontextualfragment() document.write() document.writeln() please take a look at the repository for an updated list ...
Firefox UI considerations for web developers
this list is created by a mozilla service called tippy top.
... usa today the only icon provided by usa today is its classic favicon: <link rel="shortcut icon" href="https://www.gannett-cdn.com/sites/usatoday/images/favicon.png"> since no rich icon is available, firefox creates a screenshot of the home page rendered 560 pixels wide.
Hacking with Bonsai
hacking mozilla with bonsai bonsai was originally created to solve the problem of tree instability.
...bonsai was created to solve these problems.
How to get a stacktrace for a bug report
alternative ways to get a stacktrace if the mozilla crash reporter doesn't come up or isn't available you will need to obtain a stacktrace manually: windows see the article create a stacktrace with windbg for information on how to do this.
... if breakpad successfully sends the crash report to the reporting server then, by default, the files added to the 'pending' subdirectory for the crash are removed, and a .txt file is placed in the 'submitted' directory containing the crash id created by the reporting server.
Creating a New Protocol
create the protocol file the protocol file should live in the same directory as the code which will implement it.
...you should know what protocol will manage the new protocol and what lifetime issues that creates.
Addon
instances can be created using the many getaddon methods on the addonmanager object.
...if the directory does not already exist, it will be created.
Download
a new download object can be created using the downloads.createdownload() function.
... note: if you need to start a new download from the same source, rather than restarting a failed or canceled one, you should create a separate download object with the same source as the current one.
FxAccountsOAuthClient.jsm
constructor fxaccountsoauthclient() creates and returns a new fxaccountsoauthclient object.
...default: /authorization return value a newly created fxaccountsoauthclient object implementing the methods described in this article.
FxAccountsProfileClient.jsm
constructor fxaccountsprofileclient() creates and returns a new fxaccountsprofileclient object.
... return value a newly created fxaccountsprofileclient object implementing the methods described in this article.
ISO8601DateUtils.jsm
using the iso 8601 date utilities to convert a date string into a date object, simply use: dateobj = iso8601dateutils.parse(datestring); to convert a date object into a date string: datestring = iso8601dateutils.create(dateobj); method overview string create(adate); date parse(adatestring); methods create creates an iso 8601 format date string, e.g.
...string create( adate ); parameters adate a javascript date object to translate into an iso 8601 format string.
PerfMeasurement.jsm
constructor creates a new perfmeasurement object, configured to record the specified event types.
...start() starts measuring the performance indicators that were specified when the perfmeasurement object was created.
Deferred
ise; would be return new promise(function(resolve, reject) { dosomething(function cb(good) { if (good) resolve(); else reject(); }); }); method overview void resolve([optional] avalue); void reject([optional] areason); properties attribute type description promise read only promise a newly created promise, initially in the pending state.
... */ this.reject = null; /* a newly created promise object.
Promise
promises may also be created using the new promise() constructor.
... method overview promise then([optional] function onfulfill, [optional] function onreject); promise catch([optional] function onreject); constructor creates a new promise, initially in the pending state, and provides references to the resolving functions that can be used to change its state.
PromiseWorker.jsm
promiseworker.jsm path: resource://gre/modules/promiseworker.jsm a javascript code module used by the main thread to create a worker thread and communicate with it.
... promiseworker.js path: resource://gre/modules/workers/promiseworker.js a javascript file used by the worker thread, which is created by promiseworker.jsm in main thread, to communicate with the main thread.
SourceMap.jsm
new sourcemapgenerator(startofsourcemap) to create a new one, you must pass an object with the following properties: file: the filename of the generated source that this source map is associated with.
... sourcemapgenerator.prototype.addmapping(mapping) add a single mapping from original source line and column to the generated source's line and column for this source map being created.
source-editor.jsm
initialtext string the default initial text to be in the editor when it's created.
... placeholdertext string the default initial text to be in the editor when it's created; by default, an empty string.
Localization and Plurals
for example, your extension localized for english with plural rule #1, which expects 2 plural forms, is installed on a localized version of firefox with plural rule #4, which expects 3 forms: /** * create a pair of plural form functions for the given plural rule number.
... * * @param arulenum * the plural rule number to create functions * @return a pair: [function that gets the right plural form, * function that returns the number of plural forms] */ [string pluralform get(int anum, string awords), int numforms numforms()] makegetter(int arulenum) here is an example usage of makegetter: components.utils.import("resource://gre/modules/pluralform.jsm"); // let's get irish (plural rule #11) let [get, numforms] = pluralform.makegetter(11); // make up some values to use with "get" let dummytext = "form 1;form 2;form 3;form 4;form 5"; let dummynum = 10; // in the case of irish, the value 10 uses plural form #4, so "form 4" is printed print(get(dummynum, dummytext)); in this example, the irish plural rule was hardcoded, but this could...
Localizing extension descriptions
if you do not currently have them, create localized properties files.
... add the following line to each of your localization properties files (where extension_id matches your extension id (<em:id> from install.rdf) and localized_description is the description of your extension that you want to appear in the given language): extensions.extension_id.description=localized_description if you do not currently have one, create a default preferences file.
Initial setup
for now, just be aware that should you choose to use them, you may need to create a personal account.
... perl perl is a programming language that will help you create mozilla application builds and language packs.
Translation phase
mozilla engagement campaigns individual campaigns created by mozilla to attract new contributors.
...they both have created comprehensive programs and l10n tools for localizing any and all third-party add-ons for mozilla applications.
Localization formats
in the case of download day, someone created entity-like identifiers in the msgid, which we have shown above with the "certificate_intro" key.
... then, an en-us repository was created holding the translations to all the entity-like values of msgid.
Web Localizability
the documentation is divided into 4 parts: how to create localizable content.
...how to create localizable web applications.
Mozilla Development Strategies
if you're working on something massive, start a branch if you are working on something big, and you want to be able to check in incrementally without getting reviews, create a branch.
... here's how to create a branch: from your linux or mac os x box: # start from your trunk tree on your local disk cd mozilla find .
DMD
/../../../../memory/replace/dmd/dmd.cpp:1286) #02: malloc (/home/njn/moz/mi5/go64dmd/memory/build/../../../memory/build/replace_malloc.c:153) #03: moz_xmalloc (/home/njn/moz/mi5/memory/mozalloc/mozalloc.cpp:84) #04: nscyclecollectingautorefcnt::incr(void*, nscyclecollectionparticipant*) (/home/njn/moz/mi5/go64dmd/dom/xul/../../dist/include/nsisupportsimpl.h:250) #05: nsxulelement::create(nsxulprototypeelement*, nsidocument*, bool, bool,mozilla::dom::element**) (/home/njn/moz/mi5/dom/xul/nsxulelement.cpp:287) #06: nsxblcontentsink::createelement(char16_t const**, unsigned int, mozilla::dom::nodeinfo*, unsigned int, nsicontent**, bool*, mozilla::dom::fromparser) (/home/njn/moz/mi5/dom/xbl/nsxblcontentsink.cpp:874) #07: nscomptr<nsicontent>::startassignment() (/home/njn/moz/...
...dmd only knows about heap blocks that are measured via a function created with one of the following two macros: moz_define_malloc_size_of moz_define_malloc_size_of_on_alloc fortunately, most of the existing memory reporters do this.
JS::PerfMeasurement
perfmeasurement::perfmeasurement(eventmask tomeasure) the constructor creates a new profiling object, which measures some subset of the requested events.
...perfmeasurement* js::extractperfmeasurement(jsval wrapper) if you are the c++ side of an xpcom interface, and you want to benchmark only part of your execution time but make the results available to javascript, you can declare a bare jsval argument in your .idl file and have javascript pass a perfmeasurement object that it created in that argument slot.
Leak-hunting strategies and tips
when a c++ object is exposed to javascript (the more common of the two), an xpcwrappednative object is created.
...the nsxpcwrappedjs object creates a gc root that exists as long as the wrapper does.
Measuring performance using the PerfMeasurement.jsm code module
the first thing you need to do is to import the module into your scope: components.utils.import("resource://gre/modules/perfmeasurement.jsm") you can then create a perfmeasurement object.
...for instance, let's measure instructions executed, cache references, and cache misses: let monitor = new perfmeasurement(perfmeasurement.cpu_cycles | perfmeasurement.cache_references | perfmeasurement.cache_misses); this creates a new perfmeasurement object, configured to record the specified event types.
Profiling with the Firefox Profiler
clicking on a tracing marker will create a selection corresponding with its duration allowing for easy zooming in on interesting time ranges.
... as you zoom in on ranges, breadcrumbs are created allowing you to easily navigate back to previously-selected ranges or the entire profile (denoted as "full range").
Refcount tracing and balancing
this is probably "okay" because it's a factory method that creates an addref()-ed object.
...to aid in this process, you can create an "excludes file", that lists the name of functions that you want to exclude from the tree building process (presumably because you've matched them).
Patches and pushes
method="get" template="http://ff.search.yahoo.com/gossip?output=fxjson&amp;command={searchterms}" />*** <url type="text/html" method="get" template="http://search.yahoo.com/search"> <param name="p" value="{searchterms}"/> <param name="ei" value="utf-8"/> <mozparam name="fr" condition="pref" pref="yahoo-fr" /> </url> <searchform>http://search.yahoo.com/</searchform> </searchplugin> create xml files for each search plugin preference following the above example.
... create a patch of the searchplugins directory by entering the following command in your command-line tool, where mypatch.diff is where you give your patch a name: $ hg add mozilla/browser/searchplugins/ $ hg diff mozilla/browser/searchplugins/ > mypatch.diff attach your patch file to the bug by clicking the "add an attachment" link.
Midas
createlink a uri.
... insertbronreturn true/false selects whether pressing return inside a paragraph creates another paragraph or just inserts a <br> tag.
Nonblocking IO In NSPR
a thread is typically created to attend to one of the simultaneous i/o operations that may potentially block.
...in nspr, a new socket returned by <tt>pr_newtcpsocket()</tt> or <tt>pr_newudpsocket()</tt> is always created in blocking mode.
Monitors
monitor type with the exception of pr_newmonitor, which creates a new monitor object, all monitor functions require a pointer to an opaque object of type prmonitor.
... pr_newmonitor creates a new monitor.
PRFileMap
type returned by pr_createfilemap and passed to pr_memmap and pr_closefilemap.
...before actually mapping a file to memory, you must create a memory-mapped file object by calling pr_createfilemap, which returns a pointer to prfilemap.
PRProcessAttr
syntax #include <prproces.h> typedef struct prprocessattr prprocessattr; description this opaque structure describes the attributes of a process to be created.
... pass a pointer to a prprocessattr into pr_createprocess when you create a new process, specifying information such as standard input/output redirection and file descriptor inheritance.
PRStaticLinkTable
a static link table entry can be created by a client of the runtime so that other clients can access static or dynamic libraries transparently.
...if, during initialization, such entries are manually created, then future attempts to link to the symbols can be treated in a consistent fashion.
PRThreadType
the type of an nspr thread, specified as a parameter to pr_createthread.
...nspr allows the client to synchronize the termination of all user threads and ignores those created as system threads.
PR_DetachThread
a native thread not created by nspr is automatically attached the first time it calls an nspr function, and automatically detached when it exits.
... in nspr release 19980529b and earlier, it is necessary for a native thread not created by nspr to call pr_attachthread before it calls any nspr functions, and call pr_detachthread when it is done calling nspr functions.
PR_ExportFileMapAsString
creates a string identifying a prfilemap.
... returns prstatus description creates an identifier, as a string, from a prfilemap object previously created with pr_openanonfilemap.
PR_GetInheritedFileMap
imports a prfilemap previously exported by my parent process via pr_createprocess.
... description pr_getinheritedfilemap retrieves a prfilemap object exported from its parent process via pr_createprocess.
PR_JoinThread
pr_jointhread must not be called until after pr_createthread has returned.
... if pr_jointhread is not called on the same thread as pr_createthread, then it is the caller's responsibility to ensure that pr_createthread has completed.
PR_NewMonitor
creates a new monitor object.
... description a newly created monitor has an entry count of zero.
PR NewProcessAttr
creates a process attributes structure.
... description this function creates a new prprocessattr structure that specifies the attributes of a new process, then returns a pointer to the structure.
PR_SetConcurrency
creates extra virtual processor threads.
... syntax #include <prinit.h> void pr_setconcurrency(pruintn numcpus); parameter pr_setconcurrency has one parameter: numcpus the number of extra virtual processor threads to be created.
PR_Sleep
if ticks is not pr_interval_no_wait, pr_sleep uses an existing lock, but has to create a new condition for this purpose.
... if you have already created such structures, it is more efficient to use them directly.
Thread Pools
thread pools create and manage threads to provide support for scheduling work (jobs) onto one or more threads.
... thread pool types thread pool functions thread pool types prjobiodesc prjobfn prthreadpool prjob thread pool functions pr_createthreadpool pr_queuejob pr_queuejob_read pr_queuejob_write pr_queuejob_accept pr_queuejob_connect pr_queuejob_timer pr_canceljob pr_joinjob pr_shutdownthreadpool pr_jointhreadpool ...
NSPR release process
create a beta cvs tag.
... create a rtm cvs tag.
Building NSS
use_asan 0 do not create an addresssanitizer build.
... 1 create an addresssanitizer build.
Certificate functions
cert_checkcertusage mxr 3.3 and later cert_comparename mxr 3.2 and later cert_comparevaliditytimes mxr 3.11 and later cert_completecrldecodeentries mxr 3.6 and later cert_convertanddecodecertificate mxr 3.9.3 and later cert_copyname mxr 3.4 and later cert_copyrdn mxr 3.5 and later cert_createava mxr 3.2.1 and later cert_createcertificate mxr 3.5 and later cert_createcertificaterequest mxr 3.2 and later cert_createname mxr 3.2.1 and later cert_createocspcertid mxr 3.6 and later cert_createocsprequest mxr 3.6 and later cert_createrdn mxr 3.2.1 and later cert_createsubjectcertlist ...
...mxr 3.4 and later cert_createvalidity mxr 3.5 and later cert_crlcacherefreshissuer mxr 3.7 and later cert_decodealtnameextension mxr 3.10 and later cert_decodeauthinfoaccessextension mxr 3.10 and later cert_decodeauthkeyid mxr 3.10 and later cert_decodeavavalue mxr 3.4 and later cert_decodebasicconstraintvalue mxr 3.2 and later cert_decodecertfrompackage mxr 3.4 and later cert_decodecertificatepoliciesextension mxr 3.2 and later cert_decodecertpackage mxr 3.2 and later cert_decodecrldistributionpoints mxr 3.10 and later cert_decodedercrl mxr 3.2 and later cert_decodedercrlwithflags mxr 3.6 and later ...
Cryptography functions
pk11_clonecontext mxr 3.2 and later pk11_configurepkcs11 mxr 3.2 and later pk11_convertsessionprivkeytotokenprivkey mxr 3.6 and later pk11_convertsessionsymkeytotokensymkey mxr 3.6 and later pk11_copytokenprivkeytosessionprivkey mxr 3.11 and later pk11_createcontextbysymkey mxr 3.2 and later pk11_createdigestcontext mxr 3.2 and later pk11_creategenericobject mxr 3.12 and later pk11_createmergelog mxr 3.12 and later pk11_createpbealgorithmid mxr 3.2 and later pk11_createpbev2algorithmid mxr 3.12 and l...
... 3.6 and later seckey_cachestaticflags mxr 3.10 and later seckey_converttopublickey mxr 3.2 and later seckey_copyprivatekey mxr 3.2 and later seckey_copypublickey mxr 3.6 and later seckey_copysubjectpublickeyinfo mxr 3.4 and later seckey_createdhprivatekey mxr 3.3 and later seckey_createecprivatekey mxr 3.8 and later seckey_createsubjectpublickeyinfo mxr 3.2 and later seckey_decodedersubjectpublickeyinfo mxr 3.4 and later seckey_destroyprivatekey mxr 3.2 and later seckey_ecparamstobasepointorderlen ...
NSS_3.12.1_release_notes.html
bug 67890: create self-signed cert with existing key that signed csr bug 129303: nss needs to expose interfaces to deal with multiple token sources of certs.
... bug 433594: crash destroying ocsp cert id [[@ cert_destroyocspcertid ] bug 434099: nss relies on unchecked pkcs#11 object attribute values bug 434187: fix the gcc compiler warnings in nss/lib bug 434398: libpkix cannot find issuer cert immediately after checking it with ocsp bug 434808: certutil -b deadlock when importing two or more roots bug 434860: coverity 1150 - dead code in ocsp_createcertid bug 436428: remove unneeded assert from sec_pkcs7encryptlength bug 436430: make nss public headers compilable with no_nspr_10_support defined bug 436577: uninitialized variable in sec_pkcs5createalgorithmid bug 438685: libpkix doesn't try all the issuers in a bridge with multiple certs bug 438876: signtool is still using static libraries.
NSS 3.12.4 release notes
nss builds for mozilla on linux bug 499385: drbg reseed function needs to be tested on post bug 499825: utilrename.h is missing from solaris packages bug 502961: allocator mismatch in pk11mode bug 502965: allocator mismatch in sdrtest bug 502972: another allocator mismatch in sdrtest bug 504398: pkix_pl_aiamgr_gethttpcerts could crash if sec_getregisteredhttpclient fails bug 504405: pkix_pl_crldp_create will fail on alloc success because of a missing !
... bug 504408: pkix_pl_crldp_create will always fail if dp->distpointtype != generalname bug 504456: exploitable heap overflow in nss shell expression (filename globbing) parsing bug 505559: need function to identify the one and only default internal private key slot.
NSS 3.21 release notes
certutil now supports a --rename option to change a nickname (bug 1142209) tls extended master secret extension (rfc 7627) is supported (bug 1117022) new info functions added for use during mid-handshake callbacks (bug 1084669) new functions in nss.h nss_optionset - sets nss global options nss_optionget - gets the current value of nss global options in secmod.h secmod_createmoduleex - create a new secmodmodule structure from module name string, module parameters string, nss specific parameters string, and nss configuration parameter string.
...the difference with secmod_createmodule is the new function handles nss configuration parameter strings.
NSS 3.31 release notes
in pkcs11uri.h pk11uri_createuri - create a new pk11uri object from a set of attributes.
... corrected the encoding of domain name constraints extensions created by certutil nss supports a clean seeding mechanism for *nix systems now using only /dev/urandom.
NSS Sample Code Sample_1_Hashing
*/ static int digestfile(prfiledesc *outfile, prfiledesc *infile, secoidtag hashoidtag) { unsigned int nb; unsigned char ibuf[4096]; unsigned char digest[64]; unsigned int len; unsigned int digestlen; hash_hashtype hashtype; hashcontext *hashcontext = null; hashtype = hash_gethashtypebyoidtag(hashoidtag); hashcontext = hash_create(hashtype); if (hashcontext == null) { return secfailure; } do { hash_begin(hashcontext); /* incrementally hash the file contents */ while ((nb = pr_read(infile, ibuf, sizeof(ibuf))) > 0) { hash_update(hashcontext, ibuf, nb); } hash_end(hashcontext, digest, &len, 64); /* normally we would write it out in binary w...
...progname + 1 : argv[0]; rv = nss_nodb_init("/tmp"); if (rv != secsuccess) { fprintf(stderr, "%s: nss_init failed in directory %s\n", progname, "/tmp"); return -1; } /* parse command line arguments */ optstate = pl_createoptstate(argc, argv, "t:"); while ((status = pl_getnextopt(optstate)) == pl_opt_ok) { switch (optstate->option) { case 't': require_arg(optstate->option, optstate->value); hashname = strdup(optstate->value); break; } } if (!hashname) usage(progname); /* convert and validate */ hashoidtag = hashnametooidtag(ha...
NSS Sample Code sample2
buf1 len must be atleast (data len + 8) */ tmp1_outlen = tmp2_outlen = 0; /* create cipher context */ enccontext = pk11_createcontextbysymkey(ciphermech, cka_encrypt, symkey, secparam); rv1 = pk11_cipherop(enccontext, buf1, &tmp1_outlen, sizeof(buf1), data, strlen(data)+1); rv2 = pk11_digestfinal(enccontext, buf1+tmp1_outlen, &tmp2_outlen, sizeof(buf1)-tmp1_outlen); pk11_destroyconte...
...buf2 len must be atleast buf1 len */ tmp1_outlen = tmp2_outlen = 0; /* create cipher context */ enccontext = pk11_createcontextbysymkey(ciphermech, cka_decrypt, symkey, secparam); rv1 = pk11_cipherop(enccontext, buf2, &tmp1_outlen, sizeof(buf2), buf1, result_len); rv2 = pk11_digestfinal(enccontext, buf2+tmp1_outlen, &tmp2_outlen, result_len-tmp1_outlen); pk11_destroycontext(enccontext, pr_true); result_len...
NSS Sample Code sample4
the db password should be "test" and the cert * nickname should be "testca" * here is one way of doing it: * # create ca cert db, if -f not provided, prompts for passwd * $ certutil -n -d .
... * # create ca cert, self-signed, generates key-pair, prompts for key * # type, cert type etc * # answers for prompts: 5,9,n,y,-1,n,5,6,7,9,n * $ certutil -s -s "cn=test ca, o=bogus inc, l=mtn view, st=ca, c=us" \ * -n testca -t ctu,ctu,ctu -v 60 -x -d .
Hashing - sample 1
*/ static int digestfile(prfiledesc *outfile, prfiledesc *infile, secoidtag hashoidtag) { unsigned int nb; unsigned char ibuf[4096]; unsigned char digest[64]; unsigned int len; hash_hashtype hashtype; hashcontext *hashcontext = null; hashtype = hash_gethashtypebyoidtag(hashoidtag); hashcontext = hash_create(hashtype); if (hashcontext == null) { return secfailure; } do { hash_begin(hashcontext); /* incrementally hash the file contents */ while ((nb = pr_read(infile, ibuf, sizeof(ibuf))) > 0) { hash_update(hashcontext, ibuf, nb); } hash_end(hashcontext, digest, &len, 64); /* normally we would write it out in binary w...
...progname + 1 : argv[0]; rv = nss_nodb_init("/tmp"); if (rv != secsuccess) { fprintf(stderr, "%s: nss_init failed in directory %s\n", progname, "/tmp"); return -1; } /* parse command line arguments */ optstate = pl_createoptstate(argc, argv, "t:"); while ((status = pl_getnextopt(optstate)) == pl_opt_ok) { switch (optstate->option) { case 't': require_arg(optstate->option, optstate->value); hashname = strdup(optstate->value); break; } } if (!hashname) usage(progname); /* convert and validate */ hashoidtag = hashnametooidtag(ha...
sample1
*/ static int digestfile(prfiledesc *outfile, prfiledesc *infile, secoidtag hashoidtag) { unsigned int nb; unsigned char ibuf[4096]; unsigned char digest[64]; unsigned int len; unsigned int digestlen; hash_hashtype hashtype; hashcontext *hashcontext = null; hashtype = hash_gethashtypebyoidtag(hashoidtag); hashcontext = hash_create(hashtype); if (hashcontext == null) { return secfailure; } do { hash_begin(hashcontext); /* incrementally hash the file contents */ while ((nb = pr_read(infile, ibuf, sizeof(ibuf))) > 0) { hash_update(hashcontext, ibuf, nb); } hash_end(hashcontext, digest, &len, 64); /* normally we would write it o...
...progname + 1 : argv[0]; rv = nss_nodb_init("/tmp"); if (rv != secsuccess) { fprintf(stderr, "%s: nss_init failed in directory %s\n", progname, "/tmp"); return -1; } /* parse command line arguments */ optstate = pl_createoptstate(argc, argv, "t:"); while ((status = pl_getnextopt(optstate)) == pl_opt_ok) { switch (optstate->option) { case 't': require_arg(optstate->option, optstate->value); hashname = strdup(optstate->value); break; } } if (!hashname) usage(progname); /* convert and validate */ hashoidtag = hashn...
nss tech note7
these data types should be used as if they were opaque structures, that is, they should only be created by some nss functions and you always pass pointers to these data types to nss functions and never examine the members of these structures.
... how are these keys created in nss?
NSS PKCS11 Functions
note: the database must be in the internal token, and must be one created with secmod_openuserdb().
...this slot must a a slot created by secmod_openuserdb() at some point in the past.
FC_CopyObject
name fc_copyobject - create a copy of an object.
... description fc_copyobject creates a copy of an object using the attributes specified in the template.
NSPR functions
the following nspr functions allow you to create your own nspr i/o layer and manipulate it.
... 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.
NSS tools : cmsutil
-o create a certificates-only message.
...if this is the first encrypted message for that set of recipients, a new enveloped message will be created that you can then use for future messages (encrypt only).
NSS reference
pkcs #7 functions based on "archived pkcs #7 functions documentation." pkcs #5 functions password-based encryption sec_pkcs5getiv sec_pkcs5createalgorithmid sec_pkcs5getcryptoalgorithm sec_pkcs5getkeylength sec_pkcs5getpbealgorithm sec_pkcs5isalgorithmpbealg pkcs #12 functions based on "archived pkcs #12 functions documentation." used to exchange data such as private keys and certificates between two parties.
... sec_pkcs12createexportcontext sec_pkcs12createpasswordprivsafe sec_pkcs12createunencryptedsafe sec_pkcs12addcertandkey sec_pkcs12addpasswordintegrity sec_pkcs12enablecipher sec_pkcs12encode sec_pkcs12destroyexportcontext sec_pkcs12decoderstart sec_pkcs12decoderimportbags sec_pkcs12decoderupdate sec_pkcs12decoderfinish sec_pkcs12decodervalidatebags sec_pkcs12decoderverify sec_pkcs12decodergetcerts sec_pkcs12decodersettargettokencas sec_pkcs12decoderiterateinit sec_pkcs12decoderiteratenext sec_pkcs12isencryptionallowed sec_pkcs12setpreferredcipher nspr functions a small number of nspr functions are required for using the certificate verification and ssl functions in nss.
NSS Tools
currently, you must download the nss 3.1 source and build it to create binary files for the nss tools.
... source, documentation, tasks/plans signtool 1.3 create digitally-signed jar archives containing files and/or code.
NSS Tools cmsutil
-o create a certificates-only message.
...if this is the first encrypted message for that set of recipients, a new enveloped message will be created that you can then use for future messages (encrypt only).
NSS tools : cmsutil
MozillaProjectsNSStoolscmsutil
-o create a certificates-only message.
... if this is the first encrypted message for that set of recipients, a new enveloped message will be created that you can then use for future messages (encrypt only).
Proxies in Necko
this means that callers can just create an nsichannel, not needing to worry about whether the channel will use a proxy or not the basic interfaces for proxies are: nsiproxyinfo, nsiprotocolproxyservice, and nsiproxiedprotocolhandler nsiproxyinfo is a simple helper which stores information about the type of the proxy, its host and its port.
...finally, depending on the protocol, the proxy info will be created with the appropriate type, host and port.
Rhino FAQ
frequently asked questions about rhino how do i create a java array from javascript?
...for instance, to create an array of java.lang.string of length five, do var stringarray = java.lang.reflect.array.newinstance(java.lang.string, 5); then if you wish to assign the string "hi" to the first element, simply execute stringarray[0] = "hi".
Rhino shell
sync(function) creates a synchronized function (in the sense of a java synchronized method) from an existing function.
... $ java org.mozilla.javascript.tools.shell.main -e "print('hi')" hi $ java org.mozilla.javascript.tools.shell.main js> print('hi') hi js> 6*7 42 js> function f() { return a; } js> var a = 34; js> f() 34 js> quit() $ cat echo.js for (i in arguments) { print(arguments[i]) } $ java org.mozilla.javascript.tools.shell.main echo.js foo bar foo bar $ spawn and sync the following example creates 2 threads via spawn and uses sync to create a synchronized version of the function test.
SpiderMonkey compartments
compartments are used to create multiple javascript memory heaps, which avoids having one heap for all javascript objects.
...this has some important implications: all objects created by a website reside in the same compartment and hence are located in the same memory region.
GCIntegration - SpiderMonkey Redirect 1
in the middle frame some code creates a pointer from b to c and destroys the pointer from a to c.
...now let's assume, between the left and right frames, that some code has read the weak pointer to c and then created a regular (strong) reference from b to c.
JIT Optimization Strategies
consider the following example: function base() {} base.prototype = { get x() { return 3; } }; function derived1() {} derived1.prototype = object.create(base.prototype); function derived2() {} derived1.prototype = object.create(base.prototype); if a property access for d.x sees only instances of both derived1 and derived2 for d, it can optimize the access to x to a call to the getter function defined on base.
...} }; function derived1() {} derived1.prototype = object.create(base.prototype); function derived2() {} derived1.prototype = object.create(base.prototype); if a property write for d.x = val sees only instances of both derived1 and derived2 for d, it can optimize the write to x to a call to the setter function defined on base.
JS::CallArgs
embedders should start internally switching away from using argc and vp directly, except to create a callargs.
...the principal way to create a callargs is like so, using js::callargsfromvp: static bool functionreturningargctimesarg0(jscontext *cx, unsigned argc, js::value *vp) { js::callargs args = js::callargsfromvp(argc, vp); // guard against no arguments or a non-numeric arg0.
JS::CompileFunction
this article covers features introduced in spidermonkey 17 create a javascript function from a text string.
... name is the name to assign to the newly created function.
JS::FalseValue
this article covers features introduced in spidermonkey 24 create a js::value that represents the javascript value false.
... syntax js::value js::falsevalue() description js::falsevalue creates a js::value that represents the javascript value false.
JS::NullValue
this article covers features introduced in spidermonkey 24 create a js::value that represents the javascript value null.
... syntax js::value js::nullvalue(); description js::nullvalue creates a js::value that represents the javascript value null.
JS::TrueValue
this article covers features introduced in spidermonkey 24 create a js::value that represents the javascript value true.
... syntax js::value js::truevalue() description js::truevalue creates a js::value that represents the javascript value true.
JS::UndefinedValue
this article covers features introduced in spidermonkey 24 create a js::value that represents the javascript value undefined.
... syntax js::value js::undefinedvalue(); description js::undefinedvalue creates a js::value that represents the javascript value undefined.
JSClass
a c/c++ program can use a jsclass with the js_initclass and js_newobject apis to create objects that have custom methods and properties implemented in c/c++.
...when a script creates a new property, this is called after addproperty.
JSFastNative
apis such as js_initclass and js_definefunctions can create custom methods that are implemented as c/c++ functions of this type, instead of jsnative.
... to create a jsfunctionspec that points to a jsfastnative, use js_fn.
JSFunction
for other function objects - that is, functions created by running javascript code containing function declarations or function-expressions-the relationship between the jsfunction * and the jsobject * is not well-defined.
...function objects created by calling js_newfunction have two reserved slots for the application's use.
JSGetObjectOps
jsgetobjectops is the type for jsclass.getobjectops callback syntax typedef jsobjectops * (* jsgetobjectops)(jscontext *cx, jsclass *clasp); name type description cx jscontext * the js context in which the new object is being created.
... jsclass hooks jsclass offerd following hook: the jsclass.getobjectops hook is called each time an object is created.
JSPrincipals
the data content of a principals object is defined by the application, which creates instances of jsprincipals, initializes their refcount fields to 1, and passes them into the engine through the js_...forprincipals functions.
...these functions ensure that the given jsprincipals object is indelibly associated not only with the script being compiled or evaluated, but with all functions ever created by that script or code eval()-ed by it.
JSReserveSlotsOp
syntax typedef uint32 (* jsreserveslotsop)(jscontext *cx, jsobject *obj); name type description cx jscontext * the js context in which the new object is being created.
... jsclass hooks jsclass offers the following hook: the jsclass.reserveslots callback is called each time a new object is created.
JSStringFinalizer
this article covers features introduced in spidermonkey 17 finalize external strings created by js_newexternalstring.
... description jsstringfinalizer::finalize finalizes external strings created by js_newexternalstring.
JS_ClearContextThread
description an application that creates or uses a jscontext in one thread, then uses or destroys it in another thread, must use js_clearcontextthread and js_setcontextthread to transfer the jscontext safely from one thread to the other.
... so the usual code for using a jscontext on a thread other than the one where it was created looks like this: void mythread(jscontext *cx) { js_setcontextthread(cx); /* note: outside the request */ js_beginrequest(cx); ...
JS_CompileFunction
creates a javascript function from a text string.
... name is the name to assign to the newly created function.
JS_CompileFunctionForPrincipals
create a security-enabled js function from a text string.
... name is the name to assign to the newly created function.
JS_ConvertArguments
obsolete since jsapi 30 this must be an argv pointer created by the js engine and passed to a jsnative or jsfastnative callback, not an array created by application code.
...(if conversion creates a new gc thing, the corresponding jsval is written back to argv, which is rooted.) description js_convertarguments provides a convenient way to translate a series of js values into their corresponding js types with a single function call.
JS_DefineFunctions
description js_definefunctions creates zero or more functions and makes them properties (methods) of a specified object, obj, as if by calling js_definefunction repeatedly.
...(the macro js_fs_end can be used for the last element.) js_definefunctions creates one function for each non-zero element in the array.
JS_DefineProperty
create a new property on an object.
... obj js::handleobject the object on which to create the new property.
JS_DropExceptionState
destroys a jsexceptionstate object previously created using js_saveexceptionstate.
...this object should previously have been created using js_saveexceptionstate.
JS_ErrorFromException
get or create jserrorreport from an exception object.
... description if obj is an exception object, the exception will have (or be able to lazily create) an error report struct, and js_errorfromexception will return the address of that struct.
JS_GetScopeChain
these objects represent the lexical scope of the currently executing statement or expression, not the call stack, so they include: the variable objects of any enclosing functions or let statements or expressions, and any objects selected by enclosing with statements, in order from the most-nested scope outward; lastly the global object against which the function was created.
...if the currently executing function was created in the scope of a different global object, then that object will be the last object in the current scope chain.
JS_InternString
otherwise a new string is created and added to the table.
... strings created with these functions are protected from garbage collection for the lifetime of the jsruntime.
JS_NewDouble
syntax jsdouble * js_newdouble(jscontext *cx, jsdouble d); name type description cx jscontext * the context in which to create the new number.
...if it is, js_newdouble creates a bad jsdouble that might behave as desired in some cases but not others.
JS_NewNumberValue
syntax jsbool js_newnumbervalue(jscontext *cx, jsdouble d, jsval *rval); name type description cx jscontext * the context in which to create the new number.
...otherwise, a new floating-point jsval is created.
JS_NewPropertyIterator
description create an object to iterate over the enumerable own properties of obj, in arbitrary order.
...the iterator object created by this function is not a javascript iterator.
JS_NewStringCopyZ
create a new javascript string based on a null-terminated c string.
... s const char * or const char16_t * pointer to the character array containing the text for the js string to create; or null.
JS_ReportError
create a formatted error or warning message to pass to a user-defined error reporting function.
...if the caller is in a jsapi callback, js_reporterror also creates a new javascript error object and sets it to be the pending exception on cx.
JS_RestoreExceptionState
restores the exception state from a jsexceptionstate object previously created using js_saveexceptionstate.
... description this function permits to restore any previously saved exception state which was saved into a jsexceptionstate object created by the js_saveexceptionstate function.
JS_SetPrototype
ordinarily you set a prototype for an object when you create the object with js_newobject, but if you do not set a prototype at that time, you can later call js_setprototype to do so.
...take care not to create a circularly-linked list of prototypes using this function, because such a set of prototypes cannot be resolved by the javascript engine and can easily lead to an infinite loop.
SpiderMonkey 1.8
it is fairly easy to create a microsoft visual studio project file for spidermonkey 1.8 from scratch.
...instead the object is created with no prototype.
SavedFrame
for example, if this frame’s children are calls to handlers for a promise this frame created, this frame’s asynccause would be "promise".
... asyncparent if this stack frame was called as a result of an asynchronous operation, for example if the function referenced by this frame is a promise handler, this property points to the stack frame responsible for the asynchronous call, for example where the promise was created.
TPS Tests
set up an environment and run a test to run tps, you should create a new firefox account using a restmail.net email address (strictly speaking, restmail isn't required, but it will allow tps to automatically do account confirmation steps for you.
... steps get the source code clone mozilla-central (choose your flavor): hg clone hg.mozilla.org/mozilla-central or git clone github.com/mozilla/gecko-dev cd into the tps folder cd testing/tps create the environment i suggest the path to be outside of the mc source tree python create_venv.py --username=%email% --password=%password% %path% note: if you are updating the tps environment and want to keep your existing config (eg, the existing username and password), you should instead execute: python create_venv.py --keep-config %path% activate the environment source %path%/b...
Thread Sanitizer
adjusting the build configuration create the build configuration file .mozconfig with the following content in your mozilla-central directory: mk_add_options moz_objdir=@topsrcdir@/objdir-ff-tsan mk_add_options moz_make_flags=-j12 # enable llvm specific code and build workarounds ac_add_options --enable-thread-sanitizer # if clang is already in your $path, then these can simply be: # export cc=clang # export cxx=clang++ export cc=...
...the build will then be created in a new subdirectory with that name.
Handling Mozilla Security Bugs
we have attempted to create a compromise scheme for how the mozilla project will handle reports of security vulnerabilities.
... expanding the mozilla security bug group as previously described, the mozilla security module owner can select one or more peers to share the core work of coordinating investigation and resolution of mozilla security vulnerabilities, and will work with them to create some agreed-upon ground rules for how this work can be most effectively shared among themselves.
Task graph
a "decision task" is created to decide what to do with the push.
... the decision task creates a lot of additional tasks.
Gecko object attributes
applied to: any role which related dom node has id attribute tag the actual markup tag used to create this element (also used in xul).
...if not specified, the default should be considered "additions text", which indicates that newly created objects and changes to text and text equivalents should be considered relevant, and that the hiding or removal of items is not.
Gecko events
event_dom_create an object has been created.
... is supported: yes event_dom_significant_change an object's properties or content have changed significantly so that the type of object has really changed, and therefore the accessible should be destroyed or recreated.
places.sqlite Database Troubleshooting
in the profile folder a places.sqlite-corrupt file has been created.
... create a folder to use temporarily for this work, such as my_work_folder.
XML Extras
more exhaustive test suites need to be created, however.
...the "workaround" is to use domparser object's parsefromstring() method to create a document from string, and pass the temporary document into send().
Creating XPCOM components
accordingly, the book is arranged so that you can follow along and create your own components or learn about different xpcom topics individually, as in a reference work.
... note: in general, you should try to avoid having to create xpcom components.
Components.ID
summary components.id is a constructor that creates native objects that conform to the nsijsid interface.
... syntax var interfaceid = [ new ] components.id(iid); parameters iid a string of the format '{00000000-0000-0000-0000-000000000000}' giving the interface id of the interface description components.id creates interface ids for use in implementing methods like queryinterface, getinterfaces, and other methods that take interface ids as parameters.
Components.utils.cloneInto
this function provides a safe way to take an object defined in a privileged scope and create a structured clone of it in a less-privileged scope.
...example this add-on script creates an object, clones it into the content window and makes it a property of the content window global: // add-on script var addonscriptobject = {"greeting" : "hello from add-on"}; contentwindow.addonscriptobject = cloneinto(addonscriptobject, contentwindow); scripts running in the page can now access the object: // page script button.addeventlistener("click", function() { console.log(window.addo...
Components object
utils.createobjectin creates a new object in the scope of the specified object's compartment.
... utils.sandbox creates sandbox objects for use with evalinsandbox.
IAccessibleText
lists, trees, and tables can have a large number of children and thus it's possible that the child objects for those controls would only be created as needed.
...lists, trees, and tables can have a large number of children and thus it's possible that the child objects for those controls would only be created as needed.
IJSDebugger
1.0 66 introduced gecko 9.0 inherits from: nsisupports last changed in gecko 9.0 (firefox 9.0 / thunderbird 9.0 / seamonkey 2.6) implemented by: @mozilla.org/jsdebugger;1 as a service: var jsdebugger = components.classes["@mozilla.org/jsdebugger;1"] .createinstance(components.interfaces.ijsdebugger); note: you should almost never directly use this service; instead, you should use the javascript code module that does this for you.
... the only time you should directly use this interface to create the debugger object is if you need to debug chrome; due to bug 707237, the javascript code module doesn't work in that case.
mozIStorageBindingParamsArray
last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) inherits from: nsisupports you can only create these objects by calling the mozistoragestatement.newbindingparamsarray().
... newbindingparams() creates and returns a new, empty, mozistoragebindingparams object to which you can add parameters and their values for binding.
nsIAccessibleTreeCache
le getcachedtreeitemaccessible(in long arow, in nsitreecolumn acolumn); void invalidatecache(in long arow, in long acount); void treeviewchanged(); void treeviewinvalidated(in long astartrow, in long aendrow, in long astartcol, in long aendcol); methods getcachedtreeitemaccessible() returns the tree item from the cache for the cell in the specified row and column; the nsiaccessible is created if it doesn't already exist in the cache.
...acount the number of treeitem accessibles to invalidate, the number sign specifies whether rows have been inserted (plus) or removed (minus) treeviewchanged() invalidates children created for the previous tree view.
nsIAuthPromptAdapterFactory
1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) method overview nsiauthprompt2 createadapter(in nsiauthprompt aprompt); methods createadapter() wrap an object implementing nsiauthprompt so that it's usable via nsiauthprompt2.
... nsiauthprompt2 createadapter( in nsiauthprompt aprompt ); parameters aprompt the nsiauthprompt to wrap.
nsIComponentRegistrar
registerfactory() registers a factory to be used to instantiate a particular class identified by classid, and creates an association of class name and contractid with the class.
... registerfactorylocation() registers a factory to be used to instantiate a particular class identified by classid, and creates an association of class name and contractid with the class.
nsIControllers
you should not normally need to create an instance, as you normally need to alter the window or element's existing list of controllers.
... to create an instance, use: var controllers = components.classes["@mozilla.org/xul/xul-controllers;1"] .createinstance(components.interfaces.nsicontrollers); method overview void appendcontroller(in nsicontroller controller); nsicontroller getcontrollerat(in unsigned long index); nsicontroller getcontrollerbyid(in unsigned long controllerid); unsigned long getcontrollercount(); nsicontroller getcontrollerforcommand(in string command); unsigned long getcontrollerid(in nsicontroller controller); void insertcontrollerat(in unsigned long index, in nsicontroller controller); void removecontroller(in nsicontroller controller); nsicontroller removecontrollerat(in unsigned long index); attributes attribute type description commanddispatcher nsidom...
nsIDBFolderInfo
to create an instance, use: implemented by: ?????????????????????????????????????
... as a service: var dbfolderinfo = components.classes["@mozilla.org/????????????????????????????"] .createinstance(components.interfaces.nsidbfolderinfo); method overview long andflags(in long flags); void changeexpungedbytes(in long delta); void changenummessages(in long delta); void changenumunreadmessages(in long delta); boolean getbooleanproperty(in string propertyname, in boolean defaultvalue); void getcharacterset(out acstring charset, out boolean overriden); void getcharactersetoverride(out boolean charactersetoverride); obsolete since gecko 1.8 string getcharptrcharacterset(); string getcharptrproperty(in string propertyname); ...
nsIDNSService
to access the service, use: var dnsservice = components.classes["@mozilla.org/network/dns-service;1"] .createinstance(components.interfaces.nsidnsservice); note: starting in gecko 7.0, the "happy eyeballs" strategy is used to reduce lengthy timeouts when attempting backup connections during attempts to connect from clients that have broken ipv6 connectivity.
...example let dnsservice = components.classes["@mozilla.org/network/dns-service;1"] .createinstance(components.interfaces.nsidnsservice); let thread = components.classes["@mozilla.org/thread-manager;1"] .getservice(components.interfaces.nsithreadmanager).currentthread; let host = "www.mozilla.org"; let listener = { onlookupcomplete: function(request, record, status) { if (!components.issuccesscode(status)) { // handle error here return; } let ad...
nsIDOMEvent
timestamp domtimestamp used to specify the time (in milliseconds relative to the epoch) at which the event was created.
... return value initevent() this method is used to initialize the value of an event created through the documentevent interface.
nsIDOMMouseScrollEvent
canbubblearg specifies whether or not the created event will bubble.
... cancelablearg specifies whether or not the created event can be canceled.
nsIDOMOrientationEvent
canbubblearg specifies whether or not the created event will bubble.
... cancelablearg specifies whether or not the created event can be canceled.
nsIDOMProgressEvent
canbubblearg specifies whether or not the created event will bubble.
... cancelablearg specifies whether or not the created event can be canceled.
nsIDOMXPathExpression
dom/interfaces/xpath/nsidomxpathexpression.idlscriptable represents a compiled xpath query returned from nsidomxpathevaluator.createexpression or document.createexpression inherits from: nsisupports last changed in gecko 1.7 method overview nsisupports evaluate(in nsidomnode contextnode, in unsigned short type, in nsisupports result) methods evaluate() evaluate the xpath expression.
...using null will create a new nsidomxpathresult.
nsIDocumentLoader
to create an instance, use: var documentloader = components.classes["@mozilla.org/docloaderservice;1"] .createinstance(components.interfaces.nsidocumentloader); method overview void clearparentdocloader(); obsolete since gecko 1.8 void createdocumentloader(out nsidocumentloader aninstance); obsolete since gecko 1.8 void destroy(); obsolete since gecko 1.8 ...
... createdocumentloader() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) void createdocumentloader( out nsidocumentloader aninstance ); parameters aninstance destroy() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) void destroy(); parameters none.
nsIFaviconService
an async request will be created for this uri and if the data is available, it will asynchronously get saved in the database without any further work from the caller.
...an entry linking the favicon with the page will be create with no data.
nsIFeedGenerator
1.0 66 introduced gecko 1.8 inherits from: nsifeedelementbase last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) attributes attribute type description agent astring the name of the software that created the feed.
... version astring a string indicating the version of the generator software that created the feed.
nsIFileOutputStream
this means that any errors that might happen when this flag is not set would happen during the first write, and if the file is to be created, it will not appear on the disk until the first write.
...use -1 to open the file in default mode (pr_wronly | pr_create_file | pr_truncate).
nsIFileView
to create an instance, use: var fileview = components.classes["@mozilla.org/filepicker/fileview;1"] .createinstance(components.interfaces.nsifileview); method overview void setdirectory(in nsifile directory); void setfilter(in astring filterstring); void sort(in short sorttype, in boolean reversesort); attributes attribute type description reversesort boolean if true results ...
...ecolumn" label="name" flex="1" primary="true"/> <treecol id="lastmodifiedcolumn" label="date" flex="1"/> <treecol id="size" label="size" flex="1"/> </treecols> <treechildren/> </tree> <script> var dir="/home/"; //the directory to be opened var ftree = document.getelementbyid("ftree"); //the xul tree element var lfile = components.classes["@mozilla.org/file/local;1"] .createinstance(components.interfaces.nsilocalfile); lfile.initwithpath(dir); // open the directory var fview = components.classes["@mozilla.org/filepicker/fileview;1"] .createinstance(components.interfaces.nsifileview); //create an instance of the component tview = fview.queryinterface(components.interfaces.nsitreeview); //get the nsitreeview interface fview.setdirectory(lfile.que...
nsIFrameLoader
sendcrossprocesskeyevent() creates and sends a keyevent to the content viewport's process.
... sendcrossprocessmouseevent() creates and sends a mouseevent to the content viewport's process.
nsIHttpChannel
inherits from: nsichannel last changed in gecko 1.3 to create an http channel, use nsiioservice with a http uri, for example: var ios = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); var ch = ios.newchannel("https://www.example.com/", null, null); method overview void getoriginalresponseheader(in acstring aheader, in nsihttpheadervisitor avisitor); acstring getrequestheader(in acstring aheader); acstring getresponseheader(in acstring header); boole...
... note: an http redirect results in a new channel being created.
nsIJSCID
inherits from: nsijsid last changed in gecko 1.7 method overview nsisupports createinstance(); nsisupports getservice(); methods createinstance() nsisupports createinstance(); parameters none.
... return value see also see components.classes for usage patterns of the createinstance() and getservice() methods.
nsIJetpackService
method overview nsijetpack createjetpack(); methods createjetpack() this method creates a new jetpack process and returns an nsijetpack interface that represents it.
... nsijetpack createjetpack(); parameters none.
nsILoginManager
to create an instance, use: var loginmanager = components.classes["@mozilla.org/login-manager;1"] .getservice(components.interfaces.nsiloginmanager); method overview void addlogin(in nsilogininfo alogin); nsiautocompleteresult autocompletesearch(in astring asearchstring, in nsiautocompleteresult apreviousresult, in nsidomhtmlinputelement aelement); unsigned...
... note: default values for the nsiloginmetainfo properties are created if the specified login doesn't explicitly specify them.
nsIMIMEInputStream
to create an instance, use: var mimeinputstream = components.classes["@mozilla.org/network/mime-input-stream;1"] .createinstance(components.interfaces.nsimimeinputstream); method overview void addheader(in string name, in string value); void setdata(in nsiinputstream stream); attributes attribute type description addcontentlength boolean when true a "content-length" header is automatically added to the stream.
... example var postdata = components.classes["@mozilla.org/network/mime-input-stream;1"] .createinstance(components.interfaces.nsimimeinputstream); postdata.addheader("content-type", "application/x-www-form-urlencoded"); postdata.addcontentlength = true; postdata.setdata(stringstream); ...
nsIMessenger
to create an instance, use: messenger = components.classes["@mozilla.org/messenger;1"] .createinstance(components.interfaces.nsimessenger); in thunderbird, a global nsimessenger object is defined as messenger via the createmessenger function in mailwindow.js.
... sendunsentmessages() creates a nsimsgsendlater instance and sends all messages for the given identity.
nsIMicrosummaryGenerator
for generators installed via some other mechanism (for example an extension that dynamically creates generators), this uri is a urn in a form of the extension's own choosing, with the only restriction being that the uri be globally unique.
... to ensure this, we recommend that such extensions incorporate uuids created by nsiuuidgenerator into the urns of the generators they create.
nsIMimeHeaders
to create an instance, use: implemented by: ?????????????????????????????????????
... as a service: var mimeheaders = components.classes["@mozilla.org/????????????????????????????"] .createinstance(components.interfaces.nsimimeheaders); method overview string extractheader([const] in string headername, in boolean getallofthem); void initialize([const] in string allheaders, in long allheaderssize); attributes attribute type description allheaders string read only.
nsIMsgFilter
arbitraryheader ) getterm() void nsimsgfilter::getterm ( in long termindex, in nsmsgsearchattribvalue attrib, in nsmsgsearchopvalue op, in nsimsgsearchvalue value, out boolean booleanand, out acstring arbitraryheader ) appendterm() void nsimsgfilter::appendterm (in nsimsgsearchterm term) createterm() nsimsgsearchterm nsimsgfilter::createterm ( ) matchhdr() void nsimsgfilter::matchhdr ( in nsimsgdbhdr msghdr, in nsimsgfolder folder, in nsimsgdatabase db, in string headers, in unsigned long headersize, out boolean result ) logrulehit() void nsimsgfilter::logrulehit ( in nsimsgruleaction afilteraction, in nsimsgdbhdr aheader ...
...) createaction() nsimsgruleaction nsimsgfilter::createaction ( ) getactionat() nsimsgruleaction nsimsgfilter::getactionat (in long aindex) appendaction() void nsimsgfilter::appendaction (in nsimsgruleaction action ) clearactionlist() void nsimsgfilter::clearactionlist() getsortedactionlist() void nsimsgfilter::getsortedactionlist (in nsisupportsarray actionlist) ...
nsIMsgMessageService
aconvertdata if aconvertdata is true, it will create a stream converter from message rfc2822 to */*.
...e.g., header=filter return the nsiuri that gets run example for example, the next piece of code shows the selected message code on a dialog: (taken from mozillazine) var content = ""; var messageuri = getfirstselectedmessage(); var msgservice = messenger.messageservicefromuri(messageuri); var msgstream = components.classes["@mozilla.org/network/sync-stream-listener;1"].createinstance(); var consumer = msgstream.queryinterface(components.interfaces.nsiinputstream); var scriptinput = components.classes["@mozilla.org/scriptableinputstream;1"].createinstance(); var scriptinputstream = scriptinput.queryinterface(components.interfaces.nsiscriptableinputstream); scriptinputstream.init(consumer); try { msgservice.streammessage(messageuri, msgstream, msgwindow, n...
nsIMsgProtocolInfo
folderscreateasync boolean new in thunderbird 24 (bug 832034) preflightprettynamewithemailaddress boolean unused.
... remarks this is one of the interfaces that is required to create a new account type.
nsINavHistoryObserver
avisitid id of the visit that was just created.
...if no such query exists, the history result creates a new query node dynamically.
nsINavHistoryQuery
clone() this method creates a new query item with the same parameters of this one.
...return value returns the newly created cloned query.
nsINavHistoryQueryOptions
methods clone() this method creates a new options item with the same parameters of this one.
...return value returns the newly created cloned options.
Component; nsIPrefBranch
inherits from: nsisupports last changed in gecko 58 (firefox 58 / thunderbird 58 / seamonkey 2.55) this object is created with a "root" value which describes the base point in the preferences "tree" from which this "branch" stems.
...for example, if this object is created with the root "browser.startup.", the preferences "browser.startup.page", "browser.startup.homepage", and "browser.startup.homepage_override" can be accessed by simply passing "page", "homepage", or "homepage_override" to the various get/set methods.
nsIPrintingPrompt
historically, platform toolkits with native dialogs have implemented them in the gfx layer usually they were displayed when a new devicecontextspec specific to that platform was created.
...if you wish to have a native progress dialog on windows you will have to create and register your own service.
nsIProcess
to create an instance, use: var process = components.classes["@mozilla.org/process/util;1"] .createinstance(components.interfaces.nsiprocess); method overview void init(in nsifile executable); void initwithpid(in unsigned long pid); obsolete since gecko 1.9.2 void kill(); void run(in boolean blocking, [array, size_is(count)] in string args, in unsigned long count); void runasync([array, size_is(count)] in string args, in unsigned long count, [optional] in nsiobserver observer, [optional] in...
... example // create an nsifile for the executable var file = components.classes["@mozilla.org/file/local;1"] .createinstance(components.interfaces.nsifile); file.initwithpath("c:\\myapp.exe"); // create an nsiprocess var process = components.classes["@mozilla.org/process/util;1"] .createinstance(components.interfaces.nsiprocess); process.init(file); // run the process.
nsIProcessScriptLoader
if aallowdelayedload is true, then the script will also be loaded into any new child processes created after the loadprocessscript() call.
... if this flag is true, the process script will be loaded into any new child processes created after the loadprocessscript() call, until removedelayedprocessscript() is called for that script.
nsIProtocolProxyService
if the protocol handler for the given uri supports nsiproxiedprotocolhandler, then the nsiproxyinfo instance returned from resolve may be passed to the nsiproxiedprotocolhandler.newproxiedchannel() method to create a nsichannel to the given uri that uses the specified proxy.
...this method may be useful in conjunction with nsisockettransportservice.createtransport() for creating, for example, a socks connection.
nsIPushSubscription
sending a post request to this url routes the message to the instance of firefox that created the subscription.
...components; const scriptsecuritymanager = cc["@mozilla.org/scriptsecuritymanager;1"] .getservice(ci.nsiscriptsecuritymanager); const pushservice = cc["@mozilla.org/push/service;1"] .getservice(ci.nsipushservice); function sendsubscriptiontoserver(subscription) { let request = cc["@mozilla.org/xmlextras/xmlhttprequest;1"] .createinstance(ci.nsixmlhttprequest); request.open("post", "https://example.com/register-for-push", true); request.addeventlistener("error", () => { cu.reporterror("error sending subscription to server"); }); request.send(json.stringify({ endpoint: subscription.endpoint, // base64-encode the key and authentication secret.
nsISelection
to create an instance, use: implemented by: ?????????????????????????????????????
... as a service: var selection = components.classes["@mozilla.org/????????????????????????????"] .createinstance(components.interfaces.nsiselection); method overview void addrange(in nsidomrange range); void collapse(in nsidomnode parentnode, in long offset); [noscript,notxpcom,nostdcall] boolean collapsed(); void collapsenative(in nsidomnode parentnode, in long offset); native code only!
nsIServerSocket
to create an instance, use: var serversocket = components.classes["@mozilla.org/network/server-socket;1"] .createinstance(components.interfaces.nsiserversocket); method overview void init(in long aport, in boolean aloopbackonly, in long abacklog); void initwithaddress([const] in prnetaddrptr aaddr, in long abacklog);native code only!
...this does not affect already connected client sockets (i.e., the nsisockettransport instances created from this server socket).
nsISmsService
to create an instance, use: var smsservice = components.classes["@mozilla.org/sms/smsservice;1"] .createinstance(components.interfaces.nsismsservice); method overview [implicit_jscontext] nsidommozsmsmessage createsmsmessage(in long id, in domstring delivery, in domstring sender, in domstring receiver, in domstring body, in jsval timestamp, in bool read ); unsigned short getnumberofmessagesfortext(in domstring text); boolean hassupport...
...(); void send(in domstring number, in domstring message, in long requestid, [optional] in unsigned long long processid); methods createsmsmessage() [implicit_jscontext] nsidommozsmsmessage createsmsmessage( in long id, in domstring delivery, in domstring sender, in domstring receiver, in domstring body, in jsval timestamp, in bool read ); parameters id a number representing the id of the message.
nsISocketProvider
to create an instance, use: var socketprovider = components.classes["@mozilla.org/network/socket;2?type="] .createinstance(components.interfaces.nsisocketprovider); method overview void addtosocket(in long afamily, in string ahost, in long aport, in string aproxyhost, in long aproxyport, in unsigned long aflags, in prfiledescstar afiledesc, out nsisupports asecurityinfo); native code only!
... native code only!newsocket creates a new socket.
nsIStringBundleService
to access this service, use: var stringbundleservice = components.classes["@mozilla.org/intl/stringbundle;1"] .getservice(components.interfaces.nsistringbundleservice); method overview nsistringbundle createbundle(in string aurlspec); nsistringbundle createextensiblebundle(in string aregistrykey); void flushbundles(); wstring formatstatusmessage(in nsresult astatus, in wstring astatusarg); methods createbundle() nsistringbundle createbundle( in string aurlspec ); parameters aurlspec the url of the properties file to load.
... createextensiblebundle() nsistringbundle createextensiblebundle( in string aregistrykey ); parameters aregistrykey the name of the category under which the properties file(s) have been registered.
nsIURI
to create an nsiuri object, you should use nsiioservice.newuri(), like this: function makeuri(aurl, aorigincharset, abaseuri) { var ioservice = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); return ioservice.newuri(aurl, aorigincharset, abaseuri); } components of a uri prepath path scheme userpa...
... if the uri stores information from the nsiioservice interface's nsiioservice.newuri() call that created it, other than just the parsed string, the behavior of this information when setting the spec attribute is undefined.
nsIWebSocketChannel
to create an instance, use: var websocketchannel = components.classes["@mozilla.org/????????????????????????????"] .createinstance(components.interfaces.nsiwebsocketchannel); method overview void asyncopen(in nsiuri auri, in acstring aorigin, in nsiwebsocketlistener alistener, in nsisupports acontext); void close(in unsigned short acode, in autf8string areason); void sendbinarymsg(in acstring amsg); voi...
... 1000 close_normal normal closure; the connection successfully completed whatever purpose for which it was created.
nsIWinAppHelper
toolkit/xre/nsiwinapphelper.idlscriptable used on windows only to do some work from a special process that gets created with elevated privileges.
...to create an instance, use: var xulappinfo = components.classes["@mozilla.org/xre/app-info;1"] .getservice(components.interfaces.nsiwinapphelper); the nsixulappinfo and nsixulruntime interfaces are also implemented by "xre/app-info".
nsIXSLTProcessor
to create an instance, use: var xsltprocessor = components.classes["@mozilla.org/document-transformer;1?type=xslt"] .createinstance(components.interfaces.nsixsltprocessor); method overview void clearparameters(); nsivariant getparameter(in domstring namespaceuri, in domstring localname); void importstylesheet(in nsidomnode style); void removeparameter(in domstring namespaceuri, in domstring localname); void reset(); void setparameter(in domstring namespaceuri, in domstring localname, in nsivariant value); nsidomdocument transformtodocument(in nsidomnode source); n...
...the created fragment will be owned by the specified output document.
nsIXmlRpcClient
tlistener that will get notified of xml-rpc events ctxt a context to be passed on to the listener methodname remote method to call arguments array of arguments to pass to the remote method count void asynccall ( in nsixmlrpcclientlistener listener, in nsisupports ctxt, in string methodname, [array, size_is(count)] in nsisupports arguments, in pruint32 count ); createtype() convenience: return the correct nsisupportsprimitive for a given xml-rpc type, or nsisupportsarray or nsidictionary.
... void createtype ( in unsigned long type, out nsiidref uuid, [iid_is(uuid),retval] out nsqiresult result ) ; parameters type one of the listed constants.
nsIZipReader
to create an instance, use: var zipreader = components.classes["@mozilla.org/libjar/zip-reader;1"] .createinstance(components.interfaces.nsizipreader); about character sets and code pages note: nsizipreader has a code page problem; that is, in the zip specification, filenames are supposed to use 7-bit ascii; however, most modern filesystems use 8 bit code pages, such as utf-8.
... var zr = cc["@mozilla.org/libjar/zip-reader;1"].createinstance(ci.nsizipreader); cu.import('resource://gre/modules/osfile.jsm'); cu.import('resource://gre/modules/fileutils.jsm'); var reusablestreaminstance = cc['@mozilla.org/scriptableinputstream;1'].createinstance(ci.nsiscriptableinputstream); var pathtoxpitoread = os.path.join(os.constants.path.profiledir, 'extensions', 'portabletester@jetpack.xpi'); var nsifilexpi = ...
nsIZipReaderCache
to create an instance, use: var zipreadercache = components.classes["@mozilla.org/libjar/zip-reader-cache;1"] .createinstance(components.interfaces.nsizipreadercache); method overview nsizipreader getinnerzip(in nsifile zipfile, in autf8string zipentry); nsizipreader getinnerzip(in nsifile zipfile, in string zipentry); obsolete since gecko 10 nsizipreader getzip(in nsifile zipfile); void init(in unsigned long cachesize); methods getinnerzip() returns a (possibly shared) cached nsizipre...
...otherwise the previously created nsizipreader is returned.
XPIDL
source and binary compatibility some consumers of idl interfaces create binary plugins that expect the interfaces to be stored in a specific way in memory.
... for out parameters, the callee creates the data, and transfers ownership to the caller.
Account Provisioner
to have logs dumped to the terminal, create a string preference called mail.provider.logging.dump and set its value to all.
... to have logs dumped to the error console, create a string preference called mail.provider.logging.console and set its value to all.
Events
some of these are standard events, such as those created by the dom.
... msgcreatedbview onactivecreatedview onactivemessagesloaded the active messages in the folder have been loaded oncreatedview a folder view has been created, but not yet shown.
Demo Addon
overview this demo add-on has been created by jonathan protzenko for his presentation at mozcamp 2011.
... }; let collection = query.getcollection(mylistener); at first, a new gloda query for finding messages is created.
Thunderbird extensions
gloda stands for « global database », and creates thunderbird-wide relations between objects.
...learn more about gloda: an overview of gloda how to create your first message query and read the gloda examples gloda internals: gloda debugging, gloda indexing more thunderbird-specific links some links may be out of date, but they still provide valuable information on the codebase.
Using MAPI with Thunderbird's Windows 7 developer builds
(be sure to copy - not move - these files.) in the uninstall sub-directory of the bin directory, run these two commands: helper.exe /setasdefaultappglobal helper.exe /setasdefaultappuser create an elevated shell and register the mapi proxy.dll as a com server.
... (one way to create an elevated shell is to invoke the command prompt from the start menu, right click, and select run as administrator.) in the elevated shell, change to the objdir/mozilla/dist/bin directory and enter this command: regsvr32 mapiproxy_inuse.dll ...
libmime content type handlers
00a024a7d144} #define ns_imime_content_type_handler_iid \ { 0x20dabd99, 0xf8b5, 0x11d2, \ { 0x8e, 0xe0, 0x0, 0xa0, 0x24, 0xa7, 0xd1, 0x44 } } class nsimimecontenttypehandler : public nsisupports { public: static const nsiid& getiid() { static nsiid iid = ns_imime_content_type_handler_iid; return iid; } ns_imethod getcontenttype(char **contenttype) = 0; ns_imethod createcontenttypehandlerclass(const char *content_type, contenttypehandlerinitstruct *initstruct, mimeobjectclass **objclass) = 0; }; #endif /* nsimimecontenttypehandler_h_ */ plugin installation/location the installation of these modules will be similar to the that of any xpcom component (i.e.
... sample content type handler plugin to see an example of a content type handler plugin, the source for the handler of the content type "text/calendar" can be viewed at the following link: calendar plugin note: this plugin simply creates a blue table in the output stream to identify the fact that it is operational, but the basic constructs of what is needed to build a functional content type handler can be seen.
Using popup notifications
creating a popup notification popup notifications can be created using the popupnotifications.jsm javascript code module.
... then you can create the popup notification at the appropriate time like this: popupnotifications.show(gbrowser.selectedbrowser, "sample-popup", "this is a sample popup notification.", null, /* anchor id */ { label: "do something", accesskey: "d", callback: function() { alert("doing something awesome!"); } }, null /* secondary action */ ); in this case, we aren't providing any secondary actions; that is, actions provided to the user through the drop-down menu.
Working with windows in chrome code
here is helper function that will package the data correctly and pass it to the newly opened window: function opendialog(parentwindow, url, windowname, features) { var array = components.classes["@mozilla.org/array;1"] .createinstance(components.interfaces.nsimutablearray); for (var i = 4; i < arguments.length; i++) { var variant = components.classes["@mozilla.org/variant;1"] .createinstance(components.interfaces.nsiwritablevariant); variant.setfromvariant(arguments[i]); array.appendelement(variant, false); } var watcher = components.classes["@mozilla...
... learning to create xpcom components takes time.
Using C struct and pointers
[ { "self": ctypes.pointertype(ctypes.void_t) }, { "str": ctypes.pointertype(ctypes.char) }, { "buff_size": ctypes.size_t }, { "i": ctypes.int }, { "f": ctypes.float }, { "c": ctypes.char } ]); here we are using the structtype() factory method of the ctypes object to create a ctype object that represents the c struct named st_t.
... the call to structtype() returns a ctype object, and we then apply the new operator to it to create a specific instance of this newly defined type - a javascript representation of the c struct.
StructType
note: at this time, there isn't a way to denote a packed structure (that is, one created in c using #pragma pack).
... return value a ctype object describing the newly created struct data type.
Plug-in Side Plug-in API - Plugins
npp_new creates a new instance of a plug-in.
... npp_setwindow tells the plug-in when a window is created, moved, sized, or destroyed.
Scripting plugins - Plugins
a plugin that wishes to be scriptable using this new mechanism needs to return the appropriate npobject (which is created by calling npn_createobject) when the browser requests it by calling: npp_getvalue(npp, nppvpluginscriptablenpobject, ...); accessing browser objects from a plugin a plugin that wishes to access objects in the browser window that loaded the plugin can do this by getting the npobject for the browser's window object, or the dom element that loaded the plugin.
... embed.nativeproperty.anothernativemethod(); </script> the api extensions the api extensions are based on four new structs: npstring npvariant npn_releasevariantvalue npn_getstringidentifier npn_getstringidentifiers npn_getintidentifier npn_identifierisstring npn_utf8fromidentifier npn_intfromidentifier npobject npn_construct (since firefox 3.0b1) npn_createobject npn_retainobject npn_releaseobject npn_invoke npn_invokedefault npn_enumerate (since mozilla 1.9a1) npn_evaluate npn_getproperty npn_setproperty npn_removeproperty npn_hasproperty npn_hasmethod npn_setexception npclass « previousnext » ...
Set a logpoint - Firefox Developer Tools
to create a logpoint: right click on a line number in the debugger panel and pick add log action from the context menu.
... create an expression inline.
Tutorial: Set a breakpoint - Firefox Developer Tools
adddebuggertoglobal(this); // create a 'debugger' instance.
...re-running the code in the scratchpad creates a fresh debugger instance, adds the same web page as its debuggee, and then sets a new breakpoint.
DOM allocation example - Firefox Developer Tools
it just contains a script that creates a large number of dom nodes: var toolbarbuttoncount = 20; var toolbarcount = 200; function getrandomint(min, max) { return math.floor(math.random() * (max - min + 1)) + min; } function createtoolbarbutton() { var toolbarbutton = document.createelement("span"); toolbarbutton.classlist.add("toolbarbutton"); // stop spidermonkey from sharing instances toolbarbutton[getrandomint(0,5000)] = "foo"; return toolbarbutton; } function createtoolbar() { var toolbar = document.createelement("div"); // stop spidermonkey from sharing insta...
...nces toolbar[getrandomint(0,5000)] = "foo"; for (var i = 0; i < toolbarbuttoncount; i++) { var toolbarbutton = createtoolbarbutton(); toolbar.appendchild(toolbarbutton); } return toolbar; } function createtoolbars() { var container = document.getelementbyid("container"); for (var i = 0; i < toolbarcount; i++) { var toolbar = createtoolbar(); container.appendchild(toolbar); } } createtoolbars(); a simple pseudocode representation of how this code operates looks like this: createtoolbars() -> createtoolbar() // called 200 times, creates 1 div element each time -> createtoolbarbutton() // called 20 times per toolbar, creates 1 span element each time in total, then, it creates 200 htmldivelement objects, and 4000 htmlspanelement objects.
Network request list - Firefox Developer Tools
copy > copy all as har creates an http archive (har) for all requests listed, and copies it to the clipboard.
... save all as har creates an http archive (har) for all requests listed, and opens a file dialog, so you can save it to a file.
Work with animations - Firefox Developer Tools
it displays animations created using css transitions, css @keyframes rules, or the web animations api.
...in this case, the message is "animations of 'transform' cannot be run on the compositor when geometric properties are animated on the same element at the same time." edit @keyframes any @keyframes rules associated with the currently selected element are displayed in the rules view and are editable: edit timing functions when you create a css animation you can specify a timing function: this determines the rate at which the animation progresses.
Animating CSS properties - Firefox Developer Tools
the browser creates the animation as a transition from each keyframe to the next.
... compared with animating elements using javascript, css animations can be easier to create.
Performance - Firefox Developer Tools
with the performance tool you create a recording, or profile, of your site over a period of time.
... how to basic tasks: open the tool, create, save, load, and configure recordings components of the performance tool frame rate understand your site's overall responsiveness.
Responsive Design Mode - Firefox Developer Tools
dpr (pixel ratio) - beginning with firefox 68, the dpr is no longer editable; create a custom device in order to change the dpr throttling - a drop-down list where you can select the connection throttling to apply, for example 2g, 3g, or lte enable/disable touch simulation - toggles whether or not responsive design mode simulates touch events.
... creating custom devices you can create and save custom devices in responsive design mode by clicking the add custom device button.
Taking screenshots - Firefox Developer Tools
type :screenshot in the web console to create a screenshot of the current page.
...values above 1 yield "zoomed-in" images, whereas values below 1 create "zoomed-out" images.
Tips - Firefox Developer Tools
right-click a node in the inspector and click "use in console" to create a tempn variable for it.
... click the import button () to import a style sheet or the create button () to create a new one.
Console messages - Firefox Developer Tools
the server-side library creates json objects from the messages and encodes them for transmission.
... store as global variable creates a global variable (with a name like temp0, temp1, etc.) whose value is the selected object.
Web Console remoting - Firefox Developer Tools
we change the arguments array - we create objectactor instances for each object passed as an argument - and, lastly, we remove some unneeded properties (like window ids).
...for each request a new networkeventactor instance is created.
AbortController.AbortController() - Web APIs
the abortcontroller() constructor creates a new abortcontroller object instance.
... we first create a controller using the abortcontroller() constructor, then grab a reference to its associated abortsignal object using the abortcontroller.signal property.
AnalyserNode.fftSize - Web APIs
example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input.
... var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); ...
AnalyserNode.frequencyBinCount - Web APIs
example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input.
... var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); analyser.mindecibels = -90; analyser.maxdecibels = -10; ...
AnalyserNode.maxDecibels - Web APIs
example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input.
... var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); analyser.mindecibels = -90; analyser.maxdecibels = -10; ...
AnalyserNode.minDecibels - Web APIs
example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input.
... var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); analyser.mindecibels = -90; analyser.maxdecibels = -10; ...
AnalyserNode.smoothingTimeConstant - Web APIs
example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input.
... var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); analyser.mindecibels = -90; analyser.maxdecibels = -10; analyser.smoothingtimeconstant = 0.85; ...
AnimationEvent - Web APIs
target="_top"><rect x="116" y="1" width="140" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="186" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">animationevent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor animationevent() creates an animationevent event with the given parameters.
... animationevent.initanimationevent() initializes a animationevent created using the deprecated document.createevent("animationevent") method.
Attr - Web APIs
WebAPIAttr
createattribute() use element.setattribute() instead.
... createattributens() use element.setattributens() instead.
AudioBuffer.copyFromChannel() - Web APIs
example this example creates a new audio buffer, then copies the samples from another channel into it.
... var myarraybuffer = audioctx.createbuffer(2, framecount, audioctx.samplerate); var anotherarray = new float32array(length); myarraybuffer.copyfromchannel(anotherarray, 1, 0); specification specification status comment web audio apithe definition of 'copyfromchannel' in that specification.
AudioBuffer.duration - Web APIs
syntax var myarraybuffer = audioctx.createbuffer(2, framecount, audioctx.samplerate); myarraybuffer.duration; value a double.
... example // stereo var channels = 2; // create an empty two second stereo buffer at the // sample rate of the audiocontext var framecount = audioctx.samplerate * 2.0; var myarraybuffer = audioctx.createbuffer(2, framecount, audioctx.samplerate); button.onclick = function() { // fill the buffer with white noise; // just random values between -1.0 and 1.0 for (var channel = 0; channel < channels; channel++) { // this gives us the actual arraybuffer that contains the data var nowbuffering = myarraybuffer.getchanneldata(channel); for (var i = 0; i < framecount; i++) { // math.random() is in [0; 1.0] // audio needs to be in [-1.0; 1.0] nowbuffering[i] = math.random() * 2 - 1; } } console.log(myarraybuffer.duration); } specification specific...
AudioBuffer.length - Web APIs
syntax var myarraybuffer = audioctx.createbuffer(2, framecount, audioctx.samplerate); myarraybuffer.length; value an integer.
... example // stereo var channels = 2; // create an empty two second stereo buffer at the // sample rate of the audiocontext var framecount = audioctx.samplerate * 2.0; var myarraybuffer = audioctx.createbuffer(2, framecount, audioctx.samplerate); button.onclick = function() { // fill the buffer with white noise; // just random values between -1.0 and 1.0 for (var channel = 0; channel < channels; channel++) { // this gives us the actual arraybuffer that contains the data var nowbuffering = myarraybuffer.getchanneldata(channel); for (var i = 0; i < framecount; i++) { // math.random() is in [0; 1.0] // audio needs to be in [-1.0; 1.0] nowbuffering[i] = math.random() * 2 - 1; } } console.log(myarraybuffer.length); } specification specificati...
AudioBuffer.numberOfChannels - Web APIs
syntax var myarraybuffer = audioctx.createbuffer(2, framecount, audioctx.samplerate); myarraybuffer.numberofchannels; value an integer.
... example // stereo var channels = 2; // create an empty two second stereo buffer at the // sample rate of the audiocontext var framecount = audioctx.samplerate * 2.0; var myarraybuffer = audioctx.createbuffer(2, framecount, audioctx.samplerate); button.onclick = function() { // fill the buffer with white noise; // just random values between -1.0 and 1.0 for (var channel = 0; channel < channels; channel++) { // this gives us the actual arraybuffer that contains the data var nowbuffering = myarraybuffer.getchanneldata(channel); for (var i = 0; i < framecount; i++) { // math.random() is in [0; 1.0] // audio needs to be in [-1.0; 1.0] nowbuffering[i] = math.random() * 2 - 1; } } console.log(myarraybuffer.numberofchannels); } specification s...
AudioBuffer.sampleRate - Web APIs
syntax var myarraybuffer = audioctx.createbuffer(2, framecount, audioctx.samplerate); myarraybuffer.samplerate; value a floating-point value indicating the current sample rate of the buffers data, in samples per second.
... example // stereo var channels = 2; // create an empty two second stereo buffer at the // sample rate of the audiocontext var framecount = audioctx.samplerate * 2.0; var myarraybuffer = audioctx.createbuffer(2, framecount, audioctx.samplerate); button.onclick = function() { // fill the buffer with white noise; // just random values between -1.0 and 1.0 for (var channel = 0; channel < channels; channel++) { // this gives us the actual arraybuffer that contains the data var nowbuffering = myarraybuffer.getchanneldata(channel); for (var i = 0; i < framecount; i++) { // math.random() is in [0; 1.0] // audio needs to be in [-1.0; 1.0] nowbuffering[i] = math.random() * 2 - 1; } } console.log(myarraybuffer.samplerate); } specification specifi...
AudioBufferSourceNode.buffer - Web APIs
var myarraybuffer = audioctx.createbuffer(2, framecount, audioctx.samplerate); button.onclick = function() { // fill the buffer with white noise; //just random values between -1.0 and 1.0 for (var channel = 0; channel < channels; channel++) { // this gives us the actual arraybuffer that contains the data var nowbuffering = myarraybuffer.getchanneldata(channel); for (var i = 0; i < framecount; i++) { // math.ran...
... // this is the audionode to use when we want to play an audiobuffer var source = audioctx.createbuffersource(); // set the buffer in the audiobuffersourcenode source.buffer = myarraybuffer; specifications specification status comment web audio apithe definition of 'buffer' in that specification.
AudioBufferSourceNode.detune - Web APIs
syntax var source = audioctx.createbuffersource(); source.detune.value = 100; // value in cents note: though the audioparam returned is read-only, the value it represents is not.
... example const audioctx = new audiocontext(); const channelcount = 2; const framecount = audioctx.samplerate * 2.0; // 2 seconds const myarraybuffer = audioctx.createbuffer(channelcount, framecount, audioctx.samplerate); for (let channel = 0; channel < channelcount; channel++) { const nowbuffering = myarraybuffer.getchanneldata(channel); for (let i = 0; i < framecount; i++) { nowbuffering[i] = math.random() * 2 - 1; } } const source = audioctx.createbuffersource(); source.buffer = myarraybuffer; source.connect(audioctx.destination); source.detune.value = 100; // value in cents source.start(); specifications specification status comment web audio apithe definition of...
AudioContext() - Web APIs
the audiocontext() constructor creates a new audiocontext object which represents an audio-processing graph, built from audio modules linked together, each represented by an audionode.
... example this example creates a new audiocontext for interactive audio (optimizing for latency) and a sample rate of 44.1khz.
AudioContext.close() - Web APIs
closed contexts cannot have new nodes created, but can decode audio data, create buffers, etc.
... this function does not automatically release all audiocontext-created objects, unless other references have been released as well; however, it will forcibly release any system audio resources that might prevent additional audiocontexts from being created and used, suspend the progression of audio time in the audio context, and stop processing audio data.
AudioContext.getOutputTimestamp() - Web APIs
basically, this is the time after the audio context was first created.
... contexttime: a point in the time coordinate system of the currenttime for the baseaudiocontext; the time after the audio context was first created.
AudioListener.dopplerFactor - Web APIs
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
... // set up listener and panner position information var width = window.innerwidth; var height = window.innerheight; var xpos = math.floor(width/2); var ypos = math.floor(height/2); var zpos = 295; // define other variables var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.panningmodel = 'hrtf'; panner.distancemodel = 'inverse'; panner.refdistance = 1; panner.maxdistance = 10000; panner.rollofffactor = 1; panner.coneinnerangle = 360; panner.coneouterangle = 0; panner.coneoutergain = 0; if(panner.orientationx) { panner.orientationx.setvalueattime(1, audioctx.currenttime); panner.orientationy.setvalueattime(0, audioctx.currenttime); panner.orie...
AudioListener.forwardX - Web APIs
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
... // set up listener and panner position information var width = window.innerwidth; var height = window.innerheight; var xpos = math.floor(width/2); var ypos = math.floor(height/2); var zpos = 295; // define other variables var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.panningmodel = 'hrtf'; panner.distancemodel = 'inverse'; panner.refdistance = 1; panner.maxdistance = 10000; panner.rollofffactor = 1; panner.coneinnerangle = 360; panner.coneouterangle = 0; panner.coneoutergain = 0; if(panner.orientationx) { panner.orientationx.setvalueattime(1, audioctx.currenttime); panner.orientationy.setvalueattime(0, audioctx.currenttime); panner.orie...
AudioListener.forwardY - Web APIs
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
... // set up listener and panner position information var width = window.innerwidth; var height = window.innerheight; var xpos = math.floor(width/2); var ypos = math.floor(height/2); var zpos = 295; // define other variables var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.panningmodel = 'hrtf'; panner.distancemodel = 'inverse'; panner.refdistance = 1; panner.maxdistance = 10000; panner.rollofffactor = 1; panner.coneinnerangle = 360; panner.coneouterangle = 0; panner.coneoutergain = 0; if(panner.orientationx) { panner.orientationx.setvalueattime(1, audioctx.currenttime); panner.orientationy.setvalueattime(0, audioctx.currenttime); panner.orie...
AudioListener.forwardZ - Web APIs
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
... // set up listener and panner position information var width = window.innerwidth; var height = window.innerheight; var xpos = math.floor(width/2); var ypos = math.floor(height/2); var zpos = 295; // define other variables var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.panningmodel = 'hrtf'; panner.distancemodel = 'inverse'; panner.refdistance = 1; panner.maxdistance = 10000; panner.rollofffactor = 1; panner.coneinnerangle = 360; panner.coneouterangle = 0; panner.coneoutergain = 0; if(panner.orientationx) { panner.orientationx.setvalueattime(1, audioctx.currenttime); panner.orientationy.setvalueattime(0, audioctx.currenttime); panner.orie...
AudioListener.positionX - Web APIs
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
... // set up listener and panner position information var width = window.innerwidth; var height = window.innerheight; var xpos = math.floor(width/2); var ypos = math.floor(height/2); var zpos = 295; // define other variables var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.panningmodel = 'hrtf'; panner.distancemodel = 'inverse'; panner.refdistance = 1; panner.maxdistance = 10000; panner.rollofffactor = 1; panner.coneinnerangle = 360; panner.coneouterangle = 0; panner.coneoutergain = 0; if(panner.orientationx) { panner.orientationx.setvalueattime(1, audioctx.currenttime); panner.orientationy.setvalueattime(0, audioctx.currenttime); panner.orie...
AudioListener.positionY - Web APIs
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
... // set up listener and panner position information var width = window.innerwidth; var height = window.innerheight; var xpos = math.floor(width/2); var ypos = math.floor(height/2); var zpos = 295; // define other variables var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.panningmodel = 'hrtf'; panner.distancemodel = 'inverse'; panner.refdistance = 1; panner.maxdistance = 10000; panner.rollofffactor = 1; panner.coneinnerangle = 360; panner.coneouterangle = 0; panner.coneoutergain = 0; if(panner.orientationx) { panner.orientationx.setvalueattime(1, audioctx.currenttime); panner.orientationy.setvalueattime(0, audioctx.currenttime); panner.orie...
AudioListener.positionZ - Web APIs
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
... // set up listener and panner position information var width = window.innerwidth; var height = window.innerheight; var xpos = math.floor(width/2); var ypos = math.floor(height/2); var zpos = 295; // define other variables var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.panningmodel = 'hrtf'; panner.distancemodel = 'inverse'; panner.refdistance = 1; panner.maxdistance = 10000; panner.rollofffactor = 1; panner.coneinnerangle = 360; panner.coneouterangle = 0; panner.coneoutergain = 0; if(panner.orientationx) { panner.orientationx.setvalueattime(1, audioctx.currenttime); panner.orientationy.setvalueattime(0, audioctx.currenttime); panner.orie...
AudioListener.setOrientation() - Web APIs
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
... // set up listener and panner position information var width = window.innerwidth; var height = window.innerheight; var xpos = math.floor(width/2); var ypos = math.floor(height/2); var zpos = 295; // define other variables var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.panningmodel = 'hrtf'; panner.distancemodel = 'inverse'; panner.refdistance = 1; panner.maxdistance = 10000; panner.rollofffactor = 1; panner.coneinnerangle = 360; panner.coneouterangle = 0; panner.coneoutergain = 0; if(panner.orientationx) { panner.orientationx.setvalueattime(1, audioctx.currenttime); panner.orientationy.setvalueattime(0, audioctx.currenttime); panner.orie...
AudioListener.setPosition() - Web APIs
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
... // set up listener and panner position information var width = window.innerwidth; var height = window.innerheight; var xpos = math.floor(width/2); var ypos = math.floor(height/2); var zpos = 295; // define other variables var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.panningmodel = 'hrtf'; panner.distancemodel = 'inverse'; panner.refdistance = 1; panner.maxdistance = 10000; panner.rollofffactor = 1; panner.coneinnerangle = 360; panner.coneouterangle = 0; panner.coneoutergain = 0; if(panner.orientationx) { panner.orientationx.setvalueattime(1, audioctx.currenttime); panner.orientationy.setvalueattime(0, audioctx.currenttime); panner.orie...
AudioListener.speedOfSound - Web APIs
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
... // set up listener and panner position information var width = window.innerwidth; var height = window.innerheight; var xpos = math.floor(width/2); var ypos = math.floor(height/2); var zpos = 295; // define other variables var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.panningmodel = 'hrtf'; panner.distancemodel = 'inverse'; panner.refdistance = 1; panner.maxdistance = 10000; panner.rollofffactor = 1; panner.coneinnerangle = 360; panner.coneouterangle = 0; panner.coneoutergain = 0; if(panner.orientationx) { panner.orientationx.setvalueattime(1, audioctx.currenttime); panner.orientationy.setvalueattime(0, audioctx.currenttime); panner.orie...
AudioListener.upX - Web APIs
WebAPIAudioListenerupX
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
... // set up listener and panner position information var width = window.innerwidth; var height = window.innerheight; var xpos = math.floor(width/2); var ypos = math.floor(height/2); var zpos = 295; // define other variables var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.panningmodel = 'hrtf'; panner.distancemodel = 'inverse'; panner.refdistance = 1; panner.maxdistance = 10000; panner.rollofffactor = 1; panner.coneinnerangle = 360; panner.coneouterangle = 0; panner.coneoutergain = 0; if(panner.orientationx) { panner.orientationx.setvalueattime(1, audioctx.currenttime); panner.orientationy.setvalueattime(0, audioctx.currenttime); panner.orie...
AudioListener.upY - Web APIs
WebAPIAudioListenerupY
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
... // set up listener and panner position information var width = window.innerwidth; var height = window.innerheight; var xpos = math.floor(width/2); var ypos = math.floor(height/2); var zpos = 295; // define other variables var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.panningmodel = 'hrtf'; panner.distancemodel = 'inverse'; panner.refdistance = 1; panner.maxdistance = 10000; panner.rollofffactor = 1; panner.coneinnerangle = 360; panner.coneouterangle = 0; panner.coneoutergain = 0; if(panner.orientationx) { panner.orientationx.setvalueattime(1, audioctx.currenttime); panner.orientationy.setvalueattime(0, audioctx.currenttime); panner.orie...
AudioListener.upZ - Web APIs
WebAPIAudioListenerupZ
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
... // set up listener and panner position information var width = window.innerwidth; var height = window.innerheight; var xpos = math.floor(width/2); var ypos = math.floor(height/2); var zpos = 295; // define other variables var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.panningmodel = 'hrtf'; panner.distancemodel = 'inverse'; panner.refdistance = 1; panner.maxdistance = 10000; panner.rollofffactor = 1; panner.coneinnerangle = 360; panner.coneouterangle = 0; panner.coneoutergain = 0; if(panner.orientationx) { panner.orientationx.setvalueattime(1, audioctx.currenttime); panner.orientationy.setvalueattime(0, audioctx.currenttime); panner.orie...
AudioListener - Web APIs
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
... // set up listener and panner position information var width = window.innerwidth; var height = window.innerheight; var xpos = math.floor(width/2); var ypos = math.floor(height/2); var zpos = 295; // define other variables var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.panningmodel = 'hrtf'; panner.distancemodel = 'inverse'; panner.refdistance = 1; panner.maxdistance = 10000; panner.rollofffactor = 1; panner.coneinnerangle = 360; panner.coneouterangle = 0; panner.coneoutergain = 0; if(panner.orientationx) { panner.orientationx.setvalueattime(1, audioctx.currenttime); panner.orientationy.setvalueattime(0, audioctx.currenttime); panner.orie...
AudioNode.channelCount - Web APIs
syntax var oscillator = audioctx.createoscillator(); var channels = oscillator.channelcount; value an integer.
... example var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var oscillator = audioctx.createoscillator(); var gainnode = audioctx.creategain(); oscillator.connect(gainnode); gainnode.connect(audioctx.destination); oscillator.channelcount; specifications specification status comment web audio apithe definition of 'channelcount' in that specification.
AudioNode.channelCountMode - Web APIs
syntax var oscillator = audioctx.createoscillator(); oscillator.channelcountmode = 'explicit'; value a enumerated value representing a channelcountmode.
... example var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var oscillator = audioctx.createoscillator(); var gainnode = audioctx.creategain(); oscillator.connect(gainnode); gainnode.connect(audioctx.destination); oscillator.channelcountmode = 'explicit'; specifications specification status comment web audio apithe definition of 'channelcountmode' in that specification.
AudioNode.channelInterpretation - Web APIs
syntax var oscillator = audioctx.createoscillator(); oscillator.channelinterpretation = 'discrete'; value an enumerated value representing a channelinterpretation.
... example var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var oscillator = audioctx.createoscillator(); var gainnode = audioctx.creategain(); oscillator.connect(gainnode); gainnode.connect(audioctx.destination); oscillator.channelinterpretation = 'discrete'; specifications specification status comment web audio apithe definition of 'channelinterpretation' in that specification.
AudioNode - Web APIs
WebAPIAudioNode
creating an audionode there are two ways to create an audionode: via the constuctor and via the factory method.
... // constructor const analysernode = new analysernode(audioctx, { fftsize: 2048, maxdecibels: -25, mindecibels: -60, smoothingtimeconstant: 0.5, }); // factory method const analysernode = audioctx.createanalyser(); analysernode.fftsize = 2048; analysernode.maxdecibels = -25; analysernode.mindecibels = -60; analysernode.smoothingtimeconstant = 0.5; you are free to use either constructors or factory methods, or mix both, however there are advantages to using the constructors: all parameters can be set during construction time and don't need to be set individually.
AudioParam.cancelScheduledValues() - Web APIs
syntax var audioparam = audioparam.cancelscheduledvalues(starttime) parameters starttime a double representing the time (in seconds) after the audiocontext was first created after which all scheduled changes will be cancelled.
... examples var gainnode = audioctx.creategain(); gainnode.gain.setvaluecurveattime(wavearray, audioctx.currenttime, 2); //'gain' is the audioparam gainnode.gain.cancelscheduledvalues(audioctx.currenttime); specifications specification status comment web audio apithe definition of 'cancelscheduledvalues' in that specification.
AudioParam.exponentialRampToValueAtTime() - Web APIs
this is pretty useful for fade in/fade out effects: // create audio context var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); // set basic variables for example var myaudio = document.queryselector('audio'); var pre = document.queryselector('pre'); var myscript = document.queryselector('script'); pre.innerhtml = myscript.innerhtml; var exprampplus = document.queryselector('.exp-ramp-plus'); var expram...
...pminus = document.queryselector('.exp-ramp-minus'); // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a gain node and set its gain value to 0.5 var gainnode = audioctx.creategain(); // connect the audiobuffersourcenode to the gainnode // and the gainnode to the destination gainnode.gain.setvalueattime(0, audioctx.currenttime); source.connect(gainnode); gainnode.connect(audioctx.destination); // set buttons to do something onclick exprampplus.onclick = function() { gainnode.gain.exponentialramptovalueattime(1.0, audioctx.currenttime + 2); } exprampminus.onclick = function() { gainnode.gain.exponentialramptovalueattime(0.01, audioctx.currenttime + 2); } note: a value of 0.01 was used for the v...
AudioParam.linearRampToValueAtTime() - Web APIs
// create audio context var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); // set basic variables for example var myaudio = document.queryselector('audio'); var pre = document.queryselector('pre'); var myscript = document.queryselector('script'); pre.innerhtml = myscript.innerhtml; var linearrampplus = document.queryselector('.linear-ramp-plus'); var ...
...linearrampminus = document.queryselector('.linear-ramp-minus'); // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a gain node and set it's gain value to 0.5 var gainnode = audioctx.creategain(); // connect the audiobuffersourcenode to the gainnode // and the gainnode to the destination gainnode.gain.setvalueattime(0, audioctx.currenttime); source.connect(gainnode); gainnode.connect(audioctx.destination); // set buttons to do something onclick linearrampplus.onclick = function() { gainnode.gain.linearramptovalueattime(1.0, audioctx.currenttime + 2); } linearrampminus.onclick = function() { gainnode.gain.linearramptovalueattime(0, audioctx.currenttime + 2); } specifications specifi...
AudioParam.setTargetAtTime() - Web APIs
// create audio context var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); // set basic variables for example var myaudio = document.queryselector('audio'); var pre = document.queryselector('pre'); var myscript = document.queryselector('script'); pre.innerhtml = myscript.innerhtml; var attimeplus = document.queryselector('.at-time-plus'); var attimemi...
...nus = document.queryselector('.at-time-minus'); // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a gain node and set it's gain value to 0.5 var gainnode = audioctx.creategain(); gainnode.gain.value = 0.5; var currgain = gainnode.gain.value; // connect the audiobuffersourcenode to the gainnode // and the gainnode to the destination source.connect(gainnode); gainnode.connect(audioctx.destination); // set buttons to do something onclick attimeplus.onclick = function() { currgain = 1.0; gainnode.gain.settargetattime(1.0, audioctx.currenttime + 1, 0.5); } attimeminus.onclick = function() { currgain = 0; gainnode.gain.settargetattime(0, audioctx.currenttime + 1, 0.5); } specifications ...
AudioParam - Web APIs
var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var gainnode = audioctx.creategain(); gainnode.gain.value = 0; next, an example showing a dynamicscompressornode having some param values maniuplated.
... var compressor = audioctx.createdynamicscompressor(); compressor.threshold.setvalueattime(-50, audioctx.currenttime); compressor.knee.setvalueattime(40, audioctx.currenttime); compressor.ratio.setvalueattime(12, audioctx.currenttime); compressor.attack.setvalueattime(0, audioctx.currenttime); compressor.release.setvalueattime(0.25, audioctx.currenttime); specifications specification status comment web audio apithe definition of 'audioparam' in that specification.
AudioScheduledSourceNode.start() - Web APIs
example this example demonstrates how to create an oscillatornode which is scheduled to start playing in 2 seconds and stop playing 1 second after that.
... context = new audiocontext(); osc = context.createoscillator(); osc.connect(context.destination); /* schedule the start and stop times for the oscillator */ osc.start(context.currenttime + 2); osc.stop(context.currenttime + 3); specifications specification status comment web audio apithe definition of 'start()' in that specification.
AudioTrack - Web APIs
sourcebuffer read only the sourcebuffer that created the track.
... returns null if the track was not created by a sourcebuffer or the sourcebuffer has been removed from the mediasource.sourcebuffers attribute of its parent media source.
AudioWorkletNode.port - Web APIs
examples to demonstrate bidirectional communication capabilities, we'll create an audioworkletprocessor, which will output silence and respond to ping requests from its audioworkletnode.
...cessor.js class pingpongprocessor extends audioworkletprocessor { constructor (...args) { super(...args) this.port.onmessage = (e) => { console.log(e.data) this.port.postmessage('pong') } } process (inputs, outputs, parameters) { return true } } registerprocessor('ping-pong-processor', pingpongprocessor) now in our main scripts file we'll load the processor, create an instance of audioworkletnode passing the name of the processor, and connect the node to an audio graph.
AudioWorkletProcessor.port - Web APIs
examples to demonstrate bidirectional communication capabilities, we'll create an audioworkletprocessor, which will output silence and respond to ping requests from its audioworkletnode.
...cessor.js class pingpongprocessor extends audioworkletprocessor { constructor (...args) { super(...args) this.port.onmessage = (e) => { console.log(e.data) this.port.postmessage('pong') } } process (inputs, outputs, parameters) { return true } } registerprocessor('ping-pong-processor', pingpongprocessor) now in our main scripts file we'll load the processor, create an instance of audioworkletnode passing the name of the processor, and connect the node to an audio graph.
AuthenticatorAssertionResponse.authenticatorData - Web APIs
attestedcredentialdata (variable length) - the credential that was created.
... this is only present during a navigator.credentials.create() call.
AuthenticatorAttestationResponse.getTransports() - Web APIs
note: an authenticatorattestationresponse instance is available on publickeycredential.response after calling navigator.credentials.create().
... examples var publickey = { challenge: /* from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(16), name: "jdoe@example.com", displayname: "john doe" }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { var transports = newcredentialinfo.response.gettransports(); console.table(transports); // may be something like ["internal", "nfc", "usb"] }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials ...
AuthenticatorResponse - Web APIs
authenticatorassertionresponse authenticatorattestationresponse properties authenticatorresponse.clientdatajson a json string in an arraybuffer, representing the client data that was passed to credentialscontainer.create() or credentialscontainer.get().
...console.error(err); }); getting an authenticatorattestationresponse var publickey = { challenge: /* from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(16), name: "jdoe@example.com", displayname: "john doe" }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { var attestationresponse = newcredentialinfo.response; }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the definition of 'authenticatorresponse interface' in that specification.
BaseAudioContext.decodeAudioData() - Web APIs
we then pass this buffer into a decodeaudiodata() function; the success callback takes the successfully decoded pcm data, puts it into an audiobuffersourcenode created using audiocontext.createbuffersource(), connects the source to the audiocontext.destination and sets it to loop.
...// then we put the buffer into the source function getdata() { source = audioctx.createbuffersource(); var request = new xmlhttprequest(); request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { source.buffer = buffer; source.connect(audioctx.destination); source.loop = true; }, functio...
Using the Beacon API - Web APIs
window.onload = window.onunload = function analytics(event) { if (!navigator.sendbeacon) return; var url = "https://example.com/analytics"; // create the data to send var data = "state=" + event.type + "&location=" + location.href; // send the beacon var status = navigator.sendbeacon(url, data); // log the data and result console.log("sendbeacon: url = ", url, "; data = ", data, "; status = ", status); }; the following example creates a submit handler and when that event is fired, the handler calls sendbeacon().
... this code snippet is for the global context: function worker_send(url, data) { // create the worker object var myworker = new worker("worker-using.js"); // send the worker the url and data to beacon myworker.postmessage([url, data]); // set up a message handler to receive the success/fail message from the worker myworker.onmessage = function(event) { var msg = event.data; // log worker's send status console.log("worker reply: sendbeacon() status = " + msg); ...
BlobBuilder - Web APIs
just create a blobbuilder and append chunks of data to it by calling the append() method.
... return value a blob object containing all of the data passed to any calls to append() made since the blobbuilder was created.
Body.body - Web APIs
WebAPIBodybody
example in our simple stream pump example we fetch an image, expose the response's stream using response.body, create a reader using readablestream.getreader(), then enqueue that stream's chunks into a second, custom readable stream — effectively creating an identical copy of the image.
... // when no more data needs to be consumed, close the stream if (done) { controller.close(); return; } // enqueue the next data chunk into our target stream controller.enqueue(value); return pump(); }); } } }) }) .then(stream => new response(stream)) .then(response => response.blob()) .then(blob => url.createobjecturl(blob)) .then(url => console.log(image.src = url)) .catch(err => console.error(err)); specifications specification status comment fetchthe definition of 'body' in that specification.
BroadcastChannel() - Web APIs
the broadcastchannel() constructor creates a new broadcastchannel and connects it to the underlying channel.
... example // create a new channel listening to the "internal_notification" channel.
Broadcast Channel API - Web APIs
if it is the first to connect to that broadcast channel name, the underlying channel is created.
... // connection to a broadcast channel const bc = new broadcastchannel('test_channel'); sending a message it is enough to call the postmessage() method on the created broadcastchannel object, which takes any object as an argument.
CSS numeric factory functions - Web APIs
these functions create new numeric values less verbosely than using the cssunitvalue.cssunitvalue() constructor.
...er); css.in(number); css.pt(number); css.pc(number); css.px(number); // <angle> css.deg(number); css.grad(number); css.rad(number); css.turn(number); // <time> css.s(number); css.ms(number); // <frequency> css.hz(number); css.khz(number); // <resolution> css.dpi(number); css.dpcm(number); css.dppx(number); // <flex> css.fr(number); examples we use the css.vmax() numeric factory function to create a cssunitvalue: let height = css.vmax(50); console.log( height ); // cssunitvalue {value: 50, unit: "vmax"} console.log( height.value ) // 50 console.log( height.unit ) // vmax in this example, we set the margin on our element using the css.px() factory function: myelement.attributestylemap.set('margin', css.px(40)); let currentmargin = myelement.attributestylemap.get('margin'); cons...
CSS - Web APIs
WebAPICSS
properties the css interface is a utility interface and no object of this type can be created: only static properties are defined on it.
... methods the css interface is a utility interface and no object of this type can be created: only static methods are defined on it.
CSSKeywordValue - Web APIs
the csskeywordvalue interface of the the css typed object model api creates an object to represent css keywords and other identifiers.
... constructor csskeywordvalue.csskeywordvalue() creates a new csskeywordvalue object.
CSSVariableReferenceValue - Web APIs
the cssvariablereferencevalue interface of the css typed object model api allows you to create a custom name for a built-in css value.
... constructor cssvariablereferencevalue.cssvariablereferencevalue() creates a new cssvariablereferencevalue object.
Cache.addAll() - Web APIs
WebAPICacheaddAll
the request objects created during retrieval become keys to the stored response operations.
...this consists of calling cachestorage.open to create a new cache, then using addall() to add a series of assets to it.
CacheStorage.open() - Web APIs
WebAPICacheStorageopen
note: if the specified cache does not exist, a new cache is created with that cachename and a promise that resolves to this new cache object is returned.
...this consists of calling cachestorage.open() to create a new cache, then using cache.addall() to add a series of assets to it.
CanvasRenderingContext2D.ellipse() - Web APIs
syntax void ctx.ellipse(x, y, radiusx, radiusy, rotation, startangle, endangle [, anticlockwise]); the ellipse() method creates an elliptical arc centered at (x, y) with the radii radiusx and radiusy.
... javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // draw the ellipse ctx.beginpath(); ctx.ellipse(100, 100, 50, 75, math.pi / 4, 0, 2 * math.pi); ctx.stroke(); // draw the ellipse's line of reflection ctx.beginpath(); ctx.setlinedash([5, 5]); ctx.moveto(0, 200); ctx.lineto(200, 0); ctx.stroke(); result various elliptical arcs this example creates three elliptical paths with varying properties.
CanvasRenderingContext2D.putImageData() - Web APIs
) { for (var x = dirtyx; x < limitright; x++) { var pos = y * width + x; ctx.fillstyle = 'rgba(' + data[pos*4+0] + ',' + data[pos*4+1] + ',' + data[pos*4+2] + ',' + (data[pos*4+3]/255) + ')'; ctx.fillrect(x + dx, y + dy, 1, 1); } } } // draw content onto the canvas ctx.fillrect(0, 0, 100, 100); // create an imagedata object from it var imagedata = ctx.getimagedata(0, 0, 100, 100); // use the putimagedata function that illustrates how putimagedata works putimagedata(ctx, imagedata, 150, 0, 50, 50, 25, 25); result data loss due to browser optimization due to the lossy nature of converting to and from premultiplied alpha color values, pixels that have just been set using putimagedata() might...
... javascript const canvas = document.createelement("canvas"); canvas.width = 1; canvas.height = 1; const context = canvas.getcontext("2d"); const imgdata = context.getimagedata(0, 0, canvas.width, canvas.height); const pixels = imgdata.data; pixels[0 + 0] = 1; pixels[0 + 1] = 127; pixels[0 + 2] = 255; pixels[0 + 3] = 1; console.log("before:", pixels); context.putimagedata(imgdata, 0, 0); const imgdata2 = context.getimagedata(0, 0, canvas.width, canvas.height); const pixels2 = imgdata2.data; console.log("after:", pixels2); the output might look like: before: uint8clampedarray(4) [ 1, 127, 255, 1 ] after: uint8clampedarray(4) [ 255, 255, 255, 1 ] specifications specification status comment html living st...
Basic animations - Web APIs
w: this.w }, t)), this.sn.unshift(i), -1 != e) return console.log(e), fa[e].renew(), void (document.getelementbyid("score").innertext = number(document.getelementbyid("score").innertext) + 1); this.sn.pop(), console.log(6) } this.sn.foreach((t, e, i) => { if (0 == e || i.length - 1 == e) { var n = c.createlineargradient(t.x, t.y, t.x + this.w, t.y + this.h); i.length - 1 == e ?
... } function emit(t) { key.keydown(t) } function touch(t) { t.classlist.toggle("off"), document.getelementsbyclassname("keypress")[0].classlist.toggle("hide") } var t = new date + "", d = void 0, cc = document.getelementsbytagname("canvas")[0], c = cc.getcontext("2d"); key = {}, key.keydown = function (t) { var e = document.createevent("keyboardevent"); object.defineproperty(e, "keycode", { get: function () { return this.keycodeval } }), object.defineproperty(e, "key", { get: function () { return 37 == this.keycodeval ?
Compositing and clipping - Web APIs
function draw() { var ctx = document.getelementbyid('canvas').getcontext('2d'); ctx.fillrect(0, 0, 150, 150); ctx.translate(75, 75); // create a circular clipping path ctx.beginpath(); ctx.arc(0, 0, 60, 0, math.pi * 2, true); ctx.clip(); // draw background var lingrad = ctx.createlineargradient(0, -75, 0, 75); lingrad.addcolorstop(0, '#232256'); lingrad.addcolorstop(1, '#143778'); ctx.fillstyle = lingrad; ctx.fillrect(-75, -75, 150, 150); // draw stars for (var j = 1; j < 50; j++) { ctx.save(); ctx.fills...
...next, we create the circular clipping path by drawing an arc and calling clip().
Optimizing canvas - Web APIs
mycanvas.offscreencanvas = document.createelement('canvas'); mycanvas.offscreencanvas.width = mycanvas.width; mycanvas.offscreencanvas.height = mycanvas.height; mycanvas.getcontext('2d').drawimage(mycanvas.offscreencanvas, 0, 0); avoid floating-point coordinates and use integers instead sub-pixel rendering occurs when you render objects on a canvas without whole values.
... ctx.drawimage(myimage, 0.3, 0.5); this forces the browser to do extra calculations to create the anti-aliasing effect.
Using channel messaging - Web APIs
over in the iframe, we have the following javascript: var list = document.queryselector('ul'); var port2; // listen for the initial port transfer message window.addeventlistener('message', initport); // setup the transferred port function initport(e) { port2 = e.ports[0]; port2.onmessage = onmessage; } // handle messages received on port2 function onmessage(e) { var listitem = document.createelement('li'); listitem.textcontent = e.data; list.appendchild(listitem); port2.postmessage('message received by iframe: "' + e.data + '"'); } when the initial message is received from the main page via the window.postmessage method, we run the initport function.
... when a message is received from the main page we create a list item and insert it in the unordered list, setting the textcontent of the list item equal to the event's data attribute (this contains the actual message).
ChildNode.replaceWith() - Web APIs
examples using replacewith() var parent = document.createelement("div"); var child = document.createelement("p"); parent.appendchild(child); var span = document.createelement("span"); child.replacewith(span); console.log(parent.outerhtml); // "<div><span></span></div>" childnode.replacewith() is unscopable the replacewith() method is not scoped into the with statement.
... 'use-strict'; // for safari, and ie > 10 var parent = this.parentnode, i = arguments.length, currentnode; if (!parent) return; if (!i) // if there are no arguments parent.removechild(this); while (i--) { // i-- decrements i and returns the value of i before the decrement currentnode = arguments[i]; if (typeof currentnode !== 'object'){ currentnode = this.ownerdocument.createtextnode(currentnode); } else if (currentnode.parentnode){ currentnode.parentnode.removechild(currentnode); } // the value of "i" below is after the decrement if (!i) // if currentnode is the first argument (currentnode === arguments[0]) parent.replacechild(currentnode, this); else // if currentnode isn't the first parent.insertbefore(currentnode, this.nextsib...
ClipboardItem() - Web APIs
the clipboarditem() constructor of the clipboard api creates a new clipboarditem object which represents data to be stored or retrieved via the clipboard api, that is clipboard.write() and clipboard.read() respectively.
... examples the below example requests a png image using the fetch api, and in turn, the responses' blob() method, to create a new clipboarditem and write it to the clipboard, using the clipboard api.
ClipboardItem - Web APIs
constructor clipboarditem.clipboarditem() creates a new clipboarditem object, with the mime type as the key and blob as the value properties this interface provides the following properties.
... examples writing to clipboard here we're writing a new clipboarditem.clipboarditem() to the clipboard by requesting a png image using the fetch api, and in turn, the responses' blob() method, to create the new clipboarditem.
CloseEvent.initCloseEvent() - Web APIs
the closeevent.initcloseevent() method initializes the value of a close event once it's been created (normally using the document.createevent() method).
... events initialized in this way must have been created with the document.createevent() method.
Comment() - Web APIs
WebAPICommentComment
the comment() constructor returns a newly created comment object with the optional domstring given in parameter as its textual content.
... syntax comment1 = new comment(); // create an empty comment comment2 = new comment("this is a comment"); example var comment = new comment("test"); specifications specification status comment domthe definition of 'comment: comment' in that specification.
Console.group() - Web APIs
WebAPIConsolegroup
creates a new inline group in the web console log.
...to create a new nested block, call console.group().
ConstantSourceNode.offset - Web APIs
gainnode2 = context.creategain(); gainnode3 = context.creategain(); gainnode2.gain.value = gainnode3.gain.value = 0.5; volumeslidercontrol.value = gainnode2.gain.value; constantsource = context.createconstantsource(); constantsource.connect(gainnode2.gain); constantsource.connect(gainnode3.gain); first, the gain nodes are created and configured, and a slider control's value is set to match the gain on the two nodes.
... then we create a new constantsourcenode and make it the source for the two gain nodes' gainnode.gain values.
ContentIndex.getAll() - Web APIs
async function createreadinglist() { // access our service worker registration const registration = await navigator.serviceworker.ready; // get our index entries const entries = await registration.index.getall(); // create a containing element const readinglistelem = document.createelement('div'); // test for entries if (!array.length) { // if there are no entries, display a message const m...
...essage = document.createelement('p'); message.innertext = 'you currently have no articles saved for offline reading.' readinglistelem.append(message); } else { // if entries are present, display in a list of links to the content const listelem = document.createelement('ul'); for (const entry of entries) { const listitem = document.createelement('li'); const anchorelem = document.createelement('a'); anchorelem.innertext = entry.title; anchorelem.setattribute('href', entry.url); listelem.append(listitem); } readinglistelem.append(listelem); } } specifications specification status comment unknownthe definition of 'getall' in that specification.
ContentIndex - Web APIs
async function createreadinglist() { // access our service worker registration const registration = await navigator.serviceworker.ready; // get our index entries const entries = await registration.index.getall(); // create a containing element const readinglistelem = document.createelement('div'); // test for entries if (!array.length) { // if there are no entries, display a message const m...
...essage = document.createelement('p'); message.innertext = 'you currently have no articles saved for offline reading.' readinglistelem.append(message); } else { // if entries are present, display in a list of links to the content const listelem = document.createelement('ul'); for (const entry of entries) { const listitem = document.createelement('li'); const anchorelem = document.createelement('a'); anchorelem.innertext = entry.title; anchorelem.setattribute('href', entry.url); listelem.append(listitem); } readinglistelem.append(listelem); } } unregistering indexed content below is an asynchronous function, that removes an item from the content index.
Content Index API - Web APIs
async function createreadinglist() { // access our service worker registration const registration = await navigator.serviceworker.ready; // get our index entries const entries = await registration.index.getall(); // create a containing element const readinglistelem = document.createelement('div'); // test for entries if (!array.length) { // if there are no entries, display a message const m...
...essage = document.createelement('p'); message.innertext = 'you currently have no articles saved for offline reading.' readinglistelem.append(message); } else { // if entries are present, display in a list of links to the content const listelem = document.createelement('ul'); for (const entry of entries) { const listitem = document.createelement('li'); const anchorelem = document.createelement('a'); anchorelem.innertext = entry.title; anchorelem.setattribute('href', entry.url); listelem.append(listitem); } readinglistelem.append(listelem); } } unregistering indexed content below is an asynchronous function, that removes an item from the content index.
ConvolverNode() - Web APIs
the convolvernode() constructor of the web audio api creates a new convolvernode object instance.
... options optional options are as follows: audiobuffer: a mono, stereo, or 4-channel audiobuffer containing the (possibly multichannel) impulse response used by the convolvernode to create the reverb effect.
CustomElementRegistry - Web APIs
// create a class for the element class wordcount extends htmlparagraphelement { constructor() { // always call super first in constructor super(); // count words in element's parent element var wcparent = this.parentnode; function countwords(node){ var text = node.innertext || node.textcontent return text.split(/\s+/g).length; } var count = 'words: ' + countwor...
...ds(wcparent); // create a shadow root var shadow = this.attachshadow({mode: 'open'}); // create text node and add word count to it var text = document.createelement('span'); text.textcontent = count; // append it to the shadow root shadow.appendchild(text); // update count when element content changes setinterval(function() { var count = 'words: ' + countwords(wcparent); text.textcontent = count; }, 200) } } // define the new element customelements.define('word-count', wordcount, { extends: 'p' }); note: the customelementregistry is available through the window.customelements property.
CustomEvent() - Web APIs
the customevent() constructor creates a new customevent.
... example // add an appropriate event listener obj.addeventlistener("cat", function(e) { process(e.detail) }); // create and dispatch the event var event = new customevent("cat", { detail: { hazcheeseburger: true } }); obj.dispatchevent(event); additional examples can be found at creating and triggering events.
DOMMatrixReadOnly() - Web APIs
the dommatrixreadonly constructor creates a new dommatrixreadonly object which represents 4x4 matrices, suitable for 2d and 3d operations.
... syntax var dommatrixreadonly = new dommatrixreadonly([init]) parameters init optional either a string containing a sequence of numbers or an array of integers specifying the matrix you want to create.
DOMMatrixReadOnly.flipX() - Web APIs
the flipx() method of the dommatrixreadonly interface creates a new matrix being the result of the original matrix flipped about the x-axis.
... <svg width="100" height="100" viewbox="-50 0 100 100"> <path fill="red" d="m 0 50 l 50 0 l 50 100 z" /> <path id="flipped" fill="blue" d="m 0 50 l 50 0 l 50 100 z" /> </svg> this javascript first creates an identity matrix, then uses the `flipx()` method to create a new matrix, which is then applied to the blue triangle, inverting it across the x-axis.
DOMMatrixReadOnly.translate() - Web APIs
the translate() method of the dommatrixreadonly interface creates a new matrix being the result of the original matrix with a translation applied.
... examples this svg contains two squares, one red and one blue, each positioned at the document origin: <svg width="250" height="250" viewbox="0 0 50 50"> <rect width="25" height="25" fill="red" /> <rect id="transformed" width="25" height="25" fill="blue" /> </svg> the following javascript first creates an identity matrix, then uses the translate() method to create a new, translated matrix — which is then applied to the blue square as a transform.
DOMParser - Web APIs
WebAPIDOMParser
the possible values are the following: mimetype doc.constructor text/html document text/xml xmldocument application/xml xmldocument application/xhtml+xml xmldocument image/svg+xml xmldocument examples parsing xml once you have created a parser object, you can parse xml from a string using the parsefromstring() method: let parser = new domparser() let doc = parser.parsefromstring(stringcontainingxmlsource, "application/xml") error handling note that if the parsing process fails, the domparser does not throw an exception, but instead returns an error document: <parsererror xmlns="http://www.mozilla.org/newlayout/xml/parser...
...parsefromstring; // firefox/opera/ie throw errors on unsupported types try { // webkit returns null on unsupported types if ((new domparser()).parsefromstring("", "text/html")) { // text/html parsing is natively supported return; } } catch (ex) {} proto.parsefromstring = function(markup, type) { if (/^\s*text\/html\s*(?:;|$)/i.test(type)) { var doc = document.implementation.createhtmldocument(""); if (markup.tolowercase().indexof('<!doctype') > -1) { doc.documentelement.innerhtml = markup; } else { doc.body.innerhtml = markup; } return doc; } else { return nativeparse.apply(this, arguments); } }; }(domparser)); specifications specification status comment html living standardthe definition of 'dom parsing' in t...
DOMPointInit - Web APIs
example this example creates a new dompoint representing the top-left corner of the current window, with a z component added to move the point closer to the user.
... this same code will work to create a dompointreadonly object; just change the interface name in the code.
DOMRect.DOMRect() - Web APIs
WebAPIDOMRectDOMRect
the domrect() constructor creates a new domrect object.
... examples to create a new domrect, you could run a line of code like so: mydomrect = new domrect(0,0,100,100); // running 'mydomrect' in the console would then return // domrect { x: 0, y: 0, width: 100, height: 100, top: 0, right: 100, bottom: 100, left: 0 } specifications specification status comment geometry interfaces module level 1the definition of 'domrect()' in that specification.
DOMRect - Web APIs
WebAPIDOMRect
/api/domrect" target="_top"><rect x="191" y="1" width="75" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="228.5" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">domrect</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor domrect() creates a new domrect object.
... static methods domrectreadonly.fromrect() creates a new domrect object with a given location and dimensions.
DOMRectReadOnly() - Web APIs
the domrectreadonly() constructor creates a new domrectreadonly object.
... examples to create a new dompoint, you could run a line of code like so: const mydomrect = new domrectreadonly(0, 0, 100, 100) // running 'mydomrect' in the console would then return // domrect { x: 0, y: 0, width: 100, height: 100, top: 0, right: 100, bottom: 100, left: 0 } specifications specification status comment geometry interfaces module level 1the definition of 'domrectreadonly()' in that specification.
DOMRectReadOnly - Web APIs
constructor domrectreadonly() defined to create a new domrectreadonly object.
... static methods domrectreadonly.fromrect() creates a new domrect object with a given location and dimensions.
DataTransfer.setDragImage() - Web APIs
this image is created automatically, so you do not need to create it yourself.
...use the event target's id for the data ev.datatransfer.setdata("text/plain", ev.target.id); // create an image and use it for the drag image // note: change "example.gif" to an existing image or the image will not // be created and the default drag image will be used.
DedicatedWorkerGlobalScope.name - Web APIs
the name read-only property of the dedicatedworkerglobalscope interface returns the name that the worker was (optionally) given when it was created.
... example if a worker is created using a constructor with a name option: var myworker = new worker("worker.js", { name : "myworker" }); the dedicatedworkerglobalscope will now have a name of "myworker", returnable by running self.name from inside the worker.
DedicatedWorkerGlobalScope - Web APIs
dedicatedworkerglobalscope.name read only the name that the worker was (optionally) given when it was created using the worker() constructor.
... windowbase64.btoa() creates a base-64 encoded ascii string from a string of binary data.
Document.anchors - Web APIs
WebAPIDocumentanchors
ength >= 5) { dump("found too many anchors"); } the following is an example that auto populates a table of contents with every anchor on the page: <!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <title>test</title> <script> function init() { var toc = document.getelementbyid("toc"); var i, li, newanchor; for (i = 0; i < document.anchors.length; i++) { li = document.createelement("li"); newanchor = document.createelement('a'); newanchor.href = "#" + document.anchors[i].name; newanchor.innerhtml = document.anchors[i].text; li.appendchild(newanchor); toc.appendchild(li); } } </script> </head> <body onload="init()"> <h1>title</h1> <h2><a name="contents">contents</a></h2> <ul id="toc"></ul> <h2><a name="plants">plants</a></h2> <ol> <li>apples<...
.../li> <li>oranges</li> <li>pears</li> </ol> <h2><a name="veggies">veggies</a></h2> <ol> <li>carrots</li> <li>celery</li> <li>beats</li> </ol> </body> </html> view on jsfiddle notes for reasons of backwards compatibility, the returned set of anchors only contains those anchors created with the name attribute, not those created with the id attribute.
Document.evaluate() - Web APIs
WebAPIDocumentevaluate
null is the most common and will create a new xpathresult example var headings = document.evaluate("/html/body//h2", document, null, xpathresult.any_type, null); /* search the document for all h2 elements.
... 10.1safari ios full support 4.2samsung internet android full support 1.0legend full support full support no support no support see also document.createexpression() xpathresult xpath code snippets check for browser support ...
Document.mozSetImageElement() - Web APIs
var c = 0x00; function clicked() { var canvas = document.createelement("canvas"); canvas.setattribute("width", 100); canvas.setattribute("height", 100); var ctx = canvas.getcontext('2d'); ctx.fillstyle = "#" + c.tostring(16) + "0000"; ctx.fillrect(25, 25, 75, 75); c += 0x11; if (c > 0xff) { c = 0x00; } document.mozsetimageelement("canvasbg", canvas); } the code here is called each time the user clicks the <div> element.
... it creates a new <canvas> with the width and height set to 100 pixels, then draws into it a 50 by 50 pixel square.
DocumentTouch - Web APIs
methods documenttouch.createtouch() creates a new touch object.
... documenttouch.createtouchlist() creates a new touchlist object.
Using the W3C DOM Level 1 Core - Web APIs
this implies the ability to create any html or xml document from scratch, or to change any contents of a given html or xml document.
... var para = document.getelementsbytagname("p").item(0); para.firstchild.data = "this is the first paragraph."; // create a new text node for the second paragraph var newtext = document.createtextnode("this is the second paragraph."); // create a new element to be the second paragraph var newelement = document.createelement("p"); // put the text in the paragraph newelement.appendchild(newtext); // and put the paragraph on the end of the document by appending it to // the body (which is th...
How whitespace is handled by HTML, CSS, and in the DOM - Web APIs
there are a few ways of getting around this problem: use flexbox to create the horizontal list of items instead of trying an inline-block solution.
...} or you could set negative margin on the list items: li { display: inline-block; width: 2rem; height: 2rem; margin-right: -0.25rem; } you can also solve this problem by putting your list items all on the same line in the source, which causes the whitespace nodes to not be created in the first place: <li></li><li></li><li></li><li></li><li></li> dom traversal and whitespace when trying to do dom manipulation in javascript, you can also encounter problems because of whitespace nodes.
DragEvent() - Web APIs
this constructor is used to create a synthetic dragevent object.
... although this interface has a constructor, it is not possible to create a useful datatransfer object from script, since datatransfer objects have a processing and security model that is coordinated by the browser during drag-and-drops.
DragEvent - Web APIs
WebAPIDragEvent
constructors although this interface has a constructor, it is not possible to create a useful datatransfer object from script, since datatransfer objects have a processing and security model that is coordinated by the browser during drag-and-drops.
... dragevent() creates a synthetic and untrusted dragevent.
Element.attachShadow() - Web APIs
you can see that we use attachshadow() in the middle of the code to create a shadow root, which we then attach our custom element's contents to.
... // create a class for the element class wordcount extends htmlparagraphelement { constructor() { // always call super first in constructor super(); // count words in element's parent element var wcparent = this.parentnode; function countwords(node){ var text = node.innertext || node.textcontent return text.trim().split(/\s+/g).length; } var count = 'words: ' + countwords(wcparent); // create a shadow root var shadow = this.attachshadow({mode: 'open'}); // create text node and add word count to it var text = document.createelement('span'); text.textcontent = count; // append it to the shadow root shadow.appendchild(text); // update count when element content changes setinterval(function() { var count = 'w...
Element.outerHTML - Web APIs
WebAPIElementouterHTML
for example: var div = document.createelement("div"); div.outerhtml = "<div class=\"test\">test</div>"; console.log(div.outerhtml); // output: "<div></div>" also, while the element will be replaced in the document, the variable whose outerhtml property was set will still hold a reference to the original element: var p = document.getelementsbytagname("p")[0]; console.log(p.nodename); // shows: "p" p.outerhtml = "<div>this div replace...
...d a paragraph.</div>"; console.log(p.nodename); // still "p"; the returned value will contain html escaped attributes: var anc = document.createelement("a"); anc.href = "https://developer.mozilla.org?a=b&c=d"; console.log(anc.outerhtml); // output: "<a href='https://developer.mozilla.org?a=b&amp;c=d'></a>" specification specification status comment dom parsing and serializationthe definition of 'element.outerhtml' in that specification.
Event() - Web APIs
WebAPIEventEvent
the event() constructor creates a new event.
... example // create a look event that bubbles up and cannot be canceled const evt = new event("look", {"bubbles":true, "cancelable":false}); document.dispatchevent(evt); // event can be dispatched from any element, not only the document mydiv.dispatchevent(evt); specifications specification status comment domthe definition of 'event()' in that specification.
Event.composed - Web APIs
WebAPIEventcomposed
for example, this includes synthetic events that are created without their composed option wil set to true.
... the first definition looks like this, for example: customelements.define('open-shadow', class extends htmlelement { constructor() { super(); let pelem = document.createelement('p'); pelem.textcontent = this.getattribute('text'); let shadowroot = this.attachshadow({mode: 'open'}) .appendchild(pelem); } }); we then insert one of each element into our page: <open-shadow text="i have an open shadow root"></open-shadow> <closed-shadow text="i have a closed shadow root"></closed-shadow> then include a click event listener on the <html> eleme...
Event.composedPath() - Web APIs
this does not include nodes in shadow trees if the shadow root was created with its shadowroot.mode closed.
... the first definition looks like this, for example: customelements.define('open-shadow', class extends htmlelement { constructor() { super(); let pelem = document.createelement('p'); pelem.textcontent = this.getattribute('text'); let shadowroot = this.attachshadow({mode: 'open'}) .appendchild(pelem); } }); we then insert one of each element into our page: <open-shadow text="i have an open shadow root"></open-shadow> <closed-shadow text="i have a closed shadow root"></closed-shadow> then include a click event listener on the <html> eleme...
Event.timeStamp - Web APIs
WebAPIEventtimeStamp
the timestamp read-only property of the event interface returns the time (in milliseconds) at which the event was created.
... syntax time = event.timestamp; value this value is the number of milliseconds elapsed from the beginning of the current document's lifetime till the event was created.
EventSource() - Web APIs
the eventsource() constructor returns a newly-created eventsource, which represents a remote resource.
... examples var evtsource = new eventsource('sse.php'); var eventlist = document.queryselector('ul'); evtsource.onmessage = function(e) { var newelement = document.createelement("li"); newelement.textcontent = "message: " + e.data; eventlist.appendchild(newelement); } note: you can find a full example on github — see simple sse demo using php.
EventSource: message event - Web APIs
bubbles no cancelable no interface messageevent event handler property eventsource.onmessage examples in this basic example, an eventsource is created to receive events from the server; a page with the name sse.php is responsible for generating the events.
... var evtsource = new eventsource('sse.php'); var eventlist = document.queryselector('ul'); evtsource.addeventlistener('message', (e) => { var newelement = document.createelement("li"); newelement.textcontent = "message: " + e.data; eventlist.appendchild(newelement); }); onmessage equivalent evtsource.onmessage = (e) => { var newelement = document.createelement("li"); newelement.textcontent = "message: " + e.data; eventlist.appendchild(newelement); }; specifications specification status html living standardthe definition of 'message event' in that specification.
EventTarget.dispatchEvent() - Web APIs
dispatchevent() is the last step of the create-init-dispatch process, which is used for dispatching events into the implementation's event model.
... the event can be created using event constructor.
ExtendableMessageEvent() - Web APIs
the extendablemessageevent() constructor creates a new extendablemessageevent object instance.
... syntax var extendablemessageevent = new extendablemessageevent(type, init); parameters type a domstring that defines the type of the message event being created.
FetchEvent - Web APIs
constructor fetchevent() creates a new fetchevent object.
...the browser creates these objects itself and provides them to fetch event callbacks.
Fetch basic concepts - Web APIs
when a new headers object is created using the headers() constructor, its guard is set to none (the default).
... when a request or response object is created, it has an associated headers object whose guard is set as summarized below: new object's type creating constructor guard setting of associated headers object request request() request request() with mode of no-cors request-no-cors response response() response error() or redirect() methods immutable a header's guard affects the set(), delete(), and append() methods which change the header's contents.
Fetch API - Web APIs
WebAPIFetch API
you can create a request and response directly using the request() and response() constructors, but it's uncommon to do this directly.
... instead, these are more likely to be created as results of other api actions (for example, fetchevent.respondwith() from service workers).
File.lastModified - Web APIs
WebAPIFilelastModified
put"> const fileinput = document.queryselector('#fileinput'); fileinput.addeventlistener('change', (event) => { // files is a filelist object (similar to nodelist) const files = event.target.files; for (let file of files) { const date = new date(file.lastmodified); console.log(`${file.name} has a last modified date of ${date}`); } }); try the results out below: dynamically created files if a file is created dynamically, the last modified time can be supplied in the new file() constructor function.
... if it is missing, lastmodified inherits the current time from date.now() at the moment the file object gets created.
FileReader.readyState - Web APIs
a filereader exists in one of the following states: value state description 0 empty reader has been created.
... empty the filereader has been created, but no readas method was called yet.
FileSystem - Web APIs
some browsers offer additional apis to create and manage file systems, such as chrome's requestfilesystem() method.
... basic concepts there are two ways to get access to a filesystem object: you can directly ask for one representing a sandboxed file system created just for your web app directly by calling window.requestfilesystem().
FileSystemEntry.toURL() - Web APIs
the filesystementry interface's method tourl() creates and returns a string containing a url which can be used to identify the file system entry.
... code that makes use of this might look like this: let img = document.createelement("img"); img.src = imagefileentry.tourl(); document.body.appendchild(img); assuming the scenario mentioned before the code, the result would be html that looks like this being appended to the end of the document: <img src="filesystem:http://my-awesome-website.woot/temporary/awesomesauce.jpg"> browser compatibility the compatibility table on this page is generated from structured data.
FileSystemEntry - Web APIs
basic concepts you don't create filesystementry objects directly.
... tourl() creates and returns a url which identifies the entry.
FileSystemFileEntry.file() - Web APIs
syntax filesystemfileentry.file(successcallback[, errorcallback]); parameters successcallback a callback function which is called when the file has been created successfully; the file is passed into the callback as the only parameter.
... errorcallback optional if provided, this must be a method which is called when an error occurs while trying to create the file.
FormData() - Web APIs
WebAPIFormDataFormData
the formdata() constructor creates a new formdata object.
... example the following line creates an empty formdata object: var formdata = new formdata(); // currently empty you could add a key/value pair to this using formdata.append: formdata.append('username', 'chris'); or you can specify the optional form argument when creating the formdata object, to prepopulate it with values from the specified form: <form id="myform" name="myform"> <div> <label for="username">enter name:</...
Frame Timing API - Web APIs
when one of those event types is recorded in the browser's performance timeline, the application is notified of the event via the observer's callback function that was specified when the observer was created.
... to observe "frame" performance entry types, the application first creates a performanceobserver object with a specific frame observer callback (function).
GainNode() - Web APIs
WebAPIGainNodeGainNode
the gainnode() constructor of the web audio api creates a new gainnode object which an audionode that represents a change in volume.
... note: you should typically call audiocontext.creategain() to create a gain node.
Using the Gamepad API - Web APIs
var haveevents = 'ongamepadconnected' in window; var controllers = {}; function connecthandler(e) { addgamepad(e.gamepad); } function addgamepad(gamepad) { controllers[gamepad.index] = gamepad; var d = document.createelement("div"); d.setattribute("id", "controller" + gamepad.index); var t = document.createelement("h1"); t.appendchild(document.createtextnode("gamepad: " + gamepad.id)); d.appendchild(t); var b = document.createelement("div"); b.classname = "buttons"; for (var i = 0; i < gamepad.buttons.length; i++) { var e = document.createelement("span"); e.classname = "button"; //e...
....id = "b" + i; e.innerhtml = i; b.appendchild(e); } d.appendchild(b); var a = document.createelement("div"); a.classname = "axes"; for (var i = 0; i < gamepad.axes.length; i++) { var p = document.createelement("progress"); p.classname = "axis"; //p.id = "a" + i; p.setattribute("max", "2"); p.setattribute("value", "1"); p.innerhtml = i; a.appendchild(p); } d.appendchild(a); // see https://github.com/luser/gamepadtest/blob/master/index.html var start = document.getelementbyid("start"); if (start) { start.style.display = "none"; } document.body.appendchild(d); requestanimationframe(updatestatus); } function disconnecthandler(e) { removegamepad(e.gamepad); } function removegamepad(gamepad) { var d = document.getelementbyid...
GlobalEventHandlers.onmousemove - Web APIs
examples tooltips this example creates link tooltips that follow your mouse.
... html <p><a href="#" data-tooltip="first link">see a tooltip here &hellip;</a></p> <p><a href="#" data-tooltip="second link">&hellip; or here!</a></p> css .tooltip { position: absolute; z-index: 9999; padding: 6px; background: #ffd; border: 1px #886 solid; border-radius: 5px; } javascript const tooltip = new (function() { const node = document.createelement('div'); node.classname = 'tooltip'; node.setattribute('hidden', ''); document.body.appendchild(node); this.follow = function(event) { node.style.left = event.clientx + 20 + 'px'; node.style.top = event.clienty + 10 + 'px'; }; this.show = function(event) { node.textcontent = event.target.dataset.tooltip; node.removeattribute('hidden'); }; this.hide = funct...
HTMLCanvasElement.mozFetchAsStream() - Web APIs
the htmlcanvaselement.mozfetchasstream() internal method used to create a new input stream that, when ready, would provide the contents of the canvas as image data.
...also uses netutil.jsm var canvas = document.getelementbyid('canvas'); var d = canvas.width; ctx = canvas.getcontext('2d'); ctx.beginpath(); ctx.moveto(d / 2, 0); ctx.lineto(d, d); ctx.lineto(0, d); ctx.closepath(); ctx.fillstyle = 'yellow'; ctx.fill(); var netutilcallback = function() { return function(result) { if (!components.issuccesscode(result)) { alert('failed to create icon'); } else { alert('succesfully made'); } }; } var mfascallback = function(iconname) { return function(instream) { var file = fileutils.getfile('desk', [iconname + '.ico']); var outstream = fileutils.openfileoutputstream(file); cu.import('resource://gre/modules/netutil.jsm'); netutil.asynccopy(instream, outstream, netutilcallback()...
HTMLCanvasElement: webglcontextcreationerror event - Web APIs
the webglcontextcreationerror event of the webgl api is fired if the user agent is unable to create a webglrenderingcontext context.
... yes cancelable yes interface webglcontextevent event handler property none example var canvas = document.getelementbyid('canvas'); canvas.addeventlistener('webglcontextcreationerror', function(e) { console.log(e.statusmessage || 'unknown error'); }, false); var gl = canvas.getcontext('webgl'); // logs statusmessage or "unknown error" if unable to create webgl context specifications specification status comment webgl 1.0the definition of 'webglcontextcreationerror' in that specification.
HTMLCanvasElement: webglcontextrestored event - Web APIs
once the context is restored, webgl resources such as textures and buffers that were created before the context was lost are no longer valid.
... you need to reinitialize the state of your webgl application and recreate resources.
HTMLCanvasElement - Web APIs
htmlcanvaselement.toblob() creates a blob object representing the image contained in the canvas; this file may be cached on the disk or stored in memory at the discretion of the user agent.
... webglcontextcreationerror fired if the user agent is unable to create a webglrenderingcontext or webgl2renderingcontext context.
HTMLElement: transitionrun event - Web APIs
the transitionrun event is fired when a css transition is first created, i.e.
...r('.message'); el.addeventlistener('transitionrun', function() { message.textcontent = 'transitionrun fired'; }); el.addeventlistener('transitionstart', function() { message.textcontent = 'transitionstart fired'; }); el.addeventlistener('transitionend', function() { message.textcontent = 'transitionend fired'; }); the difference is that: transitionrun fires when the transition is created (i.e.
Image() - Web APIs
the image() constructor creates a new htmlimageelement instance.
... it is functionally equivalent to document.createelement('img').
HTMLInputElement - Web APIs
defaultchecked boolean: returns / sets the default state of a radio button or checkbox as originally specified in html that created this object.
... properties not yet categorized defaultvalue string: returns / sets the default value as originally specified in the html that created this object.
Recommended Drag Types - Web APIs
the following example shows how to create an area for receiving dropped files: <listbox ondragenter="return checkdrag(event)" ondragover="return checkdrag(event)" ondrop="dodrop(event)"/> <script> function checkdrag(event) { return event.datatransfer.types.contains("application/x-moz-file"); } function dodrop(event) { var file = event.datatransfer.mozgetdataat("application/x-moz-file", 0); if (file instanceof c...
...supportsstring).data; console.log("target filename is = " + name); var dirprimitive = {}; atransferable.gettransferdata('application/x-moz-file-promise-dir', dirprimitive, datasize); var dir = dirprimitive.value.queryinterface(components.interfaces.nsilocalfile); console.log("target folder is = " + dir.path); var file = cc['@mozilla.org/file/local;1'].createinstance(components.interfaces.nsilocalfile); file.initwithpath(dir.path); file.appendrelativepath(name); console.log("output final path is =" + file.path); // now you can write or copy the file yourself… } } } see also html drag and drop api (overview) drag operations dragging and dropping multiple items html5 living standard: drag and drop ...
IDBCursor.advance() - Web APIs
WebAPIIDBCursoradvance
example in this simple fragment we create a transaction, retrieve an object store, then use a cursor to iterate through the records in the object store.
...r a complete working example, see our idbcursor example (view example live.) function advanceresult() { list.innerhtml = ''; var transaction = db.transaction(['rushalbumlist'], "readonly"); var objectstore = transaction.objectstore('rushalbumlist'); objectstore.opencursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listitem = document.createelement('li'); listitem.innerhtml = '<strong>' + cursor.value.albumtitle + '</strong>, ' + cursor.value.year; list.appendchild(listitem); cursor.advance(2); } else { console.log('every other entry displayed.'); } }; }; specifications specification status comment indexed database api 2.0the definition of 'advance()' in that specification.
IDBCursor.continue() - Web APIs
example in this simple fragment we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store.
...for a complete working example, see our idbcursor example (view example live.) function displaydata() { var transaction = db.transaction(['rushalbumlist'], "readonly"); var objectstore = transaction.objectstore('rushalbumlist'); objectstore.opencursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listitem = document.createelement('li'); listitem.innerhtml = cursor.value.albumtitle + ', ' + cursor.value.year; list.appendchild(listitem); cursor.continue(); } else { console.log('entries all displayed.'); } }; }; specifications specification status comment indexed database api 2.0the definition of 'continue()' in that specification.
IDBCursor.direction - Web APIs
example in this simple fragment we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store.
...e working example, see our idbcursor example (view example live.) function backwards() { list.innerhtml = ''; var transaction = db.transaction(['rushalbumlist'], 'readonly'); var objectstore = transaction.objectstore('rushalbumlist'); objectstore.opencursor(null,'prev').onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listitem = document.createelement('li'); listitem.innerhtml = '<strong>' + cursor.value.albumtitle + '</strong>, ' + cursor.value.year; list.appendchild(listitem); console.log(cursor.direction); cursor.continue(); } else { console.log('entries displayed backwards.'); } }; }; specifications specification status comment indexed database api 2.0t...
IDBCursor.key - Web APIs
WebAPIIDBCursorkey
example in this simple fragment we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store.
...for a complete working example, see our idbcursor example (view example live.) function displaydata() { var transaction = db.transaction(['rushalbumlist'], "readonly"); var objectstore = transaction.objectstore('rushalbumlist'); objectstore.opencursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listitem = document.createelement('li'); listitem.innerhtml = cursor.value.albumtitle + ', ' + cursor.value.year; list.appendchild(listitem); console.log(cursor.key); cursor.continue(); } else { console.log('entries all displayed.'); } }; }; specifications specification status comment indexed database api 2.0the definition of 'key' in that specification.
IDBCursor.primaryKey - Web APIs
example in this simple fragment we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store.
...for a complete working example, see our idbcursor example (view example live.) function displaydata() { var transaction = db.transaction(['rushalbumlist'], "readonly"); var objectstore = transaction.objectstore('rushalbumlist'); objectstore.opencursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listitem = document.createelement('li'); listitem.innerhtml = cursor.value.albumtitle + ', ' + cursor.value.year; list.appendchild(listitem); console.log(cursor.primarykey); cursor.continue(); } else { console.log('entries all displayed.'); } }; }; specifications specification status comment indexed database api 2.0the definition of 'primarykey' in that spe...
IDBCursor.source - Web APIs
WebAPIIDBCursorsource
example in this simple fragment we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store.
...for a complete working example, see our idbcursor example (view example live.) function displaydata() { var transaction = db.transaction(['rushalbumlist'], "readonly"); var objectstore = transaction.objectstore('rushalbumlist'); objectstore.opencursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listitem = document.createelement('li'); listitem.innerhtml = cursor.value.albumtitle + ', ' + cursor.value.year; list.appendchild(listitem); console.log(cursor.source); cursor.continue(); } else { console.log('entries all displayed.'); } }; }; specifications specification status comment indexed database api 2.0the definition of 'source' in that specificati...
IDBCursor - Web APIs
WebAPIIDBCursor
examples in this simple fragment we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store.
...for a complete working example, see our idbcursor example (view example live.) function displaydata() { var transaction = db.transaction(['rushalbumlist'], "readonly"); var objectstore = transaction.objectstore('rushalbumlist'); objectstore.opencursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listitem = document.createelement('li'); listitem.innerhtml = cursor.value.albumtitle + ', ' + cursor.value.year; list.appendchild(listitem); cursor.continue(); } else { console.log('entries all displayed.'); } }; } specifications specification status comment indexed database api 2.0the definition of 'cursor' in that specification.
IDBCursorWithValue.value - Web APIs
example in this example we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store.
...for a complete working example, see our idbcursor example (view example live.) function displaydata() { var transaction = db.transaction(['rushalbumlist'], "readonly"); var objectstore = transaction.objectstore('rushalbumlist'); objectstore.opencursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listitem = document.createelement('li'); listitem.innerhtml = cursor.value.albumtitle + ', ' + cursor.value.year; list.appendchild(listitem); console.log(cursor.value); cursor.continue(); } else { console.log('entries all displayed.'); } }; }; specifications specification status comment indexed database api 2.0the definition of 'source' in that specificatio...
IDBCursorWithValue - Web APIs
example in this example we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store.
...for a complete working example, see our idbcursor example (view example live.) function displaydata() { var transaction = db.transaction(['rushalbumlist'], "readonly"); var objectstore = transaction.objectstore('rushalbumlist'); objectstore.opencursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listitem = document.createelement('li'); listitem.innerhtml = cursor.value.albumtitle + ', ' + cursor.value.year; list.appendchild(listitem); cursor.continue(); } else { console.log('entries all displayed.'); } }; }; specifications specification status comment indexed database api 2.0the definition of 'idbcursorwithvalue' in that specification.
IDBDatabase.deleteObjectStore() - Web APIs
as with idbdatabase.createobjectstore, this method can be called only within a versionchange transaction.
... example var dbname = "sampledb"; var dbversion = 2; var request = indexeddb.open(dbname, dbversion); request.onupgradeneeded = function(e) { var db = request.result; if (e.oldversion < 1) { db.createobjectstore("store1"); } if (e.oldversion < 2) { db.deleteobjectstore("store1"); db.createobjectstore("store2"); } // etc.
IDBIndex.get() - Web APIs
WebAPIIDBIndexget
if a value is found, then a structured clone of it is created and set as the result of the request object: this returns the record the key is associated with.
...ion(['contactslist'], 'readonly'); var objectstore = transaction.objectstore('contactslist'); var myindex = objectstore.index('lname'); var getrequest = myindex.get('bungle'); getrequest.onsuccess = function() { console.log(getrequest.result); } myindex.opencursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var tablerow = document.createelement('tr'); tablerow.innerhtml = '<td>' + cursor.value.id + '</td>' + '<td>' + cursor.value.lname + '</td>' + '<td>' + cursor.value.fname + '</td>' + '<td>' + cursor.value.jtitle + '</td>' + '<td>' + cursor.value.company + '</td>' + '<td>' + cursor.value...
IDBIndex.getAll() - Web APIs
WebAPIIDBIndexgetAll
there is a performance cost associated with looking at the value property of a cursor, because the object is created lazily.
... to use a feature like getall(), the browser has to create all the objects at once.
IDBIndex.isAutoLocale - Web APIs
the isautolocale read-only property of the idbindex interface returns a boolean indicating whether the index had a locale value of auto specified upon its creation (see createindex()'s optionalparameters.) syntax var myindex = objectstore.index('index'); console.log(myindex.isautolocale); value a boolean.
...displaydatabyindex() { tableentry.innerhtml = ''; var transaction = db.transaction(['contactslist'], 'readonly'); var objectstore = transaction.objectstore('contactslist'); var myindex = objectstore.index('lname'); console.log(myindex.isautolocale); myindex.opencursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var tablerow = document.createelement('tr'); tablerow.innerhtml = '<td>' + cursor.value.id + '</td>' + '<td>' + cursor.value.lname + '</td>' + '<td>' + cursor.value.fname + '</td>' + '<td>' + cursor.value.jtitle + '</td>' + '<td>' + cursor.value.company + '</td>' + '<td>' + cursor.value...
IDBIndex.locale - Web APIs
WebAPIIDBIndexlocale
the locale read-only property of the idbindex interface returns the locale of the index (for example en-us, or pl) if it had a locale value specified upon its creation (see createindex()'s optionalparameters.) note that this property always returns the current locale being used in this index, in other words, it never returns "auto".
...ction displaydatabyindex() { tableentry.innerhtml = ''; var transaction = db.transaction(['contactslist'], 'readonly'); var objectstore = transaction.objectstore('contactslist'); var myindex = objectstore.index('lname'); console.log(myindex.locale); myindex.opencursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var tablerow = document.createelement('tr'); tablerow.innerhtml = '<td>' + cursor.value.id + '</td>' + '<td>' + cursor.value.lname + '</td>' + '<td>' + cursor.value.fname + '</td>' + '<td>' + cursor.value.jtitle + '</td>' + '<td>' + cursor.value.company + '</td>' + '<td>' + cursor.value...
IDBIndex.multiEntry - Web APIs
this is decided when the index is created, using the idbobjectstore.createindex method.
...n displaydatabyindex() { tableentry.innerhtml = ''; var transaction = db.transaction(['contactslist'], 'readonly'); var objectstore = transaction.objectstore('contactslist'); var myindex = objectstore.index('lname'); console.log(myindex.multientry); myindex.opencursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var tablerow = document.createelement('tr'); tablerow.innerhtml = '<td>' + cursor.value.id + '</td>' + '<td>' + cursor.value.lname + '</td>' + '<td>' + cursor.value.fname + '</td>' + '<td>' + cursor.value.jtitle + '</td>' + '<td>' + cursor.value.company + '</td>' + '<td>' + cursor.value...
IDBIndex.openCursor() - Web APIs
the opencursor() method of the idbindex interface returns an idbrequest object, and, in a separate thread, creates a cursor over the specified key range.
...o (view the example live.) function displaydatabyindex() { tableentry.innerhtml = ''; var transaction = db.transaction(['contactslist'], 'readonly'); var objectstore = transaction.objectstore('contactslist'); var myindex = objectstore.index('lname'); myindex.opencursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var tablerow = document.createelement('tr'); tablerow.innerhtml = '<td>' + cursor.value.id + '</td>' + '<td>' + cursor.value.lname + '</td>' + '<td>' + cursor.value.fname + '</td>' + '<td>' + cursor.value.jtitle + '</td>' + '<td>' + cursor.value.company + '</td>' + '<td>' + cursor.value...
IDBIndex.openKeyCursor() - Web APIs
the openkeycursor() method of the idbindex interface returns an idbrequest object, and, in a separate thread, creates a cursor over the specified key range, as arranged by this index.
... function displaydatabyindex() { tableentry.innerhtml = ''; var transaction = db.transaction(['contactslist'], 'readonly'); var objectstore = transaction.objectstore('contactslist'); var myindex = objectstore.index('lname'); myindex.openkeycursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var tablerow = document.createelement('tr'); tablerow.innerhtml = '<td>' + cursor.key + '</td>' + '<td>' + cursor.primarykey + '</td>'; tableentry.appendchild(tablerow); cursor.continue(); } else { console.log('all last names displayed.'); } }; }; specification specification status comment indexed database api 2.0the definition of 'o...
IDBIndex.unique - Web APIs
WebAPIIDBIndexunique
this is decided when the index is created, using the idbobjectstore.createindex method.
...ction displaydatabyindex() { tableentry.innerhtml = ''; var transaction = db.transaction(['contactslist'], 'readonly'); var objectstore = transaction.objectstore('contactslist'); var myindex = objectstore.index('lname'); console.log(myindex.unique); myindex.opencursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var tablerow = document.createelement('tr'); tablerow.innerhtml = '<td>' + cursor.value.id + '</td>' + '<td>' + cursor.value.lname + '</td>' + '<td>' + cursor.value.fname + '</td>' + '<td>' + cursor.value.jtitle + '</td>' + '<td>' + cursor.value.company + '</td>' + '<td>' + cursor.value...
IDBIndexSync - Web APIs
opencursor() creates a cursor over the records of this index.
... openobjectcursor() creates a cursor over the records of this index's referenced object store, as arranged by this index.
IDBLocaleAwareKeyRange - Web APIs
the idblocaleawarekeyrange interface of the indexeddb api is a firefox-specific version of idbkeyrange — it functions in exactly the same fashion, and has the same properties and methods, but it is intended for use with idbindex objects when the original index had a locale value specified upon its creation (see createindex()'s optionalparameters) — that is, it has locale aware sorting enabled.
...unction displaydata() { var keyrangevalue = idblocaleawarekeyrange.bound("a", "f"); var transaction = db.transaction(['fthings'], 'readonly'); var objectstore = transaction.objectstore('fthings'); var myindex = objectstore.index('lname'); myindex.opencursor(keyrangevalue).onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var tablerow = document.createelement('tr'); tablerow.innerhtml = '&lt;td&gt;' + cursor.value.id + '&lt;/td&gt;' + '&lt;td&gt;' + cursor.value.lname + '&lt;/td&gt;' + '&lt;td&gt;' + cursor.value.fname + '&lt;/td&gt;' + '&lt;td&gt;' + cursor.value.jtitle + '&lt;/td&gt;' + '&lt;td&gt;' + cursor.value.company + '&lt...
IDBObjectStore.clear() - Web APIs
the clear() method of the idbobjectstore interface creates and immediately returns an idbrequest object, and clears this object store in a separate thread.
...r transaction = db.transaction(["todolist"], "readwrite"); // report on the success of the transaction completing, when everything is done transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error: ' + transaction.error + '</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // make a request to clear all the data out of the object store var objectstorerequest = objectstore.clear(); objectstorerequest.onsuccess = function(event) { // report the success of our request note.innerhtml += '<li>request successful.</li>'; }; }; specification specificatio...
IDBObjectStore.get() - Web APIs
if a value is successfully found, then a structured clone of it is created and set as the result of the request object.
...r transaction = db.transaction(["todolist"], "readwrite"); // report on the success of the transaction completing, when everything is done transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error: ' + transaction.error + '</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // make a request to get a record by key from the object store var objectstorerequest = objectstore.get("walk dog"); objectstorerequest.onsuccess = function(event) { // report the success of our request note.innerhtml += '<li>request successful.</li>'; var myrecord = objectstorerequest...
IDBObjectStore.put() - Web APIs
it returns an idbrequest object, and, in a separate thread, creates a structured clone of the value and stores the cloned value in the object store.
...(['todolist'], "readwrite").objectstore('todolist'); // get the to-do list object that has this title as it's title const objectstoretitlerequest = objectstore.get(title); objectstoretitlerequest.onsuccess = () => { // grab the data object returned as the result const data = objectstoretitlerequest.result; // update the notified value in the object to "yes" data.notified = "yes"; // create another request that inserts the item back into the database const updatetitlerequest = objectstore.put(data); // log the transaction that originated this request console.log("the transaction that originated this request is " + updatetitlerequest.transaction); // when this new request succeeds, run the displaydata() function again to update the display updatetitlerequest.onsuccess = (...
IDBOpenDBRequest.onblocked - Web APIs
// this is used a lot below db = request.result; // run the displaydata() function to populate the task list with // all the to-do list data already in the idb displaydata(); }; // this event handles the event whereby a new version of the // database needs to be created.
... either one has not been created // before, or a new version number has been submitted via the // window.indexeddb.open line above //it is only implemented in recent browsers request.onupgradeneeded = function(event) { var db = event.target.result; db.onerror = function(event) { note.innerhtml += '<li>error loading database.</li>'; }; // create an objectstore for this database var objectstore = db.createobjectstore("todolist", { keypath: "tasktitle" }); ...
IDBOpenDBRequest - Web APIs
this is used a lot below db = dbopenrequest.result; // run the displaydata() function to populate the task // listwith all the to-do list data already in the idb displaydata(); }; // this event handles the event whereby a new version of // the database needs to be created either one has not // been created before, or a new version number has been // submitted via the window.indexeddb.open line above // it is only implemented in recent browsers dbopenrequest.onupgradeneeded = function(event) { var db = this.result; db.onerror = function(event) { note.innerhtml += '<li>error loading database.</li>'; }; // create an objectstore for this database var ...
...objectstore = db.createobjectstore("todolist", { keypath: "tasktitle" }); // define what data items the objectstore will contain objectstore.createindex("hours", "hours", { unique: false }); objectstore.createindex("minutes", "minutes", { unique: false }); objectstore.createindex("day", "day", { unique: false }); objectstore.createindex("month", "month", { unique: false }); objectstore.createindex("year", "year", { unique: false }); objectstore.createindex("notified", "notified", { unique: false }); }; specifications specification status comment indexed database api 2.0the definition of 'idbopendbrequest' in that specification.
IDBTransaction.db - Web APIs
WebAPIIDBTransactiondb
// this is used a lot below db = dbopenrequest.result; // run the adddata() function to add the data to the database adddata(); }; function adddata() { // create a new object ready for being inserted into the idb var newitem = [ { tasktitle: "walk dog", hours: 19, minutes: 30, day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(e...
...duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of the request (this does not mean the item // has been stored successfully in the db - for that you need transaction.onsuccess) note.innerhtml += '<li>request successful.</li>'; }; // return the database (idbdatabase) connection with which this transacti...
IDBTransaction.error - Web APIs
// this is used a lot below db = dbopenrequest.result; // run the adddata() function to add the data to the database adddata(); }; function adddata() { // create a new object ready for being inserted into the idb var newitem = [ { tasktitle: "walk dog", hours: 19, minutes: 30, day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(e...
...vent) { note.innerhtml += '<li>transaction completed: database modification finished.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error: ' + transaction.error + '</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of the request (this does not mean the item // has been stored successfully in the db - for that you need transaction.onsuccess) note.innerhtml += '<li>request successful.</li>'; }; }; specification specification status comment indexe...
IDBTransaction.objectStore() - Web APIs
// this is used a lot below db = dbopenrequest.result; // run the adddata() function to add the data to the database adddata(); }; function adddata() { // create a new object ready for being inserted into the idb var newitem = [ { tasktitle: "walk dog", hours: 19, minutes: 30, day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(e...
...duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of the request (this does not mean the item // has been stored successfully in the db - for that you need transaction.onsuccess) note.innerhtml += '<li>request successful.</li>'; }; specification specification status comment ind...
IDBTransaction.onabort - Web APIs
// this is used a lot below db = dbopenrequest.result; // run the adddata() function to add the data to the database adddata(); }; function adddata() { // create a new object ready for being inserted into the idb var newitem = [ { tasktitle: "walk dog", hours: 19, minutes: 30, day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(e...
...vent) { note.innerhtml += '<li>transaction completed: database modification finished.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error: ' + transaction.error + '</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of the request (this does not mean the item // has been stored successfully in the db - for that you need transaction.onsuccess) note.innerhtml += '<li>request successful.</li>'; }; transaction.onabort = function() { // report when the transaction was su...
IDBTransaction.oncomplete - Web APIs
// this is used a lot below db = dbopenrequest.result; // run the adddata() function to add the data to the database adddata(); }; function adddata() { // create a new object ready for being inserted into the idb var newitem = [ { tasktitle: "walk dog", hours: 19, minutes: 30, day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(e...
...vent) { note.innerhtml += '<li>transaction completed: database modification finished.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error: ' + transaction.error + '</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of the request (this does not mean the item // has been stored successfully in the db - for that you need transaction.oncomplete) note.innerhtml += '<li>request successful.</li>'; }; }; specification specification status comment indexe...
IDBTransaction.onerror - Web APIs
// this is used a lot below db = dbopenrequest.result; // run the adddata() function to add the data to the database adddata(); }; function adddata() { // create a new object ready for being inserted into the idb var newitem = [ { tasktitle: "walk dog", hours: 19, minutes: 30, day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(e...
...vent) { note.innerhtml += '<li>transaction completed: database modification finished.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error: ' + transaction.error + '</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of the request (this does not mean the item // has been stored successfully in the db - for that you need transaction.onsuccess) note.innerhtml += '<li>request successful.</li>'; }; }; specification specification status comment indexe...
ImageData() - Web APIs
if no such array is given, an image with a transparent black rectangle of the specified width and height will be created.
... examples creating a blank imagedata object this example creates an imagedata object that is 200 pixels wide and 100 pixels tall, containing a total of 20,000 pixels.
IndexedDB API - Web APIs
you create a transaction on a database, specify the scope (such as which object stores you want to access), and determine the kind of access (read only or readwrite) that you want.
... idblocaleawarekeyrange defines a key range that can be used to retrieve data from a database in a certain range, sorted according to the rules of the locale specified for a certain index (see createindex()'s optionalparameters.).
install - Web APIs
description in the example below, a special javascript object constructor is used to create an object that can be passed to the install() method.
... in the example below, a single installation object is created, but you can use this approach to create multiple installations to pass to a single install.
IntersectionObserver.IntersectionObserver() - Web APIs
the intersectionobserver() constructor creates and returns a new intersectionobserver object.
... example this example creates a new intersection observer which calls the function myobservercallback every time the visible area of the element being observed changes by at least 10%.
KeyboardEvent - Web APIs
t" target="_top"><rect x="231" y="1" width="130" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="296" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">keyboardevent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor keyboardevent() creates a new keyboardevent object.
... keyboardevent.getmodifierstate() returns a boolean indicating if a modifier key such as alt, shift, ctrl, or meta, was pressed when the event was created.
KeyframeEffect - Web APIs
the keyframeeffect interface of the web animations api lets us create sets of animatable properties and values, called keyframes.
... examples in the follow the white rabbit example, the keyframeeffect constructor is used to create a set of keyframes that dictate how the white rabbit should animate down the hole: var rabbitdownkeyframes = new keyframeeffect( whiterabbit, // element to animate [ { transform: 'translatey(0%)' }, // keyframe { transform: 'translatey(100%)' } // keyframe ], { duration: 3000, fill: 'forwards' } // keyframe options ); specifications specification s...
MSManipulationEvent.initMSManipulationEvent() - Web APIs
the initmsmanipulationevent method is used to create a msmanipulationevent that can be called from javascript.
... syntax msmanipulationevent.initmsmanipulationevent(typearg, canbubblearg, cancelablearg, viewarg, detailarg, laststate, currentstate); parameters typearg [in] type: domstring the type of the event being created.
MediaElementAudioSourceNode() - Web APIs
the mediaelementaudiosourcenode() constructor creates a new mediaelementaudiosourcenode object instance.
... example var ac = new audiocontext(); var mediaelement = document.createelement('audio'); var options = { mediaelement : mediaelement } var myaudiosource = new mediaelementaudiosourcenode(ac, options); specifications specification status comment web audio apithe definition of 'mediaelementaudiosourcenode' in that specification.
MediaError.code - Web APIs
WebAPIMediaErrorcode
example this example creates a <video> element, establishes an error handler for it, and then sets the element's src attribute to the video resource to present in the element.
... the error handler simply outputs a message var obj = document.createelement('video'); obj.onerror = function() {console.log("error with media: " + obj.error.code);} obj.src="https://example.com/blahblah.mp4"; specifications specification status comment html living standardthe definition of 'mediaerror.code' in that specification.
MediaError.message - Web APIs
example this example creates a <audio> element, establishes an error handler for it, then lets the user click buttons to choose whether to assign a valid audio file or a missing file to the element's src attribute.
... the example creates an <audio> element and lets the user assign either a valid music file to it, or a link to a file which doesn't exist.
MediaMetadata.MediaMetadata() - Web APIs
the mediametadata() constructor creates a new mediametadata object.
... example the following example creates a new media session and assigns action handlers to it: if ('mediasession' in navigator){ navigator.mediasession.metadata = new mediametadata({ title: "podcast episode title", artist: "podcast host", album: "podcast name", artwork: [{src: "podcast.jpg"}] }); navigator.mediasession.setactionhandler('play', function() {}); navigator.mediasession.setactionhandler('pause', fu...
MediaQueryList - Web APIs
you can create a mediaquerylist by calling matchmedia() on the window object.
... examples this simple example creates a mediaquerylist and then sets up a listener to detect when the media query status changes, running a custom function when it does to change the appearence of the page.
MediaRecorder: dataavailable event - Web APIs
var chunks = []; mediarecorder.addeventlistener('stop', (event) => { 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); }); ...
... var chunks = []; mediarecorder.onstop = 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); } ...
MediaRecorder.ondataavailable - Web APIs
when mediarecorder.requestdata() is called, all media data which has been captured since recording began or the last time a dataavailable event occurred is delivered; then a new blob is created and media capture continues into that blob.
... var chunks = []; mediarecorder.onstop = 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); } ...
MediaRecorder.onerror - Web APIs
example this example creates a new mediarecorder instance and starts recording using the user agent's default media format.
...eak; case securityerror: shownotification("recording the specified source " + "is not allowed due to security " + "restrictions."); break; default: shownotification("a problem occurred while trying " + "to record the video."); break; } }; /* this would be a good place to create a worker to handle writing the buffers to disk periodically */ recorder.start(100); /* 100ms time slices per buffer */ return recorder; } specifications specification status comment mediastream recordingthe definition of 'mediarecorder.onerror' in that specification.
MediaRecorder.stream - Web APIs
the mediarecorder.stream read-only property returns the stream that was passed into the mediarecorder() constructor when the mediarecorder was created.
... syntax var stream = mediarecorder.stream values the mediastream passed into the mediarecorder() constructor when the mediarecorder was originally created.
MediaSource.endOfStream() - Web APIs
this can be used create a custom error handler related to media streams.
...urce for further investigation.) var asseturl = 'frag_bunny.mp4'; // need to be specific for blink regarding codecs // ./mp4info frag_bunny.mp4 | grep codec var mimecodec = 'video/mp4; codecs="avc1.42e01e, mp4a.40.2"'; if ('mediasource' in window && mediasource.istypesupported(mimecodec)) { var mediasource = new mediasource; //console.log(mediasource.readystate); // closed video.src = url.createobjecturl(mediasource); mediasource.addeventlistener('sourceopen', sourceopen); } else { console.error('unsupported mime type or codec: ', mimecodec); } function sourceopen (_) { //console.log(this.readystate); // open var mediasource = this; var sourcebuffer = mediasource.addsourcebuffer(mimecodec); fetchab(asseturl, function (buf) { sourcebuffer.addeventlistener('updateend', fun...
MediaSource.isTypeSupported() - Web APIs
that is, if it can successfully create sourcebuffer objects for that mime type.
...urce for further investigation.) var asseturl = 'frag_bunny.mp4'; // need to be specific for blink regarding codecs // ./mp4info frag_bunny.mp4 | grep codec var mimecodec = 'video/mp4; codecs="avc1.42e01e, mp4a.40.2"'; if ('mediasource' in window && mediasource.istypesupported(mimecodec)) { var mediasource = new mediasource; //console.log(mediasource.readystate); // closed video.src = url.createobjecturl(mediasource); mediasource.addeventlistener('sourceopen', sourceopen); } else { console.error('unsupported mime type or codec: ', mimecodec); } function sourceopen (_) { //console.log(this.readystate); // open var mediasource = this; var sourcebuffer = mediasource.addsourcebuffer(mimecodec); fetchab(asseturl, function (buf) { sourcebuffer.addeventlistener('updateend', fun...
MediaStream - Web APIs
constructor mediastream() creates and returns a new mediastream object.
... you can create an empty stream, a stream which is based upon an existing stream, or a stream that contains a specified list of tracks (specified as an array of mediastreamtrack objects).
MediaStreamAudioDestinationNode - Web APIs
it is an audionode that acts as an audio destination, created using the audiocontext.createmediastreamdestination method.
... number of inputs 1 number of outputs 0 channel count 2 channel count mode "explicit" channel count interpretation "speakers" constructor mediastreamaudiodestinationnode.mediastreamaudiodestinationnode() creates a new mediastreamaudiodestinationnode object instance.
MediaStreamTrackAudioSourceOptions.mediaStreamTrack - Web APIs
the mediastreamtrackaudiosourceoptions dictionary's mediastreamtrack property must contain a reference to the mediastreamtrack from which the mediastreamtrackaudiosourcenode being created using the mediastreamtrackaudiosourcenode() constructor.
... example this example uses getusermedia() to obtain access to the user's camera, then creates a new mediastreamaudiosourcenode from the first audio track provided by the device.
MessageChannel() - Web APIs
syntax var channel = new messagechannel(); returns a newly created messagechannel object.
... example in the following code block, you can see a new channel being created using the messagechannel.messagechannel constructor.
MessageChannel - Web APIs
the messagechannel interface of the channel messaging api allows us to create a new message channel and send data through it via its two messageport properties.
... example in the following example, you can see a new channel being created using the messagechannel.messagechannel constructor.
MessageEvent.MessageEvent() - Web APIs
the messageevent() constructor creates a new messageevent object instance.
... syntax var messageevent = new messageevent(type, init); parameters type the type of messageevent that will be created.
MessageEvent - Web APIs
ent" target="_top"><rect x="116" y="1" width="120" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="176" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">messageevent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor messageevent() creates a new messageevent.
...both scripts contain this: var myworker = new sharedworker('worker.js'); both scripts then access the worker through a messageport object created using the sharedworker.port property.
Metadata.modificationTime - Web APIs
if it was last modified in a year at least five prior to the current year, the file is removed and a new one is created.
... workingdirectory.getfile("tmp/workfile.json", { create: true }, function(fileentry) { fileentry.getmetadata(function(metadata) { if ((new date().getfullyear() - metadata.modificationtime.getfullyear()) >= 5) { fileentry.remove(function() { workingdirectory.getfile("tmp/workfile.json", { create: true }, function(newentry) { fileentry = newentry; }); }); } }); }, handleerror); this api has no official w3c or whatwg specification.
MouseEvent - Web APIs
seevent" target="_top"><rect x="231" y="1" width="100" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="281" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">mouseevent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor mouseevent() creates a mouseevent object.
... mouseevent.initmouseevent() initializes the value of a mouseevent created.
MutationObserver.MutationObserver() - Web APIs
the dom mutationobserver() constructor — part of the mutationobserver interface — creates and returns a new observer which invokes a specified callback when dom events occur.
... example this example simply creates a new mutationobserver configured to watch a node and all of its children for additions and removals of elements to the tree, as well as any changes to attributes on any of the elements in the tree.
MutationObserver - Web APIs
constructor mutationobserver() creates and returns a new mutationobserver which will invoke a specified callback function when dom changes occur.
...on(mutationslist, observer) { // use traditional 'for loops' for ie 11 for(let mutation of mutationslist) { if (mutation.type === 'childlist') { console.log('a child node has been added or removed.'); } else if (mutation.type === 'attributes') { console.log('the ' + mutation.attributename + ' attribute was modified.'); } } }; // create an observer instance linked to the callback function const observer = new mutationobserver(callback); // start observing the target node for configured mutations observer.observe(targetnode, config); // later, you can stop observing observer.disconnect(); specifications specification status comment domthe definition of 'mutationobserver' in that specification.
Navigator.requestMediaKeySystemAccess() - Web APIs
the navigator.requestmediakeysystemaccess() method returns a promise which delivers a mediakeysystemaccess object that can be used to access a particular media key system, which can in turn be used to create keys for decrypting a media stream.
...as a general rule, this function should be called only when it's about time to create and use a mediakeys object by calling the returned mediakeysystemaccess object's createmediakeys() method.
navigator.hardwareConcurrency - Web APIs
examples in this example, one worker is created for each logical processor reported by the browser and a record is created which includes a reference to the new worker as well as a boolean value indicating whether or not we're using that worker yet; these objects are, in turn, stored into an array for later use.
... this creates a pool of workers we can use to process requests later.
Node.appendChild() - Web APIs
WebAPINodeappendChild
notes chaining may not work as expected, due to appendchild() returning the child element: let ablock = document.createelement('block').appendchild( document.createelement('b') ); sets ablock to <b></b> only, which is probably not what you want.
... example // create a new paragraph element, and append it to the end of the document body let p = document.createelement("p"); document.body.appendchild(p); specifications specification status comment domthe definition of 'node.appendchild()' in that specification.
Node.isConnected - Web APIs
WebAPINodeisConnected
examples standard dom a standard dom example: let test = document.createelement('p'); console.log(test.isconnected); // returns false document.body.appendchild(test); console.log(test.isconnected); // returns true shadow dom a shadow dom example: // create a shadow root var shadow = this.attachshadow({mode: 'open'}); // create some css to apply to the shadow dom var style = document.createelement('style'); console.log(style.isconnected); // returns false style.t...
...extcontent = ` .wrapper { position: relative; } .info { font-size: 0.8rem; width: 200px; display: inline-block; border: 1px solid black; padding: 10px; background: white; border-radius: 10px; opacity: 0; transition: 0.6s all; positions: absolute; bottom: 20px; left: 10px; z-index: 3 } `; // attach the created style element to the shadow dom shadow.appendchild(style); console.log(style.isconnected); // returns true polyfill node.isconnected can be polyfilled with the following code for ie10 and edgehtml: /* * node.isconnected polyfill for ie and edgehtml * 2020-02-04 * * by eli grey, https://eligrey.com * public domain.
Node.replaceChild() - Web APIs
WebAPINodereplaceChild
example // given: // <div> // <span id="childspan">foo bar</span> // </div> // create an empty element node // without an id, any attributes, or any content var sp1 = document.createelement("span"); // give it an id attribute called 'newspan' sp1.id = "newspan"; // create some content for the new element.
... var sp1_content = document.createtextnode("new replacement span element."); // apply that content to the new element sp1.appendchild(sp1_content); // build a reference to the existing node to be replaced var sp2 = document.getelementbyid("childspan"); var parentdiv = sp2.parentnode; // replace existing node sp2 with the new span element sp1 parentdiv.replacechild(sp1, sp2); // result: // <div> // <span id="newspan">new replacement span element.</span> // </div> specifications specification status comment domthe definition of 'node: replacechild' in that specification.
Node.setUserData() - Web APIs
WebAPINodesetUserData
the handler will be passed five arguments: an operation type integer (e.g., 1 to indicate a clone operation), the user key, the data on the node, the source node (null if being deleted), the destination node (the newly created node or null if none).if no handler is desired, one must specify null.
... example var d = document.implementation.createdocument('', 'test', null); d.documentelement.setuserdata('key', 15, {handle:function (o, k, d, s, ds) {console.log(o+'::'+k+'::'+d+'::'+s+'::'+ds)}}); // 2::key::15::[object element]::[object element] console.log(d.documentelement.getuserdata('key')); // 15 var e = document.importnode(d.documentelement, true); // causes handler to be called console.log(e.getuserdata('key')); // null since user data is not copied specifications specification status comment document object model (dom) level 3 core specificationthe definition of 'node.setuserdata...
NodeIterator - Web APIs
syntax a nodeiterator can be created using the document.createnodeiterator() method, as follows: const nodeiterator = document.createnodeiterator(root, whattoshow, filter); properties this interface doesn't inherit any property.
... nodeiterator.root read only returns a node representing the root node as specified when the nodeiterator was created.
Notification.Notification() - Web APIs
the notification() constructor creates a new notification object instance, which represents a user notification.
...the function is passed parameters to specify the body, icon, and title we want, and then it creates the necessary options object and triggers the notification by using the notification() constructor.
Notification.timestamp - Web APIs
the notification's timestamp can represent the time, in milliseconds since 00:00:00 utc on 1 january 1970, of the event for which the notification was created, or it can be an arbitrary timestamp that you want associated with the notification.
... examples the following snippet fires a notification; a simple options object is created, then the notification is fired using the notification() constructor.
OES_vertex_array_object - Web APIs
ext.createvertexarrayoes() creates a new webglvertexarrayobject.
... examples var oes_vao_ext = gl.getextension('oes_vertex_array_object'); var vao = oes_vao_ext.createvertexarrayoes(); oes_vao_ext.bindvertexarrayoes(vao); // ...
OfflineAudioCompletionEvent.OfflineAudioCompletionEvent() - Web APIs
the offlineaudiocompletionevent() constructor of the web audio api creates a new offlineaudiocompletionevent object instance.
... syntax var offlineaudiocompletionevent = new offlineaudiocompletionevent(type, init) parameters type optional a domstring representing the type of object to create.
OscillatorNode.OscillatorNode() - Web APIs
the oscillatornode() constructor of the web audio api creates a new oscillatornode object which is an audionode that represents a periodic waveform, like a sine wave, optionally setting the node's properties' values to match values in a specified object.
... if the default values of the properties are acceptable, you can optionally use the audiocontext.createoscillator() factory method instead.
OscillatorNode.start() - Web APIs
example the following example shows basic usage of an audiocontext to create an oscillator node.
... // create web audio api context var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); // create oscillator node var oscillator = audioctx.createoscillator(); oscillator.type = 'square'; oscillator.frequency.setvalueattime(3000, audioctx.currenttime); // value in hertz oscillator.start(); specifications specification status comment web audio apithe definition of 'start' in that specification.
OscillatorNode.stop() - Web APIs
example the following example shows basic usage of an audiocontext to create an oscillator node.
... // create web audio api context var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); // create oscillator node var oscillator = audioctx.createoscillator(); oscillator.connect(audioctx.destination); oscillator.start(); oscillator.stop(audioctx.currenttime + 2); // stop 2 seconds after the current time specifications specification status comment web audio apithe definition of 'stop' in that specification.
OscillatorNode.type - Web APIs
example the following example shows basic usage of an audiocontext to create an oscillator node.
... // create web audio api context var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); // create oscillator node var oscillator = audioctx.createoscillator(); oscillator.type = 'square'; oscillator.frequency.setvalueattime(440, audioctx.currenttime); // value in hertz oscillator.start(); specifications specification status comment web audio apithe definition of 'type' in that specification.
PannerNode.coneInnerAngle - Web APIs
syntax var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.coneinnerangle = 360; value a double.
...they range between -1 and 1 const x = math.cos(radians); const z = math.sin(radians); // we hard-code the y component to 0, as y is the axis of rotation return [x, 0, z]; }; now we can create our audiocontext, an oscillator and a pannernode: const context = new audiocontext(); const osc = new oscillatornode(context); osc.type = 'sawtooth'; const panner = new pannernode(context); panner.panningmodel = 'hrtf'; next, we set up the cone of our spatialised sound, determining the area in which it can be heard: // this value determines the size of the area in which the sound volume is c...
PannerNode.coneOuterAngle - Web APIs
syntax var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.coneouterangle = 0; value a double.
...they range between -1 and 1 const x = math.cos(radians); const z = math.sin(radians); // we hard-code the y component to 0, as y is the axis of rotation return [x, 0, z]; }; now we can create our audiocontext, an oscillator and a pannernode: const context = new audiocontext(); const osc = new oscillatornode(context); osc.type = 'sawtooth'; const panner = new pannernode(context); panner.panningmodel = 'hrtf'; next, we set up the cone of our spatialised sound, determining the area in which it can be heard: // this value determines the size of the area in which the sound volume is c...
PannerNode.coneOuterGain - Web APIs
syntax var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.coneoutergain = 0; value a double.
...they range between -1 and 1 const x = math.cos(radians); const z = math.sin(radians); // we hard-code the y component to 0, as y is the axis of rotation return [x, 0, z]; }; now we can create our audiocontext, an oscillator and a pannernode: const context = new audiocontext(); const osc = new oscillatornode(context); osc.type = 'sawtooth'; const panner = new pannernode(context); panner.panningmodel = 'hrtf'; next, we set up the cone of our spatialised sound, determining the area in which it can be heard: // this value determines the size of the area in which the sound volume is c...
PannerNode.refDistance - Web APIs
syntax var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.refdistance = 1; value a non-negative number.
... const context = new audiocontext(); // all our test tones will last this many seconds const note_length = 6; // this is how far we'll move the sound const z_distance = 20; // this function creates a graph for the test tone with a given refdistance // and schedules it to move away from the listener along the z (depth-wise) axis // at the given start time, resulting in a decrease in volume (decay) const scheduletesttone = (refdistance, starttime) => { const osc = new oscillatornode(context); const panner = new pannernode(context); panner.refdistance = refdistance; // set the initi...
PannerNode.rolloffFactor - Web APIs
syntax var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.rollofffactor = 1; value a number whose range depends on the distancemodel of the panner as follows (negative values are not allowed): "linear" the range is 0 to 1.
... example this example demonstrates how different rollofffactor values affect how the volume of the test tone decreases with increasing distance from the listener: const context = new audiocontext(); // all our test tones will last this many seconds const note_length = 4; // this is how far we'll move the sound const z_distance = 20; // this function creates a graph for the test tone with a given rollofffactor // and schedules it to move away from the listener along the z (depth-wise) axis // at the given start time, resulting in a decrease in volume (decay) const scheduletesttone = (rollofffactor, starttime) => { const osc = new oscillatornode(context); const panner = new pannernode(context); panner.rollofffactor = rollofffactor; // set t...
PasswordCredential.additionalData - Web APIs
example the following example creates a formdata object with an appended csrf token.
... //the options object was previously created.
Path2D - Web APIs
WebAPIPath2D
creates a new path2d object.
... path2d.rect() creates a path for a rectangle at position (x, y) with a size that is determined by width and height.
PaymentMethodChangeEvent - Web APIs
the paymentmethodchangeevent() constructor creates a new paymentmethodchangeevent object providing details about a paymentmethodchange event.
... return value a newly-created paymentmethodchangeevent object describing a change to the options specified for the payment method given in the methodname property.
PaymentRequest: paymentmethodchange event - Web APIs
this code creates a new paymentrequest, adds a handler for the paymentmethodchange event by calling the request's addeventlistener(), then calls show() to present the payment interface to the user.
...ple.com/apple-pay") { const servicefeeinfo = calculateservicefee(event.methoddetails); object.assign(detailsupdate, servicefeeinfo); } event.updatewith(detailsupdate); }, false); this begins by looking at the event's methodname property; if that indicates that the user is trying to use apple pay, we pass the methoddetails into a function called calculateservicefee(), which we might create to take the information about the transaction, such as the underlying credit card being used to service the apple pay request, and compute and return an paymentdetailsupdate object that specifies changes to be applied to the paymentrequest in order to add any service fees that the payment method might require.
Using the Payment Request API - Web APIs
so for example, you could create a new paymentrequest instance like so: var request = new paymentrequest(buildsupportedpaymentmethoddata(), buildshoppingcartdetails()); the functions invoked inside the constructor simply return the required object parameters: function buildsupportedpaymentmethoddata() { // example supported payment methods: return [{ supportedmethods: 'basic-card', ...
...}]; } function buildshoppingcartdetails() { // hardcoded for demo purposes: return { id: 'order-123', displayitems: [ { label: 'example item', amount: {currency: 'usd', value: '1.00'} } ], total: { label: 'total', amount: {currency: 'usd', value: '1.00'} } }; } starting the payment process once the paymentrequest object has been created, you call the paymentrequest.show() method on it to initiate the payment request.
performance.clearMarks() - Web APIs
// create a small helper to show how many performancemark entries there are.
... function logmarkcount() { console.log( "found this many entries: " + performance.getentriesbytype("mark").length ); } // create a bunch of marks.
performance.clearMeasures() - Web APIs
// create a small helper to show how many performancemeasure entries there are.
... function logmeasurecount() { console.log( "found this many entries: " + performance.getentriesbytype("measure").length ); } // create a bunch of measures.
performance.getEntries() - Web APIs
the list's members (entries) can be created by making performance marks or measures (for example by calling the mark() method) at explicit points in time.
...performance.mark not supported"); return; } // create some performance entries via the mark() method performance.mark("begin"); do_work(50000); performance.mark("end"); performance.mark("begin"); do_work(100000); performance.mark("end"); do_work(200000); performance.mark("end"); // use getentries() to iterate through the each entry let p = performance.getentries(); for (var i=0; i < p.length; i++) { console.log("entry[" + ...
performance.getEntriesByName() - Web APIs
the list's members (entries) can be created by making performance marks or measures (for example by calling the mark() method) at explicit points in time.
...performance.mark not supported"); return; } // create some performance entries via the mark() method performance.mark("begin"); do_work(50000); performance.mark("end"); performance.mark("begin"); do_work(100000); performance.mark("end"); do_work(200000); performance.mark("end"); // use getentries() to iterate through the each entry var p = performance.getentries(); for (var i=0; i < p.length; i++) { log("entry[" + i + "]")...
performance.getEntriesByType() - Web APIs
the list's members (entries) can be created by making performance marks or measures (for example by calling the mark() method) at explicit points in time.
...performance.mark not supported"); return; } // create some performance entries via the mark() method performance.mark("begin"); dowork(50000); performance.mark("end"); performance.mark("begin"); dowork(100000); performance.mark("end"); dowork(200000); performance.mark("end"); // use getentries() to iterate through the each entry var p = performance.getentries(); for (var i=0; i < p.length; i++) { log("entry[" + i + "]"); ...
performance.now() - Web APIs
WebAPIPerformancenow
bear in mind the following points: in dedicated workers created from a window context, the value in the worker will be lower than performance.now() in the window who spawned that worker.
... in shared or service workers, the value in the worker might be higher than that of the main context because that window can be created after those workers.
PerformanceEntry - Web APIs
a performance entry can be directly created by making a performance mark or measure (for example by calling the mark() method) at an explicit point in an application.
... performance entries are also created in indirect ways such as loading a resource (such as an image).
PerformanceMark - Web APIs
entries of this type are created by calling performance.mark() to add a named domhighrestimestamp (the mark) to the browser's performance timeline.
... performanceentry.name returns the name given to the mark when it was created via a call to performance.mark().
PerformanceMeasure - Web APIs
entries of this type are created by calling performance.measure() to add a named domhighrestimestamp (the measure) between two marks to the browser's performance timeline.
... performanceentry.name returns the name given to the measure when it was created via a call to performance.measure().
Performance Timeline - Web APIs
this interface has the following four properties, and these properties are extended (with additional constraints) by other interfaces (such as performancemark): name the name of the performance entry when the metric was created.
... performance observers the performance observer interfaces allow an application to register an observer for specific performance event types, and when one of those event types is recorded, the application is notified of the event via the observer's callback function that was specified when the observer was created.
Pointer events - Web APIs
they are designed to create a single dom event model to handle pointing input devices such as a mouse, pen/stylus or touch (such as one or more fingers).
... #target { touch-action: pan-x; } compatibility with mouse events although the pointer event interfaces enable applications to create enhanced user experiences on pointer enabled devices, the reality is the vast majority of today's web content is designed to only work with mouse input.
ProgressEvent - Web APIs
t" target="_top"><rect x="116" y="1" width="130" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="181" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">progressevent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor progressevent() creates a progressevent event with the given parameters.
... progressevent.initprogressevent() initializes a progressevent created using the deprecated document.createevent("progressevent") method.
PromiseRejectionEvent() - Web APIs
the promiserejectionevent() constructor returns a newly created promiserejectionevent, which represents events fired when a javascript promise is rejected.
... examples this example creates a new unhandledrejection event for the promise mypromise with the reason being the string "my house is on fire".
PublicKeyCredential.getClientExtensionResults() - Web APIs
during the creation or fetching of a publickeycredential (respectively via navigator.credentials.create() and navigator.credentials.get()), it is possible to have "custom" processing by the client for different extensions which are respectively given by publickeycredentialcreationoptions.extensions and publickeycredentialrequestoptions.extensions.
...rification index: how the user was verified }, challenge: new uint8array(16) /* from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(16) /* from the server */, name: "jdoe@example.com", displayname: "john doe" }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { var mybuffer = newcredentialinfo.getclientextensionresults(); // mybuffer will contain the result of any of the processing of the "loc" and "uvi" extensions }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public...
PublicKeyCredential.response - Web APIs
an authenticatorresponse is either: an authenticatorattestationresponse (when the publickeycredential is created via credentialscontainer.create()) an authenticatorassertionresponse (when the publickeycredential is obtained via credentialscontainer.get()).
... examples var options = { challenge: new uint8array(16) /* from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(16) /* from the server */, name: "jdoe@example.com", displayname: "john doe" }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey: options }) .then(function (pubkeycredential) { var response = pubkeycredential.response; var clientextresults = pubkeycredential.getclientextensionresults(); // send response and client extensions to the server so that it can validate // and create credentials }).catch(function (err) { // deal with any error }); specifications specification status...
PublicKeyCredentialCreationOptions.rp - Web APIs
the rp property of the publickeycredentialcreationoptions dictionary is an object describing the relying party which requested the credential creation (via navigator.credentials.create()).
... examples var publickey = { challenge: /* from the server */, rp: { name: "example corp", id : "login.example.com", icon: "https://login.example.com/login.ico" }, user: { id: new uint8array(16), name: "jdoe@example.com", displayname: "john doe" }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { // send attestation response and client extensions // to the server to proceed with the registration // of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the def...
PublicKeyCredentialCreationOptions.user - Web APIs
the user property of the publickeycredentialcreationoptions dictionary is an object describing the user account for which the credentials are generated (via navigator.credentials.create()).
...ple corp", id : "login.example.com" }, user: { // to be changed for each user id: new uint8array.from(window.atob("laegmlkjnrlkgnamlafalfka="), c=>c.charcodeat(0)); name: "jdoe@example.com", displayname: "john doe", icon: "https://gravatar.com/avatar/jdoe.png" }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { // send attestation response and client extensions // to the server to proceed with the registration // of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the def...
RTCAnswerOptions - Web APIs
the rtcansweroptions dictionary is used to provide optional settings when creating an sdp answer using rtcpeerconnection.createoffer() after receiving an offer from a remote peer.
... the createoffer() method's options parameter is of this type.
RTCConfiguration.bundlePolicy - Web APIs
max-compat the ice agent intially creates one rtcdtlstransport for each media track and a separate one for the rtcdatachannel, if one is created.
... examples the following example creates a new rtcpeerconnection with a configuration setting the connection's bundlepolicy to max-compat to maximize compatibility while attempting to optimize network use.
RTCDTMFToneChangeEvent.RTCDTMFToneChangeEvent() - Web APIs
the rtcdtmftonechangeevent() constructor creates a new rtcdtmftonechangeevent.
... return value a newly-created rtcdtmftonechangeevent, configured as specified in the provided options.
RTCDataChannel: bufferedamountlow event - Web APIs
let pc = new rtcpeerconnection(); let dc = pc.createdatachannel("sendfile"); let source = /* source data object */ dc.bufferedamountlowthreshold = 65536; pc.addeventlistener("bufferedamountlow", ev => { if (source.position <= source.length) { dc.send(source.readfile(65536)); } }, false); after creating the rtcpeerconnection, this calls rtcpeerconnection.createdatachannel() to create the data channel.
... then a listener is created for bufferedamountlow to refill the incoming data buffer any time its contents fall below 65536 bytes.
RTCDataChannel.id - Web APIs
WebAPIRTCDataChannelid
this id is set at the time the data channel is created, either by the user agent (if rtcdatachannel.negotiated is false) or by the site or app script (if negotiated is true).
... example var pc = new rtcpeerconnection(); var dc = pc.createdatachannel("my channel"); console.log("channel id: " + dc.id); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdatachannel.id' in that specification.
RTCDataChannel.maxPacketLifeTime - Web APIs
the read-only rtcdatachannel property maxpacketlifetime returns the amount of time, in milliseconds, the browser is allowed to take to attempt to transmit a message, as set when the data channel was created, or null.
...if not set when rtcpeerconnection.createdatachannel() was called to create the data channel, this value is null.
RTCDataChannel.onclose - Web APIs
example in this sample from a hypothetical instant messaging client, a data channel is created, then handlers for the open and close events are set up to enable and disable user interface objects based on the state of the channel.
... let pc = new rtcpeerconnection(); let dc = pc.createdatachannel("messagechannel")}}; dc.onopen = function(event) { document.getelementbyid("messagebox").disabled = false; document.getelementbyid("sendbutton").disabled = false; }; dc.onclose = function(event) { document.getelementbyid("messagebox").disabled = true; document.getelementbyid("sendbutton").disabled = true; } /* now negotiate the connection, etc...
RTCDataChannel.onmessage - Web APIs
example this code snippet creates a peer connection, adds a data channel to it, and starts creating new <p> (paragraph) elements each time a message arrives, with the message's contents displayed inside it.
... let pc = new rtcpeerconnection(); let dc = pc.createdatachannel(); dc.onmessage = function(event) { var el = document.createelement("p"); var txtnode = document.createtextnode(event.data); el.appendchild(txtnode); receivebox.appendchild(el); } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdatachannel.onmessage' in that specification.
RTCDataChannel.ordered - Web APIs
this is set when the rtcdatachannel is created, by setting the ordered property on the rtcdatachannelinit object passed as rtcpeerconnection.createdatachannel()'s options parameter.
... example var pc = new rtcpeerconnection(); var dc = pc.createdatachannel("my channel"); if (!dc.ordered) { // handle unordered messaging } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdatachannel.ordered' in that specification.
RTCDataChannel.protocol - Web APIs
if no protocol was specified when the data channel was created, then this property's value is "" (the empty string).
... example var pc = new rtcpeerconnection(); var dc = pc.createdatachannel("my channel", { protocol: "json" }); function handlechannelmessage(datachannel, msg) { switch(datachannel.protocol) { case "json": /* process json data */ break; case "raw": /* process raw binary data */ break; } } specifications specification status comment webrtc 1.0: real-time communication between browser...
RTCDataChannel.send() - Web APIs
example in this example, a routine called sendmessage() is created; it accepts an object as input and sends to the remote peer, over the rtcdatachannel, a json string with the specified object and a time stamp.
... var pc = new rtcpeerconnection(); var dc = pc.createdatachannel("backchannel"); function sendmessage(msg) { let obj = { "message": msg, "timestamp": new date() } dc.send(json.stringify(obj)); } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdatachannel.send()' in that specification.
RTCDataChannel.stream - Web APIs
this id is set at the time the data channel is created, either by the user agent (if rtcdatachannel.negotiated is false) or by the site or app script (if negotiated is true).
... example var datachannel = pc.createdatachannel("samplechannel"); console.log("data channel stream id: " + datachannel.stream); ...
RTCIceCandidate.RTCIceCandidate() - Web APIs
the rtcicecandidate() constructor creates and returns a new rtcicecandidate object, which can be configured to represent a single ice candidate.
... return value a newly-created rtcicecandidate object, optionally configured based on the specified object based on the rtcicecandidateinit dictionary.
RTCOfferOptions.iceRestart - Web APIs
pc.oniceconnectionstatechange = function(evt) { if (pc.iceconnectionstate === "failed") { if (pc.restartice) { pc.restartice(); } else { pc.createoffer({ icerestart: true }) .then(pc.setlocaldescription) .then(sendoffertoserver); } } } if the state changes to failed, this handler starts by looking to see if the rtcpeerconnection includes the restartice() method; if it does, we call that to request an ice restart.
... otherwise, we call back to the older technique: we manually create a new offer with icerestart set to true, then that offer is set as the new local description for the connection.
RTCOfferOptions - Web APIs
the rtcofferoptions dictionary is used to provide optional settings when creating an rtcpeerconnection offer with the createoffer() method.
... icerestart optional a boolean which, when set to true, tells createoffer() to generate and use new values for the identifying properties of the sdp it creates, resulting in a request that triggers renegotiation of the ice connection.
RTCPeerConnection() - Web APIs
the rtcpeerconnection() constructor returns a newly-created rtcpeerconnection, which represents a connection between the local device and a remote peer.
... return value a newly-created rtcpeerconnection object, configured as described by configuration, if specified; otherwise, configured to appropriate basic defaults.
RTCPeerConnection.close() - Web APIs
make sure that you delete all references to the previous rtcpeerconnection before attempting to create a new one that connects to the same remote peer, as not doing so might result in some errors depending on the browser.
... example var pc = new rtcpeerconnection(); var dc = pc.createdatachannel("my channel"); dc.onmessage = function (event) { console.log("received: " + event.data); pc.close(); // we decided to close after the first received message }; dc.onopen = function () { console.log("datachannel open"); }; dc.onclose = function () { console.log("datachannel close"); }; specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnection.close()' in that specification.
RTCPeerConnection: datachannel event - Web APIs
a datachannel event is sent to an rtcpeerconnection instance when an rtcdatachannel has been added to the connection, as a result of the remote peer calling rtcpeerconnection.createdatachannel().
... note: this event is not dispatched when the local end of the connection creates the channel.
RTCPeerConnection.getStats() - Web APIs
example this example creates a periodic function using setinterval() that collects statistics for an rtcpeerconnection every second, generating an html-formatted report and inserting it into a specific element in the dom.
...a section is created for each report with a header and all of the statistics below, with the type, id, and timestamp handled specially to place them at the top of the list.
RTCPeerConnection.peerIdentity - Web APIs
if there isn't already a target peer identity, peeridentity is set to a newly created promise and the process begins again, until the process succeeds or no further attempts to authenticate occur.
... example in this example, a function, getidentityassertion(), is created which asynchronously waits for the peer's identity to be verified, then returns the identity to the caller.
RTCPeerConnection.setConfiguration() - Web APIs
var restartconfig = { iceservers: [{ urls: "turn:asia.myturnserver.net", username: "allie@oopcode.com", credential: "topsecretpassword" }] }; mypeerconnection.setconfiguration(restartconfig); mypeerconnection.createoffer({"icerestart": true}).then(function(offer) { return mypeerconnection.setlocaldescription(offer); }) .then(function() { // send the offer to the other peer using the signaling server }) .catch(reporterror); first, a new rtcconfiguration is created, restartconfig, specifying the new ice server and its credentials.
...ice negotiation is restarted by calling createoffer(), specifying true as the value of the icerestart option.
RTCPeerConnectionIceErrorEvent - Web APIs
constructor rtcpeerconnectioniceerrorevent() creates and returns a new rtcpeerconnectioniceerrorevent object, with its type and other properties initialized as specified in the parameters.
... you will not normally create an object of this type yourself.
RTCPeerConnectionIceEvent() - Web APIs
the rtcpeerconnectioniceevent() constructor creates a new rtcpeerconnectioniceevent.
... return value a newly-created rtcpeerconnectioniceevent, configured as specified in the provided options.
RTCRtpReceiver.transport - Web APIs
description when the rtcrtpreceiver is first created, the value of transport is null.
... note that when bundling is in effect—that is, when the rtcpeerconnection was created with an rtcconfiguration object whose bundlepolicy is max-compat or max-bundle—multiple receivers may be sharing the same transport; in this case, all of them are using the same connection to transmit and/or receive rtp and rtcp packets.
RTCRtpSender.setParameters() - Web APIs
you cannot change the number of encoding options once the sender has been created.
... an attempt has been made to alter a property that cannot be changed after the sender is first created.
RTCRtpSender.transport - Web APIs
description when the rtcrtpsender is first created, the value of transport is null.
... note that when bundling is in effect—that is, when the rtcpeerconnection was created with an rtcconfiguration object whose bundlepolicy is max-compat or max-bundle—multiple senders may be sharing the same transport; in this case, all of them are using the same connection to transmit and/or receive rtp and rtcp packets.
RTCSessionDescription() - Web APIs
the rtcsessiondescription() constructor creates a new rtcsessiondescription with its properties initialized as described in the specified object.
... navigator.getusermedia({video: true}, function(stream) { pc.onaddstream({stream: stream}); // adding a local stream won't trigger the onaddstream callback pc.addstream(stream); pc.createoffer(function(offer) { pc.setlocaldescription(new rtcsessiondescription(offer), function() { // send the offer to a server to be forwarded to the friend you're calling.
RTCTrackEvent() - Web APIs
the rtctrackevent() constructor creates and returns a new rtctrackevent object, configured to describe the track which has been added to the rtcpeerconnection.
... in general, you won't need to use this constructor, as rtctrackevent objects are created by webrtc and delivered to your rtcpeerconnector's ontrack event handler as appropriate.
Range.commonAncestorContainer - Web APIs
syntax rangeancestor = range.commonancestorcontainer; example in this example, we create an event listener to handle pointerup events on a list.
... html <ul> <li>strings <ul> <li>cello</li> <li>violin <ul> <li>first chair</li> <li>second chair</li> </ul> </li> </ul> </li> <li>woodwinds <ul> <li>clarinet</li> <li>oboe</li> </ul> </li> </ul> css the .highlight class created below uses a set of css @keyframes to animate a fading outline.
Range.compareNode() - Web APIs
WebAPIRangecompareNode
the following function can be used as replacement: function rangecomparenode(range, node) { var noderange = node.ownerdocument.createrange(); try { noderange.selectnode(node); } catch (e) { noderange.selectnodecontents(node); } var nodeisbefore = range.compareboundarypoints(range.start_to_start, noderange) == 1; var nodeisafter = range.compareboundarypoints(range.end_to_end, noderange) == -1; if (nodeisbefore && !nodeisafter) return 0; if (!nodeisbefore && nodeisafter) return 1; if (nodeisbefo...
... example range = document.createrange(); range.selectnode(document.getelementsbytagname("div").item(0)); returnvalue = range.comparenode(document.getelementsbytagname("p").item(0)); notes this method is obsolete; you should use the w3c dom range.compareboundarypoints() method.
Range.getClientRects() - Web APIs
this is created by aggregating the results of calls to element.getclientrects() for all the elements in the range.
... syntax rectlist = range.getclientrects() example range = document.createrange(); range.selectnode(document.getelementsbytagname("div").item(0)); rectlist = range.getclientrects(); specification specification status comment css object model (cssom) view modulethe definition of 'range.getclientrects()' in that specification.
ReadableStream.pipeThrough() - Web APIs
next, we log the contents of the readable stream, use pipethrough() to send it to a new function that creates a gray-scaled version of the stream, then log the new stream's contents too.
... // fetch the original image fetch('png-logo.png') // retrieve its body as readablestream .then(response => response.body) .then(rs => logreadablestream('fetch response stream', rs)) // create a gray-scaled png stream out of the original .then(body => body.pipethrough(new pngtransformstream())) .then(rs => logreadablestream('png chunk stream', rs)) specifications specification status comment streamsthe definition of 'pipethrough()' in that specification.
ReadableStream.tee() - Web APIs
examples in the following simple example, a previously-created stream is teed, then both resulting streams (contained in two members of a generated array) are passed to a function that reads the data out of the two streams and prints each stream's chunks sequentially to a different part of the ui.
... if (done) { console.log("stream complete"); return; } // value for fetch streams is a uint8array charsreceived += value.length; const chunk = value; let listitem = document.createelement('li'); listitem.textcontent = 'read ' + charsreceived + ' characters so far.
ReadableStreamDefaultController.close() - Web APIs
examples in the following simple example, a custom readablestream is created using a constructor (see our simple random stream example for the full code).
... const stream = new readablestream({ start(controller) { interval = setinterval(() => { let string = randomchars(); // add the string to the stream controller.enqueue(string); // show it on the screen let listitem = document.createelement('li'); listitem.textcontent = string; list1.appendchild(listitem); }, 1000); button.addeventlistener('click', function() { clearinterval(interval); fetchstream(); controller.close(); }) }, pull(controller) { // we don't really need a pull in this example }, cancel() { // this is called if the reader cancels, // so we should sto...
ReadableStreamDefaultController.enqueue() - Web APIs
examples in the following simple example, a custom readablestream is created using a constructor (see our simple random stream example for the full code).
... const stream = new readablestream({ start(controller) { interval = setinterval(() => { let string = randomchars(); // add the string to the stream controller.enqueue(string); // show it on the screen let listitem = document.createelement('li'); listitem.textcontent = string; list1.appendchild(listitem); }, 1000); button.addeventlistener('click', function() { clearinterval(interval); fetchstream(); controller.close(); }) }, pull(controller) { // we don't really need a pull in this example }, cancel() { // this is called if the reader cancels, // so we should sto...
ReadableStreamDefaultReader.cancel() - Web APIs
examples in the following simple example, a previously-created custom readablestream is read using a readablestreamdefaultreader created using getreader().
... if (done) { console.log("stream complete"); reader.cancel(); para.textcontent = result; return; } // value for fetch streams is a uint8array charsreceived += value.length; const chunk = value; let listitem = document.createelement('li'); listitem.textcontent = 'received ' + charsreceived + ' characters so far.
ReadableStreamDefaultReader - Web APIs
constructor readablestreamdefaultreader() creates and returns a readablestreamdefaultreader object instance.
... examples in the following example, an artifical response is created to stream html fragments fetched from another resource to the browser.
ReportingObserver() - Web APIs
the reportingobserver() constructor of the reporting api creates a new reportingobserver object instance, which can be used to collect and access reports.
... buffered: a boolean that defines whether the reports that were generated before the observer was able to be created should be observable (true) or not (false).
ReportingObserver - Web APIs
constructor reportingobserver() creates a new reportingobserver object instance, which can be used to collect and access reports.
... examples in our deprecation_report.html example, we create a simple reporting observer to observe usage of deprecated features on our web page: let options = { types: ['deprecation'], buffered: true } let observer = new reportingobserver(function(reports, observer) { reportbtn.onclick = () => displayreports(reports); }, options); we then tell it to start observing reports using reportingobserver.observe(); this tells the observer to start collec...
Request.clone() - Web APIs
WebAPIRequestclone
the clone() method of the request interface creates a copy of the current request object.
... example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then clone the request.
Request.redirect - Web APIs
WebAPIRequestredirect
syntax var myredirect = request.redirect; value a requestredirect enum value, which can be one the following strings: follow error manual if not specified when the request is created, it takes the default value of follow.
... example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request redirect value in a variable: var myrequest = new request('flowers.jpg'); var mycred = myrequest.redirect; specifications specification status comment fetchthe definition of 'redirect' in that specification.
ResizeObserver - Web APIs
resizeobserver avoids infinite callback loops and cyclic dependencies that are often created when resizing via a callback function.
... constructor resizeobserver() creates and returns a new resizeobserver object.
Response() - Web APIs
WebAPIResponseResponse
the response() constructor creates a new response object.
... examples in our fetch response example (see fetch response live) we create a new response object using the constructor, passing it a new blob as a body, and an init object containing a custom status and statustext: var myblob = new blob(); var init = { "status" : 200 , "statustext" : "supersmashinggreat!" }; var myresponse = new response(myblob,init); specifications specification status comment fetchthe definition of 'response()' in that speci...
Response.redirected - Web APIs
fetch("awesome-picture.jpg").then(function(response) { let elem = document.getelementbyid("warning-message-box"); if (response.redirected) { elem.innerhtml = "unexpected redirect"; } else { elem.innerhtml = ""; } return response.blob(); }).then(function(imageblob) { let imgobjecturl = url.createobjecturl(imageblob); document.getelementbyid("img-element-id").src = imgobjecturl; }); disallowing redirects because using redirected to manually filter out redirects can allow forgery of redirects, you should instead set the redirect mode to "error" in the init parameter when calling fetch(), like this: fetch("awesome-picture.jpg", { redirect: "error" }).then(function(response) { return ...
...response.blob(); }).then(function(imageblob) { let imgobjecturl = url.createobjecturl(imageblob); document.getelementbyid("img-element-id").src = imgobjecturl; }); specifications specification status comment fetchthe definition of 'redirected' in that specification.
SVGAnimationElement: beginEvent event - Web APIs
dur="5s" repeatcount="indefinite" /> </circle> </svg> <hr> <ul> </ul> ul { height: 100px; border: 1px solid #ddd; overflow-y: scroll; padding: 10px 30px; } let svgelem = document.queryselector('svg'); let animateelem = document.queryselector('animatemotion'); let list = document.queryselector('ul'); animateelem.addeventlistener('beginevent', () => { let listitem = document.createelement('li'); listitem.textcontent = 'beginevent fired'; list.appendchild(listitem); }) animateelem.addeventlistener('repeatevent', (e) => { let listitem = document.createelement('li'); let msg = 'repeatevent fired'; if(e.detail) { msg += '; repeat number: ' + e.detail; } listitem.textcontent = msg; list.appendchild(listitem); }) event handler property equivalent note th...
...at you can also create an event listener for the begin event using the onbegin event handler property: animateelem.onbegin = () => { console.log('beginevent fired'); } specifications specification status comment scalable vector graphics (svg) 2the definition of 'beginevent' in that specification.
SVGAnimationElement: endEvent event - Web APIs
stop animation</button> <ul> </ul> ul { height: 100px; border: 1px solid #ddd; overflow-y: scroll; padding: 10px 30px; } let svgelem = document.queryselector('svg'); let animateelem = document.queryselector('animatemotion'); let list = document.queryselector('ul'); let btn = document.queryselector('button'); animateelem.addeventlistener('beginevent', () => { let listitem = document.createelement('li'); listitem.textcontent = 'beginevent fired'; list.appendchild(listitem); }) animateelem.addeventlistener('endevent', () => { let listitem = document.createelement('li'); listitem.textcontent = 'endevent fired'; list.appendchild(listitem); }) animateelem.addeventlistener('repeatevent', (e) => { let listitem = document.createelement('li'); let msg = 'repeatevent fired'; ...
... if(e.detail) { msg += '; repeat number: ' + e.detail; } listitem.textcontent = msg; list.appendchild(listitem); }) btn.addeventlistener('click', () => { btn.disabled = true; animateelem.setattribute('repeatcount', '1'); }) event handler property equivalent note that you can also create an event listener for the end event using the onend event handler property: animateelem.onend = () => { console.log('endevent fired'); } specifications specification status comment scalable vector graphics (svg) 2the definition of 'endevent' in that specification.
SVGAnimationElement: repeatEvent event - Web APIs
dur="5s" repeatcount="indefinite" /> </circle> </svg> <hr> <ul> </ul> ul { height: 100px; border: 1px solid #ddd; overflow-y: scroll; padding: 10px 30px; } let svgelem = document.queryselector('svg'); let animateelem = document.queryselector('animatemotion'); let list = document.queryselector('ul'); animateelem.addeventlistener('beginevent', () => { let listitem = document.createelement('li'); listitem.textcontent = 'beginevent fired'; list.appendchild(listitem); }) animateelem.addeventlistener('repeatevent', (e) => { let listitem = document.createelement('li'); let msg = 'repeatevent fired'; if(e.detail) { msg += '; repeat number: ' + e.detail; } listitem.textcontent = msg; list.appendchild(listitem); }) event handler property equivalent note th...
...at you can also create an event listener for the repeat event using the onrepeat event handler property: animateelem.onrepeat = () => { console.log('repeatevent fired'); } specifications specification status comment scalable vector graphics (svg) 2the definition of 'repeatevent' in that specification.
SVGPoint - Web APIs
WebAPISVGPoint
syntax retobject = svgsvgelement.createsvgpoint() value the returned value is an svgpoint object.
... example // create an svgpoint in the user coordinate system let s = document.getelementbyid("svg-elementid").createsvgpoint(); // then, set the x and y values of the returned svgpoint object // (which is the variable `s`) s.y = 10; s.x = 10; ...
Screen Wake Lock API - Web APIs
the wakelock.request method is promise based and so we can create an asynchronous function, which in turn updates the ui to reflect the wake lock is active.
... // create a reference for the wake lock let wakelock = null; // create an async function to request a wake lock const requestwakelock = async () => { try { wakelock = await navigator.wakelock.request('screen'); // change up our interface to reflect wake lock active statuselem.textcontent = 'wake lock is active!'; } catch (err) { // if wake lock request fails - usually system related, such as battery statuselem.textcontent = `${err.name}, ${err.message}`; } } releasing wake lock the following example shows how to release the previously acquired wake lock.
ScriptProcessorNode.bufferSize - Web APIs
syntax var audioctx = new audiocontext(); var scriptnode = audioctx.createscriptprocessor(4096, 1, 1); console.log(scriptnode.buffersize); value an integer.
... note: for a full working example, see our script-processor-node github repo (also view the source code.) var myscript = document.queryselector('script'); var mypre = document.queryselector('pre'); var playbutton = document.queryselector('button'); // create audiocontext and buffer source var audioctx = new audiocontext(); source = audioctx.createbuffersource(); // create a scriptprocessornode with a buffersize of 4096 and a single input and output channel var scriptnode = audioctx.createscriptprocessor(4096, 1, 1); console.log(scriptnode.buffersize); // load in an audio track via xhr and decodeaudiodata function getdata() { request = new xmlhtt...
ScriptProcessorNode.onaudioprocess - Web APIs
syntax var audioctx = new audiocontext(); var scriptnode = audioctx.createscriptprocessor(4096, 1, 1); scriptnode.onaudioprocess = function() { ...
... note: for a full working example, see our script-processor-node github repo (also view the source code.) var myscript = document.queryselector('script'); var mypre = document.queryselector('pre'); var playbutton = document.queryselector('button'); // create audiocontext and buffer source var audioctx = new audiocontext(); source = audioctx.createbuffersource(); // create a scriptprocessornode with a buffersize of 4096 and a single input and output channel var scriptnode = audioctx.createscriptprocessor(4096, 1, 1); console.log(scriptnode.buffersize); // load in an audio track via xhr and decodeaudiodata function getdata() { request = new xmlhtt...
ScriptProcessorNode - Web APIs
the size of the input and output buffer are defined at the creation time, when the audiocontext.createscriptprocessor() method is called (both are defined by audiocontext.createscriptprocessor()'s buffersize parameter).
... note: for a full working example, see our script-processor-node github repo (also view the source code.) var myscript = document.queryselector('script'); var mypre = document.queryselector('pre'); var playbutton = document.queryselector('button'); // create audiocontext and buffer source var audioctx = new audiocontext(); source = audioctx.createbuffersource(); // create a scriptprocessornode with a buffersize of 4096 and a single input and output channel var scriptnode = audioctx.createscriptprocessor(4096, 1, 1); console.log(scriptnode.buffersize); // load in an audio track via xhr and decodeaudiodata function getdata() { request = new xmlhtt...
Selection - Web APIs
WebAPISelection
typically, it holds only one range, accessed as follows: var selobj = window.getselection(); var range = selobj.getrangeat(0); selobj is a selection object range is a range object as the selection api specification notes, the selection api was initially created by netscape and allowed multiple ranges (for instance, to allow the user to select a column from a <table>).
...range objects can also be created via the dom and programmatically added or removed from a selection.
ServiceWorkerGlobalScope.onnotificationclick - Web APIs
notifications created on the main thread or in workers which aren't service workers using the notification() constructor will instead receive a click event on the notification object itself.
... note: trying to create a notification inside the serviceworkerglobalscope using the notification() constructor will throw an error.
onnotificationclose - Web APIs
notifications created on the main thread or in workers which aren't service workers using the notification() constructor will instead receive a close event on the notification object itself.
... note: trying to create a notification inside the serviceworkerglobalscope using the notification() constructor will throw an error.
ServiceWorkerMessageEvent.ServiceWorkerMessageEvent() - Web APIs
the serviceworkermessageevent() constructor creates a new serviceworkermessageevent object instance.
... syntax var myswme = new serviceworkermessageevent(type, init); parameters type a domstring that defines the type of the message event being created.
ServiceWorkerRegistration.getNotifications() - Web APIs
the getnotifications() method of the serviceworkerregistration interface returns a list of the notifications in the order that they were created from the current origin via the current service worker registration.
...notifications created by one service worker on the same origin will not be available to other active services workers on that same origin.
ServiceWorkerRegistration.showNotification() - Web APIs
the shownotification() method of the serviceworkerregistration interface creates a notification on an active service worker.
... timestamp: a domtimestamp representing the time when the notification was created.
ShadowRoot - Web APIs
you can retrieve a reference to an element's shadow root using its element.shadowroot property, provided it was created using element.attachshadow() with the mode option set to open.
... examples the following snippets are taken from our life-cycle-callbacks example (see it live also), which creates an element that displays a square of a size and color specified in the element's attributes.
SharedWorker - Web APIs
constructors sharedworker() creates a shared web worker that executes the script at the specified url.
...both scripts contain this: var myworker = new sharedworker('worker.js'); both scripts then access the worker through a messageport object created using the sharedworker.port property.
SharedWorkerGlobalScope.name - Web APIs
the name read-only property of the sharedworkerglobalscope interface returns the name that the sharedworker was (optionally) given when it was created.
... example if a shared worker is created using a constructor with a name option: var myworker = new sharedworker("worker.js", { name : "mysharedworker" }); the sharedworkerglobalscope will now have a name of "mysharedworker", returnable by running self.name from inside the shared worker.
SharedWorkerGlobalScope - Web APIs
sharedworkerglobalscope.name read only the name that the sharedworker was (optionally) given when it was created using the sharedworker() constructor.
... windowbase64.btoa() creates a base-64 encoded ascii string from a string of binary data.
SpeechGrammarList.SpeechGrammarList() - Web APIs
the speechgrammarlist() constructor creates a new speechgrammarlist object instance.
... examples in our simple speech color changer example, we create a new speechrecognition object instance using the speechrecognition() constructor, create a new speechgrammarlist, add our grammar string to it using the speechgrammarlist.addfromstring method, and set it to be the grammar that will be recognised by the speechrecognition instance using the speechrecognition.grammars property.
SpeechGrammarList - Web APIs
constructor speechgrammarlist.speechgrammarlist() creates a new speechgrammarlist object.
... examples in our simple speech color changer example, we create a new speechrecognition object instance using the speechrecognition() constructor, create a new speechgrammarlist, add our grammar string to it using the speechgrammarlist.addfromstring method, and set it to be the grammar that will be recognised by the speechrecognition instance using the speechrecognition.grammars property.
SpeechRecognition - Web APIs
constructor speechrecognition.speechrecognition() creates a new speechrecognition object.
... examples in our simple speech color changer example, we create a new speechrecognition object instance using the speechrecognition() constructor, create a new speechgrammarlist, and set it to be the grammar that will be recognised by the speechrecognition instance using the speechrecognition.grammars property.
SpeechSynthesis: voiceschanged event - Web APIs
you can use the voiceschanged event in an addeventlistener method: var synth = window.speechsynthesis; synth.addeventlistener('voiceschanged', function() { var voices = synth.getvoices(); for(i = 0; i < voices.length ; i++) { var option = document.createelement('option'); option.textcontent = voices[i].name + ' (' + voices[i].lang + ')'; option.setattribute('data-lang', voices[i].lang); option.setattribute('data-name', voices[i].name); voiceselect.appendchild(option); } }); or use the onvoiceschanged event handler property: synth.onvoiceschanged = function() { var voices = synth.getvoices(); for(i = 0; i < voices.length ; ...
...i++) { var option = document.createelement('option'); option.textcontent = voices[i].name + ' (' + voices[i].lang + ')'; option.setattribute('data-lang', voices[i].lang); option.setattribute('data-name', voices[i].name); voiceselect.appendchild(option); } } specifications specification status comment web speech apithe definition of 'speech synthesis events' in that specification.
SpeechSynthesis - Web APIs
inside the inputform.onsubmit handler, we stop the form submitting with preventdefault(), create a new speechsynthesisutterance instance containing the text from the text <input>, set the utterance's voice to the voice selected in the <select> element, and start the utterance speaking via the speechsynthesis.speak() method.
...r voiceselect = document.queryselector('select'); var pitch = document.queryselector('#pitch'); var pitchvalue = document.queryselector('.pitch-value'); var rate = document.queryselector('#rate'); var ratevalue = document.queryselector('.rate-value'); var voices = []; function populatevoicelist() { voices = synth.getvoices(); for(i = 0; i < voices.length ; i++) { var option = document.createelement('option'); option.textcontent = voices[i].name + ' (' + voices[i].lang + ')'; if(voices[i].default) { option.textcontent += ' -- default'; } option.setattribute('data-lang', voices[i].lang); option.setattribute('data-name', voices[i].name); voiceselect.appendchild(option); } } populatevoicelist(); if (speechsynthesis.onvoiceschanged !== undefined) { spe...
SpeechSynthesisUtterance - Web APIs
inside the inputform.onsubmit handler, we stop the form submitting with preventdefault(), use the constructor to create a new utterance instance containing the text from the text <input>, set the utterance's voice to the voice selected in the <select> element, and start the utterance speaking via the speechsynthesis.speak() method.
... var synth = window.speechsynthesis; var voices = synth.getvoices(); var inputform = document.queryselector('form'); var inputtxt = document.queryselector('input'); var voiceselect = document.queryselector('select'); for(var i = 0; i < voices.length; i++) { var option = document.createelement('option'); option.textcontent = voices[i].name + ' (' + voices[i].lang + ')'; option.value = i; voiceselect.appendchild(option); } inputform.onsubmit = function(event) { event.preventdefault(); var utterthis = new speechsynthesisutterance(inputtxt.value); utterthis.voice = voices[voiceselect.value]; synth.speak(utterthis); inputtxt.blur(); } specifications specification status comment web speech apithe definition of 'speechsynthesisutterance' in that specific...
Storage.setItem() - Web APIs
WebAPIStoragesetItem
syntax storage.setitem(keyname, keyvalue); parameters keyname a domstring containing the name of the key you want to create/update.
... example the following function creates three data items inside local storage.
Streams API - Web APIs
for example, the response body returned by a successful fetch request can be exposed as a readablestream, and you can then read it using a reader created with readablestream.getreader(), cancel it with readablestream.cancel(), etc.
... examples we have created a directory of examples to go along with the streams api documentation — see mdn/dom-examples/streams.
StylePropertyMapReadOnly.get() - Web APIs
we create an array of properties of interest and use the stylepropertymapreadonly's get() method to get only those values.
....queryselector('#regurgitation'); // retrieve all computed styles with computedstylemap() const stylemap = myelement.computedstylemap(); // array of properties we're interested in const ofinterest = ['font-weight', 'border-left-color', 'color', '--colour']; // iterate thru our properties of interest for ( let i = 0; i < ofinterest.length; i++ ) { // properties const cssproperty = document.createelement('dt'); cssproperty.appendchild(document.createtextnode(ofinterest[i])); styleslist.appendchild(cssproperty); // values const cssvalue = document.createelement('dd'); cssvalue.appendchild(document.createtextnode( stylemap.get(ofinterest[i]))); styleslist.appendchild(cssvalue); } specifications specification status comment css typed om level 1the def...
SubmitEvent() - Web APIs
the submitevent() constructor creates and returns a new submitevent object, which is used to represent a submit event fired at an html form.
...next, a new submitevent is created, configured with its submitter set to the identified button (or null if the button wasn't found).
Text() - Web APIs
WebAPITextText
the text() constructor returns a newly created text object with the optional domstring given in parameter as its textual content.
... syntax text1 = new text(); // create an empty text node text2 = new text("this is a text node"); example let text = new text("test"); specifications specification status comment domthe definition of 'text()' in that specification.
TextEncoder() - Web APIs
the textencoder() constructor returns a newly created utf-8 textencoder object.
...any type label passed into the textencoder constructor will now be ignored and a utf-8 textencoder will be created.
Touch events - Web APIs
create a canvas <canvas id="canvas" width="600" height="600" style="border:solid black 1px;"> your browser does not support canvas element.
...it is only intended as a guide.) function ontouch(evt) { evt.preventdefault(); if (evt.touches.length > 1 || (evt.type == "touchend" && evt.touches.length > 0)) return; var newevt = document.createevent("mouseevents"); var type = null; var touch = null; switch (evt.type) { case "touchstart": type = "mousedown"; touch = evt.changedtouches[0]; break; case "touchmove": type = "mousemove"; touch = evt.changedtouches[0]; break; case "touchend": type = "mouseup"; touch = evt.changedtouches[0]; break; } newevt.initmousee...
TrackEvent() - Web APIs
the trackevent() constructor creates and returns a new trackevent object describing an event which occurred on a list of tracks (audiotracklist, videotracklist, or texttracklist).
... return value a newly-created trackevent object, initialized as described by the inputs to the constructor.
TreeWalker - Web APIs
a treewalker can be created using the document.createtreewalker() method.
... treewalker.root read only returns a node representing the root node as specified when the treewalker was created.
UIEvent - Web APIs
WebAPIUIEvent
although the uievent.inituievent() method is kept for backward compatibility, you should create a uievent object using the uievent() constructor.
...api/uievent" target="_top"><rect x="116" y="1" width="75" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="153.5" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">uievent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructors uievent() creates a uievent object.
URL.revokeObjectURL() - Web APIs
the url.revokeobjecturl() static method releases an existing object url which was previously created by calling url.createobjecturl().
... syntax url.revokeobjecturl(objecturl) parameters objecturl a domstring representing a object url that was previously created by calling createobjecturl().
URLSearchParams() - Web APIs
the urlsearchparams() constructor creates and returns a new urlsearchparams object.
... examples the following example shows how to create a urlsearchparams object from a url string.
URLSearchParams.set() - Web APIs
if the search parameter doesn't exist, this method creates it.
...params.set('baz', 3); params.tostring(); // "foo=1&bar=2&baz=3" below is a real-life example demonstrating how to create a url and set some search parameters.
VTTCue() - Web APIs
WebAPIVTTCueVTTCue
the vttcue() constructor creates and returns a new vttcue object.
... example // create a cue that is shown from 2 to 3 seconds and uses the given text.
VideoPlaybackQuality.creationTime - Web APIs
the read-only creationtime property on the videoplaybackquality interface reports the number of milliseconds since the browsing context was created this quality sample was recorded.
... syntax value = videoplaybackquality.creationtime; value a domhighrestimestamp object which indicates the number of milliseconds that elapased between the time the browsing context was created and the time at which this sample of the video quality was obtained.
VideoPlaybackQuality - Web APIs
totalvideoframes read only an unsigned long giving the number of video frames created and dropped since the creation of the associated htmlvideoelement.
...a corrupted frame may be created or dropped.
VideoTrack - Web APIs
sourcebuffer read only the sourcebuffer that created the track.
... returns null if the track was not created by a sourcebuffer or the sourcebuffer has been removed from the mediasource.sourcebuffers attribute of its parent media source.
WakeLockSentinel - Web APIs
examples in this example we create an asynchronous function which requests a wakelocksentinel.
... // create a reference for the wake lock let wakelock = null; // create an async function to request a wake lock const requestwakelock = async () => { try { wakelock = await navigator.wakelock.request('screen'); // listen for our release event wakelock.addeventlistener('release', () => { // if wake lock is released alter the ui accordingly }); } catch (err) { // if wake lock request fails - usually system related, such as battery } } wakelockonbutton.addeventlistener('click', () => { requestwakelock(); }) wakelockoffbutton.addeventlistener('click', () => { if (wakelock !== null) { w...
WebGLProgram - Web APIs
to create a webglprogram, call the gl context's createprogram() function.
... var program = gl.createprogram(); // attach pre-existing shaders gl.attachshader(program, vertexshader); gl.attachshader(program, fragmentshader); gl.linkprogram(program); if ( !gl.getprogramparameter( program, gl.link_status) ) { var info = gl.getprograminfolog(program); throw 'could not compile webgl program.
WebGLQuery - Web APIs
when working with webglquery objects, the following methods of the webgl2renderingcontext are useful: webgl2renderingcontext.createquery() webgl2renderingcontext.deletequery() webgl2renderingcontext.isquery() webgl2renderingcontext.beginquery() webgl2renderingcontext.endquery() webgl2renderingcontext.getquery() webgl2renderingcontext.getqueryparameter() examples creating a webglquery object in this example, gl must be a webgl2renderingcontext.
... var query = gl.createquery(); specifications specification status comment webgl 2.0the definition of 'webglquery' in that specification.
WebGLRenderingContext.generateMipmap() - Web APIs
mipmaps are used to create distance with objects.
...it starts with the resolution of the texture image and halves the resolution until a 1x1 dimension texture image is created.
WebGLRenderingContext.getProgramInfoLog() - Web APIs
when a webglprogram object is initially created, its information log will be a string of length 0.
... examples checking program errors var program = gl.createprogram(); // attach pre-existing shaders gl.attachshader(program, vertexshader); gl.attachshader(program, fragmentshader); gl.linkprogram(program); gl.getprograminfolog(program); specifications specification status comment webgl 1.0the definition of 'getprograminfolog' in that specification.
WebGLSampler - Web APIs
when working with webglsampler objects, the following methods of the webgl2renderingcontext are useful: webgl2renderingcontext.createsampler() webgl2renderingcontext.deletesampler() webgl2renderingcontext.issampler() webgl2renderingcontext.bindsampler() webgl2renderingcontext.getsamplerparameter() examples creating a webglsampler object in this example, gl must be a webgl2renderingcontext.
... var sampler = gl.createsampler(); specifications specification status comment webgl 2.0the definition of 'webglsample' in that specification.
WebGLTransformFeedback - Web APIs
when working with webgltransformfeedback objects, the following methods of the webgl2renderingcontext are useful: webgl2renderingcontext.createtransformfeedback() webgl2renderingcontext.deletetransformfeedback() webgl2renderingcontext.istransformfeedback() webgl2renderingcontext.bindtransformfeedback() webgl2renderingcontext.begintransformfeedback() webgl2renderingcontext.endtransformfeedback() webgl2renderingcontext.pausetransformfeedback() webgl2renderingcontext.resumetransformfeedback() webgl2renderingcontext.transformfeedback...
... var transformfeedback = gl.createtransformfeedback(); specifications specification status comment webgl 2.0the definition of 'webgltransformfeedback' in that specification.
WebGLVertexArrayObject - Web APIs
when working with webglvertexarrayobject objects, the following methods are useful: webgl2renderingcontext.createvertexarray() webgl2renderingcontext.deletevertexarray() webgl2renderingcontext.isvertexarray() webgl2renderingcontext.bindvertexarray() webgl 1: the oes_vertex_array_object extension allows you to use vertex array objects in a webgl 1 context.
... examples var vao = gl.createvertexarray(); gl.bindvertexarray(vao); // ...
Detect WebGL - Web APIs
button.addeventlistener("click", detectwebglcontext, false); function detectwebglcontext () { // create canvas element.
... var canvas = document.createelement("canvas"); // get webglrenderingcontext from canvas element.
Hello GLSL - Web APIs
main() { gl_fragcolor = vec4(0.18, 0.54, 0.34, 1.0); } </script> ;(function(){ "use strict" window.addeventlistener("load", setupwebgl, false); var gl, program; function setupwebgl (evt) { window.removeeventlistener(evt.type, setupwebgl, false); if (!(gl = getrenderingcontext())) return; var source = document.queryselector("#vertex-shader").innerhtml; var vertexshader = gl.createshader(gl.vertex_shader); gl.shadersource(vertexshader,source); gl.compileshader(vertexshader); source = document.queryselector("#fragment-shader").innerhtml var fragmentshader = gl.createshader(gl.fragment_shader); gl.shadersource(fragmentshader,source); gl.compileshader(fragmentshader); program = gl.createprogram(); gl.attachshader(program, vertexshader); gl.attachshader(progra...
..." + "error log: " + linkerrlog; return; } initializeattributes(); gl.useprogram(program); gl.drawarrays(gl.points, 0, 1); cleanup(); } var buffer; function initializeattributes() { gl.enablevertexattribarray(0); buffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, buffer); gl.vertexattribpointer(0, 1, gl.float, false, 0, 0); } function cleanup() { gl.useprogram(null); if (buffer) gl.deletebuffer(buffer); if (program) gl.deleteprogram(program); } function getrenderingcontext() { var canvas = document.queryselector("canvas"); canvas.width = canvas.clientwidth; canvas.height = canvas.clientheight; va...
Hello vertex attributes - Web APIs
main() { gl_fragcolor = vec4(0.18, 0.54, 0.34, 1.0); } </script> ;(function(){ "use strict" window.addeventlistener("load", setupwebgl, false); var gl, program; function setupwebgl (evt) { window.removeeventlistener(evt.type, setupwebgl, false); if (!(gl = getrenderingcontext())) return; var source = document.queryselector("#vertex-shader").innerhtml; var vertexshader = gl.createshader(gl.vertex_shader); gl.shadersource(vertexshader,source); gl.compileshader(vertexshader); source = document.queryselector("#fragment-shader").innerhtml var fragmentshader = gl.createshader(gl.fragment_shader); gl.shadersource(fragmentshader,source); gl.compileshader(fragmentshader); program = gl.createprogram(); gl.attachshader(program, vertexshader); gl.attachshader(progra...
...get.offsetleft; var clickxinwebglcoords = 2.0 * (clickxrelativtocanvas- gl.drawingbufferwidth/2) / gl.drawingbufferwidth; gl.bufferdata(gl.array_buffer, new float32array([clickxinwebglcoords]), gl.static_draw); gl.drawarrays(gl.points, 0, 1); }, false); } var buffer; function initializeattributes() { gl.enablevertexattribarray(0); buffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, buffer); gl.bufferdata(gl.array_buffer, new float32array([0.0]), gl.static_draw); gl.vertexattribpointer(0, 1, gl.float, false, 0, 0); } window.addeventlistener("beforeunload", cleanup, true); function cleanup() { gl.useprogram(null); if (buffer) gl.deletebuffer(buffer); if (program) gl.deleteprogram(program); } function getrendering...
Textures from code - Web APIs
0.2/distancesqrd, 0.1/distancesqrd, 0.0, 1.0 ); } </script> ;(function(){ "use strict" window.addeventlistener("load", setupwebgl, false); var gl, program; function setupwebgl (evt) { window.removeeventlistener(evt.type, setupwebgl, false); if (!(gl = getrenderingcontext())) return; var source = document.queryselector("#vertex-shader").innerhtml; var vertexshader = gl.createshader(gl.vertex_shader); gl.shadersource(vertexshader,source); gl.compileshader(vertexshader); source = document.queryselector("#fragment-shader").innerhtml var fragmentshader = gl.createshader(gl.fragment_shader); gl.shadersource(fragmentshader,source); gl.compileshader(fragmentshader); program = gl.createprogram(); gl.attachshader(program, vertexshader); gl.attachshader(progra...
..." + "error log: " + linkerrlog; return; } initializeattributes(); gl.useprogram(program); gl.drawarrays(gl.points, 0, 1); cleanup(); } var buffer; function initializeattributes() { gl.enablevertexattribarray(0); buffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, buffer); gl.bufferdata(gl.array_buffer, new float32array([0.0, 0.0]), gl.static_draw); gl.vertexattribpointer(0, 2, gl.float, false, 0, 0); } function cleanup() { gl.useprogram(null); if (buffer) gl.deletebuffer(buffer); if (program) gl.deleteprogram(program); } function getrenderingcontext() { var canvas = document.queryselector("canvas"); ...
Compressed texture formats - Web APIs
no examples async function getcompressedtextureifavailable(gl) { const texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); // create texture object on gpu const ext = gl.getextension('webgl_compressed_texture_s3tc'); // will be null if not supported if (ext) { // the file is already in the correct compressed format const dataarraybuffer = await fetch('/textures/foobar512x512.rgba_s3tc_dxt1') .then(response => response.arraybuffer()); gl.compres...
...sedteximage2d(gl.texture_2d, 0, // set the base image level ext.compressed_rgba_s3tc_dxt1_ext, // the compressed format we are using 512, 512, // width, height of the image 0, // border, always 0 new dataview(dataarraybuffer)); gl.generatemipmap(); // create mipmap levels, like we would for a standard image return texture; } } ...
Introduction to the Real-time Transport Protocol (RTP) - Web APIs
this triggers renegotiation of the rtcpeerconnection by sending it a negotiationneeded event, which your code responds to generating an sdp offer using rtcpeerconnection.createoffer and sending it through the signaling server to the remote peer.
... the sdp answer is generated and sent using a method called sendanswer(), which generates the answer using createanswer() then sends the resulting sdp to the other peer over the signaling service.
Introduction to WebRTC protocols - Web APIs
this can mean that even though we have the public ip address found by the stun server, not anyone can create a connection.
...you would create a connection with a turn server and tell all peers to send packets to the server which will then be forwarded to you.
WebSocket - Web APIs
WebAPIWebSocket
constructor websocket(url[, protocols]) returns a newly created websocket object.
... examples // create websocket connection.
Writing WebSocket client applications - Web APIs
creating a websocket object in order to communicate using the websocket protocol, you need to create a websocket object; this will automatically attempt to open the connection to the server.
... examples this simple example creates a new websocket, connecting to the server at wss://www.example.com/socketserver.
Writing a WebSocket server in Java - Web APIs
introduction this example shows you how to create a websocket api server using oracle java.
... although other server-side languages can be used to create a websocket server, this example uses oracle java to simplify the example code.
WebXR performance guide - Web APIs
let normalmatrix = mat4.create(); let modelviewmatrix = mat4.create(); let objectmatrix = mat4.
...const normalmatrix = mat4.create(); const modelviewmatrix = mat4.create(); function drawscene(gl, view, programinfo, buffers, texture, deltatime) { ...
Using the Web Animations API - Web APIs
representing keyframes the first thing we need is to create a keyframe object corresponding to our css @keyframes block: var alicetumbling = [ { transform: 'rotate(0) translate3d(-50%, -50%, 0)', color: '#000' }, { color: '#431236', offset: 0.3}, { transform: 'rotate(360deg) translate3d(-50%, -50%, 0)', color: '#000' } ]; here we’re using an array containing multiple objects.
... representing timing properties we’ll also need to create an object of timing properties (an animationeffecttimingproperties object) corresponding to the values in alice’s animation: var alicetiming = { duration: 3000, iterations: infinity } you’ll notice a few differences here from how equivalent values are represented in css: for one, the duration is in milliseconds as opposed to seconds — 3000 not 3s.
Web Animations API - Web APIs
can take an object created with the keyframeeffect() constructor.
...it returns the created animation object instance.
Web Storage API - Web APIs
these mechanisms are available via the window.sessionstorage and window.localstorage properties (to be more precise, in supporting browsers the window object implements the windowlocalstorage and windowsessionstorage objects, which the localstorage and sessionstorage properties hang off) — invoking one of these will create an instance of the storage object, through which data items can be set, retrieved and removed.
... examples to illustrate some typical web storage usage, we have created a simple example, imaginatively called web storage demo.
Web Workers API - Web APIs
web workers concepts and usage a worker is an object created using a constructor (e.g.
... workernavigator represents the identity and state of the user agent (the client): examples we have created a couple of simple demos to show basic usage: basic dedicated worker example (run dedicated worker).
window.dump() - Web APIs
WebAPIWindowdump
note: this preference is not listed in about:config by default, you may need to create it (right-click the content area -> new -> boolean).
...if you don't have one already, closing the application and re-opening it with the command line parameter -console should create the console or use -attach-console to use the existing console.
Privileged features - Web APIs
a typical modal window is created by the alert() function.
... alwayslowered if on, the new created window floats below, under its own parent when the parent window is not minimized.
Window: popstate event - Web APIs
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.
... if new-entry doesn't currently contain an existing document, fetch the content and create its document before continuing.
Window.sessionStorage - Web APIs
opening a page in a new tab or window creates a new session with the value of the top-level browsing context, which differs from how session cookies work.
... opening multiple tabs/windows with the same url creates sessionstorage for each tab/window.
Window.speechSynthesis - Web APIs
inside the inputform.onsubmit handler, we stop the form submitting with preventdefault(), create a new speechsynthesisutterance instance containing the text from the text <input>, set the utterance's voice to the voice selected in the <select> element, and start the utterance speaking via the speechsynthesis.speak() method.
... var synth = window.speechsynthesis; var inputform = document.queryselector('form'); var inputtxt = document.queryselector('input'); var voiceselect = document.queryselector('select'); function populatevoicelist() { voices = synth.getvoices(); for(i = 0; i < voices.length ; i++) { var option = document.createelement('option'); option.textcontent = voices[i].name + ' (' + voices[i].lang + ')'; if(voices[i].default) { option.textcontent += ' -- default'; } option.setattribute('data-lang', voices[i].lang); option.setattribute('data-name', voices[i].name); voiceselect.appendchild(option); } } populatevoicelist(); if (speechsynthesis.onvoiceschanged !== undefined) { speechsynthesis.onvoiceschanged = populatevoicelist; } inputform.onsubmit = function(...
Worker() - Web APIs
WebAPIWorkerWorker
the worker() constructor creates a worker object that executes the script at the specified url.
...available properties are as follows: type: a domstring specifying the type of worker to create.
WorkerGlobalScope - Web APIs
windoworworkerglobalscope.btoa() creates a base-64 encoded ascii string from a string of binary data.
... windoworworkerglobalscope.createimagebitmap() accepts a variety of different image sources, and returns a promise which resolves to an imagebitmap.
WritableStreamDefaultWriter.close() - Web APIs
it then calls a function called sendmessage(), passing the newly created stream and a string.
...trategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) { return new promise((resolve, reject) => { var buffer = new arraybuffer(2); var view = new uint16array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listitem = document.createelement('li'); listitem.textcontent = "chunk decoded: " + decoded; list.appendchild(listitem); result += decoded; resolve(); }); }, close() { var listitem = document.createelement('li'); listitem.textcontent = "[message received] " + result; list.appendchild(listitem); }, abort(err) { console.log("sink error:", err); } }, queuingstrategy); sen...
WritableStreamDefaultWriter.write() - Web APIs
it then calls a function called sendmessage(), passing the newly created stream and a string.
...trategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) { return new promise((resolve, reject) => { var buffer = new arraybuffer(2); var view = new uint16array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listitem = document.createelement('li'); listitem.textcontent = "chunk decoded: " + decoded; list.appendchild(listitem); result += decoded; resolve(); }); }, close() { var listitem = document.createelement('li'); listitem.textcontent = "[message received] " + result; list.appendchild(listitem); }, abort(err) { console.log("sink error:", err); } }, queuingstrategy); sen...
XMLDocument.load() - Web APIs
WebAPIXMLDocumentload
examples var xmldoc = document.implementation.createdocument("", "test", null); function documentloaded (e) { alert(new xmlserializer().serializetostring(e.target)); // gives querydata.xml contents as string } xmldoc.addeventlistener("load", documentloaded, false); xmldoc.load('querydata.xml'); see also the load sample in the xml tests directory.
... (to test this functionality, create the files on your local disk or on a webserver rather than loading the load.html file from the lxr-generated page, which will serve the text.xml file as html.) specifications old w3c working draft of the dom level 3 load & save module ...
XMLHttpRequest.getAllResponseHeaders() - Web APIs
the code shows how to obtain the raw header string, as well as how to convert it into an array of individual headers and then how to take that array and create a mapping of header names to their values.
... var request = new xmlhttprequest(); request.open("get", "foo.txt", true); request.send(); request.onreadystatechange = function() { if(this.readystate == this.headers_received) { // get the raw header string var headers = request.getallresponseheaders(); // convert the header string into an array // of individual headers var arr = headers.trim().split(/[\r\n]+/); // create a map of header names to values var headermap = {}; arr.foreach(function (line) { var parts = line.split(': '); var header = parts.shift(); var value = parts.join(': '); headermap[header] = value; }); } } once this is done, you can, for example: var contenttype = headermap["content-type"]; this obtains the value of the content-type header into the variable...
XMLHttpRequest.readyState - Web APIs
an xhr client exists in one of the following states: value state description 0 unsent client has been created.
... unsent the xmlhttprequest client has been created, but the open() method hasn't been called yet.
XMLSerializer - Web APIs
inserting nodes into a dom based on xml this example uses the element.insertadjacenthtml() method to insert a new dom node into the body of the document, based on xml created by serializing an element object.
... var inp = document.createelement('input'); var xmls = new xmlserializer(); var inp_xmls = xmls.serializetostring(inp); // first convert dom node into a string // insert the newly created node into the document's body document.body.insertadjacenthtml('afterbegin', inp_xmls); the code creates a new <input> element by calling document.createelement(), then serializes it into xml using serializetostring().
XPathExpression - Web APIs
objects of this type are created by calling xpathevaluator.createexpression().
... html <div>xpath example</div> <div>number of &lt;div&gt;s: <output></output></div> javascript var xpath = "//div"; var evaluator = new xpathevaluator(); var expression = evaluator.createexpression(xpath); var result = expression.evaluate(document, xpathresult.ordered_node_snapshot_type); document.queryselector("output").textcontent = result.snapshotlength; result specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathexpression' in that specification.
XRInputSourceEventInit.frame - Web APIs
of course, as a general rule, you won't need to create xrinputsourceeventinit objects yourself.
... examples this example creates a new select event and sends it to the xrsession.
XRReferenceSpaceEventInit - Web APIs
you will not usually need to use this, since these events are created by the webxr infrastructure.
... examples this simple snippet calls the constructor to create a new reference space event of type reset.
XRRigidTransform() - Web APIs
the xrrigidtransform() constructor creates and returns a new xrrigidtransform object, representing the position and orientation of a point or object.
...after creating an xrrigidtransform from the viewer's initial position and orientation, we pass the new transform into getoffsetreferencespace() to create another reference space, now offset so that its origin is located at the same place in space as the coordinates given by viewerposition, with the orientation also revised in the same fashion.
XRRigidTransform.matrix - Web APIs
[100px010py001pz0001]\begin{bmatrix} 1 & 0 & 0 & x\\ 0 & 1 & 0 & y\\ 0 & 0 & 1 & z\\ 0 & 0 & 0 & 1 \end{bmatrix} then a rotation matrix is created by computing a column-vector rotation matrix from the unit quaternion specified by orientation: [1-2(qy2+qz2)2(qxqy-qzqw)2(qxqz+qyqw)02(qxqy+qzqw)1-2(qx2+qz2)2(qyqz-qxqw)02(qxqz-qyqw)2(qyqz+qxqw)1-2(qx2+qy2)00001]\begin{bmatrix} 1 - 2(q_y^2 + q_z^2) & 2(q_xq_y - q_zq_w) & 2(q_xq_z + q_yq_w) & p_x\\ 2(q_xq_y + q_zq_w) & 1 - 2(q_x^2 + q_z^2) & 2(q_yq_z - q_xq_w) & p_y\\ 2(q_xq_z - q_yq_w) & 2(q_y...
...qzqw)2(qxqz+qyqw)px2(qxqy+qzqw)1-2(qx2+qz2)2(qyqz-qxqw)py2(qxqz-qyqw)2(qyqz+qxqw)1-2(qx2+qy2)pz0001]\begin{bmatrix} 1 - 2(q_y^2 + q_z^2) & 2(q_xq_y - q_zq_w) & 2(q_xq_z + q_yq_w) & p_x\\ 2(q_xq_y + q_zq_w) & 1 - 2(q_x^2 + q_z^2) & 2(q_yq_z - q_xq_w) & p_y\\ 2(q_xq_z - q_yq_w) & 2(q_yq_z + q_xq_w) & 1 - 2(q_x^2 + q_y^2) & p_z\\ 0 & 0 & 0 & 1 \end{bmatrix} examples in this example, a transform is created to create a matrix which can be used as a transform during rendering of webgl objects, in order to place objects to match a given offset and orientation.
XRRigidTransform - Web APIs
constructor new xrrigidtransform() creates a new xrrigidtransform object which represents a transform that applies a specified position and/or orientation.
... example this code snippet creates an xrrigidtransform to specify the offset and orientation in relation to the current reference space to use when creating a new reference space.
XRSessionEvent - Web APIs
constructor xrsessionevent() creates and returns a new xrsessionevent object configured using the specified xrsessioneventinit object's values as available.
... examples this example creates a listiener that watches for the visibility state of the session to change.
XRView.transform - Web APIs
WebAPIXRViewtransform
const modelviewmatrix = mat4.create(); const normalmatrix = mat4.create(); for (let view of pose.views) { let viewport = gllayer.getviewport(view); gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height); for (let obj of world.objects) { mat4.multiply(modelviewmatrix, view.transform.inverse.matrix, obj.matrix); mat4.invert(normalmatrix, modelviewmatrix); mat4.transpose(normalmatrix, normalmatrix); ...
... obj.render(modelviewmatrix, normalmatrix); } } two matrices are created outside the rendering loop; this avoids repeatedly allocating and deallocating the matrices, and generally reduces overhead by reusing the same matrix for each object rendered.
XRWebGLLayerInit.framebufferScaleFactor - Web APIs
a value of 2.0, on the other hand, creates a frame buffer whose resolution is double that of the actual display buffer.
... example in this example, a new xrwebgllayer is created for a webxr session, xrsession, with a frame buffer whose resolution is half that of the default display resolution of the xr device.
XRWebGLLayerInit.ignoreDepthValues - Web APIs
syntax let layerinit = { ignoredepthvalues: boolvalue }; let gllayer = new xrwebgllayer(xrsession, gl, layerinit); let gllayer = new xrwebgllayer(xrsession, gl, { ignoredepthvalues: boolvalue }); value a boolean value which can be set to true to disable the use of the depth buffer by the webgl rendering layer created by the xrwebgllayer() constructor.
... example in this example, a new xrwebgllayer is created for a webxr session, xrsession.
XRWebGLLayerInit.stencil - Web APIs
when using the xrwebgllayer() constructor to create a new webgl rendering layer for webxr, providing as the layerinit parameter an object whose stencil property is false requests that the new layer be created without a stencil buffer.
... example in this example, a new xrwebgllayer is created for a webxr session, xrsession, without a stencil buffer.
Using the alert role - Accessibility
<h2 role="alert">your form could not be submitted because of 3 validation errors.</h2> example 2: dynamically adding an element with the alert role this snippet dynamically creates an element with an alert role and adds it to the document structure.
... let myalert = document.createelement("p"); myalert.setattribute("role", "alert"); let myalerttext = document.createtextnode("you must agree with our terms of service to create an account."); myalert.appendchild(myalerttext); document.body.appendchild(myalert); note: the same result can be achieved with less code when using a script library like jquery: $("<p role='alert'>you must agree with our terms of service to create an account.</p>").appendto(document.body); example 3: adding alert role to an existing element sometimes it's useful to add an alert role to an element that is already visible on the page rather than creating a new element.
Using the log role - Accessibility
the log role is used to identify an element that creates a live region where new information is added in a meaningful order and old information may disappear.
... <div id="liveregion" class="region" role="log"></div> example 2: snippet from an example application this snippet creates the chat log in an ajax chat application.
ARIA Test Cases - Accessibility
in virtual buffer mode, the slider exists in the virtual buffer as a single entity, and any images or text that create the sliders appearance are not presented to the user separately.
...9 - - n/a n/a jaws 10 - - - - voiceover (leopard) n/a n/a - fail window-eyes - - - - nvda - n/a - - zoom (leopard) pass n/a pass pass zoomtext - - - - orca - - - - tree dojo nightly build simple tree -- uses document structure to create hierarchy tree - subtrees are encapsulated in treeitems ms ie8 tree example we need an example that uses aria-level, aria-setsize and aria-posinset to create the hierarchy we also need one that uses aria-owns to create the hierarchy / structure we need one that uses the document to create structure, but uses nested uls with links inside, and role="presentation" expected at behavior: if ...
ARIA: contentinfo role - Accessibility
each page should only include one contentinfo landmark, created by either using the <footer> element or by declaring role="contentinfo".
...using too many landmark roles can create "noise" in screen readers, making it difficult to understand the overall layout of the page.
ARIA: form role - Accessibility
description a form landmark identifies a region of content that contains a collection of items and objects that, as a whole, combine to create a form when no other named landmark is appropriate (e.g.
...using too many landmark roles can create "noise" in screen readers, making it difficult to understand the overall layout of the page.
ARIA: row role - Accessibility
to create an aria row, add role="row" to the container element.
... to create an interactive widget that has a tabular structure, use the grid pattern instead.
ARIA: search role - Accessibility
the search role is added to the container element that encompasses the items and objects that, as a whole, combine to create search functionality.
...using too many landmark roles can create "noise" in screen readers, making it difficult to understand the overall layout of the page.
ARIA: switch role - Accessibility
the aria switch role is functionally identical to the checkbox role, except that instead of representing "checked" and "unchecked" states, which are fairly generic in meaning, the switch role represents the states "on" and "off." this example creates a widget and assigns the aria switch role to it.
... adding the switch role in aria this simple example just creates a widget and assigns the aria switch role to it.
ARIA: table role - Accessibility
to create an aria table, add role="table" to the container element.
... to create an interactive widget that has a tabular structure, use the grid pattern instead.
ARIA: textbox role - Accessibility
to create a multi-line text box which supports line breaks, as in an html <textarea>, set aria-multiline="true".
... aria-multiline attribute if aria-multiline="true" is set, the at informs the user that the textbox supports multi-line input, with the expectation that enter or return will create a line break rather than submitting the form.
Web applications and ARIA FAQ - Accessibility
for more information about how to create accessible widgets with aria, see the overview of accessible web applications and widgets.
...progressbar.setattribute("role", "progressbar"); progressbar.setattribute("aria-valuemin", 0); progressbar.setattribute("aria-valuemax", 100); // create a function that can be called at any time to update the value of the progress bar.
Accessibility documentation index - Accessibility
this role can be used in combination with the aria-pressed attribute to create toggle buttons.
... 79 widgets accessibility this page was auto-generated because a user created a sub-page to this page.
Keyboard - Accessibility
this creates confusion for keyboard-only users when the focus order differs from the logical order of the page.
... if you create your own focusable components, be sure that you also define focus styling for them.
::before (:before) - CSS: Cascading Style Sheets
WebCSS::before
in css, ::before creates a pseudo-element that is the first child of the selected element.
... html <span class="ribbon">notice where the orange box is.</span> css .ribbon { background-color: #5bc8f7; } .ribbon::before { content: "look at this orange box."; background-color: #ffba10; border-color: black; border-style: dotted; } result to-do list in this example we will create a simple to-do list using pseudo-elements.
Using URL values for the cursor property - CSS: Cascading Style Sheets
an animated png or gif will not create an animated cursor.
...javascript, css animation, and declarative smil inside an svg image are ignored; you can't use svg to create an animated cursor, for example.
Styling Columns - CSS: Cascading Style Sheets
as column boxes created inside multicol containers are anonymous boxes, there is little we can do to style them.
... in this next example i have created a 5px dotted rule with a color of rebeccapurple, using the longhand values.
CSS Containment - CSS: Cascading Style Sheets
the containing box creates a stacking context, therefore z-index can be used.
... using contain: style would ensure that the counter-increment and counter-set properties created new counters scoped to that subtree only.
OpenType font features guide - CSS: Cascading Style Sheets
this way you can create a named option that applies to only a single font, or one that is shared and can be applied more generally in this case, @stylistic(alternates) will show all the alternate characters for either font).
... while more common in script typefaces, in the below example they are used to create arrows: position (font-variant-position) position variants are used to enable typographic superscript and subscript glyphs.
Line-based placement with CSS Grid - CSS: Cascading Style Sheets
the following two examples will create the same grid area.
...that can create some nice effects, however you can also end up with things overlapping incorrectly if you specify the wrong start or end line.
Using CSS counters - CSS: Cascading Style Sheets
ion ', the value of section counter, and a colon before the content of each h3 */ } html <h3>introduction</h3> <h3>body</h3> <h3>conclusion</h3> result nesting counters a css counter can be especially useful for making outlined lists, because a new instance of the counter is automatically created in child elements.
... example of a nested counter css ol { counter-reset: section; /* creates a new instance of the section counter with each ol element */ list-style-type: none; } li::before { counter-increment: section; /* increments only this instance of the section counter */ content: counters(section, ".") " "; /* combines the values of all instances of the section counter, separated by a period */ } html <ol> <li>item</li> <!-- 1 -...
Stacking context example 2 - CSS: Cascading Style Sheets
div #4 belongs to the stacking context created by div #3, and as explained previously div #3 (and all its content) is under div #2.
...in the stacking context hierarchy, elements that do not create a stacking context are collapsed on their parent.
Stacking context example 3 - CSS: Cascading Style Sheets
the first-level menu is only relatively positioned, so no stacking context is created.
...the problem is that for each second-level menu, a stacking context is created and each third-level menu belongs to the context of its parent.
Using the :target pseudo-class in selectors - CSS: Cascading Style Sheets
this is simple enough: h2:target { font-weight: bold; } it's also possible to create styles that are specific to a particular fragment of the document.
...thus, to add a border to the #example fragment, we would write: #example:target { border: 1px solid black; } targeting all elements if the intent is to create a "blanket" style that will apply to all targeted elements, then the universal selector comes in handy: :target { color: red; } example in the following example, there are five links that point to elements in the same document.
CSS Transitions - CSS: Cascading Style Sheets
css transitions is a module of css that lets you create gradual transitions between the values of specific css properties.
... reference properties transition transition-delay transition-duration transition-property transition-timing-function guides using css transitions step-by-step tutorial about how to create transitions using css.
Sticky footers - CSS: Cascading Style Sheets
we then create a single column grid layout with three rows, one row for each part of our layout.
... alternate method if you need compatibility with browsers that do not support grid layout you can also use flexbox to create a sticky footer.
background-size - CSS: Cascading Style Sheets
background images created with the element() function use the intrinsic dimensions and proportions of the generating element.
... note: in gecko, background images created using the element() function are currently treated as images with the dimensions of the element, or of the background positioning area if the element is svg, with the corresponding intrinsic proportion.
box-shadow - CSS: Cascading Style Sheets
the specification does not include an exact algorithm for how the blur radius should be calculated, however, it does elaborate as follows: …for a long, straight shadow edge, this should create a color transition the length of the blur distance that is perpendicular to and centered on the shadow’s edge, and that ranges from the full shadow color at the radius endpoint inside the shadow to fully transparent at the endpoint outside it.
...)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle> examples setting three shadows in this example, we include three shadows: an inset shadow, a regular drop shadow, and a 2px shadow that creates a border effect (we could have used an outline instead for that third shadow).
clip-path - CSS: Cascading Style Sheets
WebCSSclip-path
the clip-path css property creates a clipping region that sets what part of an element should be shown.
... none no clipping path is created.
content - CSS: Cascading Style Sheets
WebCSScontent
</p> css q { color: blue; } q::before { content: open-quote; } q::after { content: close-quote; } h1::before { content: "chapter "; /* the trailing space creates separation between the added content and the rest of the content */ } result image combined with text this example inserts an image before the link.
... html <h2>paperback best sellers</h2> <ol> <li>political thriller</li> <li class="new-entry">halloween stories</li> <li>my biography</li> <li class="new-entry">vampire romance</li> </ol> css .new-entry::after { content: " new!"; /* the leading space creates separation between the added content and the rest of the content */ color: red; } result images and element attributes this example inserts an image before each link, and adds its id attribute after.
counter-set - CSS: Cascading Style Sheets
it manipulates the value of existing counters, and will only create new counters if there isn't already a counter of the given name on the element.
...if there isn't currently a counter of the given name on the element, the element will create a new counter of the given name with a starting value of 0 (though it may then immediately set or increment that value to something different).
<easing-function> - CSS: Cascading Style Sheets
for some properties, such as left or right, this creates a kind of "bouncing" effect.
... examples easing function comparison this example creates an animation that can be started and stopped again using the provided button, and a select menu that can be used to switch its easing function between the available keywords, plus a couple of cubic-bezier() and steps() options.
font - CSS: Cascading Style Sheets
WebCSSfont
</p> <form action="createshorthand()"> <div class="cf"> <div class="setpropcont"> font-style<br/> <input type="radio" id="font-style-none" name="font_style" checked="" value="" onchange="setcss()"> <label for="font-style-none">none</label><br/> <input type="radio" id="font-style-normal" name="font_style" value="normal" onchange="setcss()"> <label for="font-style-normal">norm...
...dio_name, curelem = document.getelementbyid(curelemname); curelem.value = oradio[i].value; return oradio[i].value; } } } setcss = function () { getproperties(); injectcss(shorttext); } injectcss = function(cssfragment) { old = document.body.getelementsbytagname("style"); if (old.length > 1) { old[1].parentelement.removechild(old[1]); } css = document.createelement("style"); css.innerhtml = ".fontshorthand{font: " + cssfragment + "}"; document.body.appendchild(css); } setcss(); specifications specification status comment css fonts module level 3the definition of 'font' in that specification.
grid-auto-columns - CSS: Cascading Style Sheets
the grid-auto-columns css property specifies the size of an implicitly-created grid column track or pattern of tracks.
... if a grid item is positioned into a column that is not explicitly sized by grid-template-columns, implicit grid tracks are created to hold it.
grid-auto-rows - CSS: Cascading Style Sheets
the grid-auto-rows css property specifies the size of an implicitly-created grid row track or pattern of tracks.
... if a grid item is positioned into a row that is not explicitly sized by grid-template-rows, implicit grid tracks are created to hold it.
grid-template-areas - CSS: Cascading Style Sheets
<string>+ a row is created for every separate string listed, and a column is created for each cell in the string.
... multiple named cell tokens within and between rows create a single named grid area that spans the corresponding grid cells.
image() - CSS: Cascading Style Sheets
the first two represent the x and y coordates for the starting point of the box that will be created.
... omitting image sources while including a color is valid and creates a color swatch.
<length> - CSS: Cascading Style Sheets
WebCSSlength
note: these units, especially em and rem, are often used to create scalable layouts, which maintain the vertical rhythm of the page even when the user changes the font size.
... flex; justify-content: flex-start; align-items: center; height: 50px; } label { margin: 0 10px 0 20px; } javascript const inputdiv = document.queryselector('.inner'); const inputelem = document.queryselector('input'); const resultsdiv = document.queryselector('.results'); inputelem.addeventlistener('change', () => { inputdiv.style.width = inputelem.value; const result = document.createelement('div'); result.classname = 'result'; result.style.width = inputelem.value; result.innerhtml = `<code>width: ${inputelem.value}</code>`; resultsdiv.appendchild(result); inputelem.value = ''; inputelem.focus(); }) result specifications specification status comment css values and units module level 4the definition of '<length>' in that specificati...
margin - CSS: Cascading Style Sheets
WebCSSmargin
note: margins create extra space around an element.
... in contrast, padding creates extra space within an element.
mask-border - CSS: Cascading Style Sheets
the mask-border css shorthand property lets you create a mask along the edge of an element's border.
...-slice: as specifiedmask-border-source: as specified, but with <url> values made absolutemask-border-width: as specified, but with relative lengths converted into absolute lengthsanimation typeas each of the properties of the shorthand:mask-border-mode: discretemask-border-outset: discretemask-border-repeat: discretemask-border-slice: discretemask-border-source: discretemask-border-width: discretecreates stacking contextyes formal syntax <'mask-border-source'> | <'mask-border-slice'> [ / <'mask-border-width'>?
padding - CSS: Cascading Style Sheets
WebCSSpadding
note: padding creates extra space within an element.
... in contrast, margin creates extra space around an element.
shape-outside - CSS: Cascading Style Sheets
the shape includes any curvature created by the border-radius property (behavior which is similar to background-clip).
... <basic-shape> the float area is computed based on the shape created by of one of inset(), circle(), ellipse(), polygon(), or as added in the level 2 specification path().
scaleZ() - CSS: Cascading Style Sheets
in the above interactive examples, perspective: 550px; (to create a 3d space) and transform-style: preserve-3d; (so the children, the 6 sides of the cube, are also positioned in the 3d space), have been set on the cube.
... 10001000s 1000010000s00001 examples html <div>normal</div> <div class="perspective">translated</div> <div class="scaled-translated">scaled</div> css div { width: 80px; height: 80px; background-color: skyblue; } .perspective { /* includes a perspective to create a 3d space */ transform: perspective(400px) translatez(-100px); background-color: limegreen; } .scaled-translated { /* includes a perspective to create a 3d space */ transform: perspective(400px) scalez(2) translatez(-100px); background-color: pink; } result specifications specification status comment css transforms level 2the definition of 'scalez()' ...
transform - CSS: Cascading Style Sheets
WebCSStransform
if the property has a value different than none, a stacking context will be created.
... find out more: mdn understanding wcag, guideline 2.3 explanations understanding success criterion 2.3.3 | w3c understanding wcag 2.1 formal definition initial valuenoneapplies totransformable elementsinheritednopercentagesrefer to the size of bounding boxcomputed valueas specified, but with relative lengths converted into absolute lengthsanimation typea transformcreates stacking contextyes formal syntax none | <transform-list>where <transform-list> = <transform-function>+where <transform-function> = <matrix()> | <translate()> | <translatex()> | <translatey()> | <scale()> | <scalex()> | <scaley()> | <rotate()> | <skew()> | <skewx()> | <skewy()> | <matrix3d()> | <translate3d()> | <translatez()> | <scale3d()> | <scalez()> | <rotate3d()> | <rotatex()> | <rotatey(...
translate - CSS: Cascading Style Sheets
WebCSStranslate
formal definition initial valuenoneapplies totransformable elementsinheritednopercentagesrefer to the size of bounding boxcomputed valueas specified, but with relative lengths converted into absolute lengthsanimation typea transformcreates stacking contextyes formal syntax none | <length-percentage> [ <length-percentage> <length>?
... initial valuenoneapplies totransformable elementsinheritednopercentagesrefer to the size of bounding boxcomputed valueas specified, but with relative lengths converted into absolute lengthsanimation typea transformcreates stacking contextyes ...
unicode-bidi - CSS: Cascading Style Sheets
bidi-override for inline elements this creates an override.
... for block container elements this creates an override for inline-level descendants not within another block container element.
will-change - CSS: Cascading Style Sheets
be aware, that will-change may actually influence the visual appearance of elements, when used with property values, that create a stacking context (e.g.
... will-change: opacity), as the stacking context is created up front.
Event reference
a versionchange transaction has been created.
... domwindowcreated addons specific a window has been created.
Getting Started - Developer guides
<button id="ajaxbutton" type="button">make a request</button> <script> (function() { var httprequest; document.getelementbyid("ajaxbutton").addeventlistener('click', makerequest); function makerequest() { httprequest = new xmlhttprequest(); if (!httprequest) { alert('giving up :( cannot create an xmlhttp instance'); return false; } httprequest.onreadystatechange = alertcontents; httprequest.open('get', 'test.html'); httprequest.send(); } function alertcontents() { if (httprequest.readystate === xmlhttprequest.done) { if (httprequest.status === 200) { alert(httprequest.responsetext); } else { alert('there was a problem with the ...
... first off, let's create a valid xml document that we'll request later on.
Live streaming web audio and video - Developer guides
the key consideration when streaming media to a browser is the fact that rather than playing a finite file we are relaying a file that is being created on the fly and has no pre-determined start or end.
... gstreamer gstreamer is an open source cross-platform multimedia framework that allows you to create a variety of media-handling components, including streaming components.
Web Audio playbackRate explained - Developer guides
playbackrate basics let's starting by looking at a brief example of playbackrate usage: var myaudio = document.createelement('audio'); myaudio.setattribute('src','audiofile.mp3'); myaudio.playbackrate = 0.5; here we create an <audio> element, and set its src to a file of our choice.
... next we set playbackrate to 0.5, which represents half normal speed (the playbackrate is a multiplier applied to the original rate.) a complete example let's create a <video> element first, and set up video and playback rate controls in html: <video id="myvideo" controls> <source src="https://udn.realityripple.com/samples/6f/08625b424a.m4v" type='video/mp4' /> <source src="https://udn.realityripple.com/samples/5b/8cd6da9c65.webm" type='video/webm' /> </video> <form> <input id="pbr" type="range" value="1" min="0.5" max="4" step="0.1" > <p>playback rate <span id="currentpbr">1</span></p> </form> and apply some javascript to it: window.onload = function () { var v = document.getelementbyid("myvideo"); var p = document.getelementbyid("pbr"); var c = document.getelementbyid("cur...
Content categories - Developer guides
this is a loose grouping (it doesn't actually create a relationship among elements of these categories), but they help define and describe the categories' shared behavior and their associated rules, especially when you come upon their intricate details.
... a few other elements belong to this category, but only if a specific condition is fulfilled: <area>, if it is a descendant of a <map> element <link>, if the itemprop attribute is present <meta>, if the itemprop attribute is present <style>, if the scoped attribute is present sectioning content elements belonging to the sectioning content model create a section in the current outline that defines the scope of <header> elements, <footer> elements, and heading content.
Constraint validation - Developer guides
intrinsic and basic constraints in html5, basic constraints are declared in two ways: by choosing the most semantically appropriate value for the type attribute of the <input> element, e.g., choosing the email type automatically creates a constraint that checks whether the value is a valid e-mail address.
... <input> <output> <select> submit buttons (created with either a <button> element with the submit type, or an input element with the submit type.
HTML5 - Developer guides
WebGuideHTMLHTML5
this page was created with help from the w3c as a quick guide for those who have some basic familiarity and experience using html5.
... device access touch events handlers to react to events created by a user pressing touch screens.
Index - Developer guides
WebGuideIndex
9 cross-browser audio basics apps, audio, guide, html5, media, events this article provides: a basic guide to creating a cross-browser html5 audio player with all the associated attributes, properties, and events explained a guide to custom controls created using the media api 10 live streaming web audio and video guide, adaptive streaming live streaming technology is often employed to relay live events such as sports, concerts and more generally tv and radio programmes that are output live.
... 18 creating and triggering events advanced, dom, guide, javascript, needscontent, events this article demonstrates how to create and dispatch dom events.
Allowing cross-origin use of images and canvas - HTML: Hypertext Markup Language
to begin downloading the image, we create a new htmlimageelement object by using the image() constructor.
... receiving and saving the image the code that handles the newly-downloaded image is found in the imagereceived() method: function imagereceived() { let canvas = document.createelement("canvas"); let context = canvas.getcontext("2d"); canvas.width = downloadedimg.width; canvas.height = downloadedimg.height; context.drawimage(downloadedimg, 0, 0); imagebox.appendchild(canvas); try { localstorage.setitem("saved-image-example", canvas.todataurl("image/png")); } catch(err) { console.log("error: " + err); } } imagereceived() is called to handle t...
<audio>: The Embed Audio element - HTML: Hypertext Markup Language
WebHTMLElementaudio
you can, however, create your own custom controls using javascript and the htmlmediaelement api.
... to get a consistent look and feel across browsers, you'll need to create custom controls; these can be marked up and styled in whatever way you want, and then javascript can be used along with the htmlmediaelement api to wire up their functionality.
<content>: The Shadow DOM Content Placeholder element (obsolete) - HTML: Hypertext Markup Language
WebHTMLElementcontent
it has now been replaced by the <slot> element, which creates a point in the dom at which a shadow dom can be inserted.
... var mycontent = document.queryselector('div'); // create a shadow dom on the <div> var shadowroot = mycontent.createshadowroot(); // insert into the shadow dom a new heading and // part of the original content: the <p> tag.
<dfn>: The Definition element - HTML: Hypertext Markup Language
WebHTMLElementdfn
result this looks like this rendered in your browser: links to definitions to add links to the definitions, you create the link the same way you always do, with the <a> element.
...later on, a link is created using <a> with the href attribute set to "#definition-dfn" to set up the link back to the definition.
<input type="button"> - HTML: Hypertext Markup Language
WebHTMLElementinputbutton
note: while <input> elements of type button are still perfectly valid html, the newer <button> element is now the favored way to create buttons.
... examples the below example shows a very simple drawing app created using a <canvas> element and some simple css and javascript (we'll hide the css for brevity).
<input type="submit"> - HTML: Hypertext Markup Language
WebHTMLElementinputsubmit
if you want to create a custom button and then customize the behavior using javascript, you need to use <input type="button">, or better still, a <button> element.
... if you choose to use <button> elements to create the buttons in your form, keep this in mind: if there's only one <button> inside the <form>, that button will be treated as the "submit" button.
<input type="text"> - HTML: Hypertext Markup Language
WebHTMLElementinputtext
<input> elements of type text create basic single-line text fields.
... using text inputs <input> elements of type text create basic, single-line inputs.
<input type="url"> - HTML: Hypertext Markup Language
WebHTMLElementinputurl
using url inputs when you create a url input with the proper type value, url, you get automatic validation that the entered text is at least in the correct form to potentially be a legitimate url.
... the example below creates a 30-character wide url address entry box, requiring that the contents be no shorter than 10 characters and no longer than 80 characters.
<select>: The HTML Select element - HTML: Hypertext Markup Language
WebHTMLElementselect
you can further nest <option> elements inside <optgroup> elements to create separate groups of options inside the dropdown.
... for more useful information on styling <select>, see: styling html forms advanced styling for html forms examples basic select the following example creates a very simple dropdown menu, the second option of which is selected by default.
<shadow>: The obsolete Shadow Root element - HTML: Hypertext Markup Language
WebHTMLElementshadow
you might have used it if you have created multiple shadow roots under a shadow host.
...--> <div> <!-- this heading will not be displayed --> <h4>my original heading</h4> </div> <script> // get the <div> above with its content var origcontent = document.queryselector('div'); // create the first shadow root var shadowroot1 = origcontent.createshadowroot(); // create the second shadow root var shadowroot2 = origcontent.createshadowroot(); // insert something into the older shadow root shadowroot1.innerhtml = '<p>older shadow root inserted by &lt;shadow&gt;</p>'; // insert into younger shadow root, including <shadow>.
<template>: The Content Template element - HTML: Hypertext Markup Language
WebHTMLElementtemplate
now that the table has been created and the template defined, we use javascript to insert rows into the table, with each row being constructed using the template as its basis.
...if ('content' in document.createelement('template')) { // instantiate the table with the existing html tbody // and the row with the template var tbody = document.queryselector("tbody"); var template = document.queryselector('#productrow'); // clone the new row and insert it into the table var clone = template.content.clonenode(true); var td = clone.queryselectorall("td"); td[0].textcontent = "1235646565"; td[1].textcontent = "stuff"; tbody.appendchild(clone); // clone the new row and insert it into the table var clone2 = template.content.clonenode(true); td = clone2.queryselectorall("td"); td[0...
<th> - HTML: Hypertext Markup Language
WebHTMLElementth
to create a similar effect use the background-color property in css instead.
...additional space can be added with the cellspacing and cellpadding properties and the width of the <col> element can also create extra width.
<tt>: The Teletype Text element (obsolete) - HTML: Hypertext Markup Language
WebHTMLElementtt
the obsolete html teletype text element (<tt>) creates inline text which is presented using the user agent's default monospace font face.
... this element was created for the purpose of rendering text as it would be displayed on a fixed-width display such as a teletype, text-only screen, or line printer.
dropzone - HTML: Hypertext Markup Language
it can have the following values: copy, which indicates that dropping will create a copy of the element that was dragged.
... link, which will create a link to the dragged data.
itemscope - HTML: Hypertext Markup Language
specifying the itemscope attribute for an element creates a new item, which results in a number of name-value pairs that are associated with the element.
... itemscope itemtype movie itemprop (itemprop name) (itemprop value) itemprop director james cameron itemprop genre science fiction itemprop name avatar itemprop https://youtu.be/0ay1xikx7by trailer itemscope id attributes when you specify the itemscope attribute for an element, a new item is created.
Microdata - HTML: Hypertext Markup Language
to create an item, the itemscope attribute is used.
...itemscope creates the item and defines the scope of the itemtype associated with it.
Preloading content with rel="preload" - HTML: Hypertext Markup Language
for example, here we create a htmllinkelement instance, then attach it to the dom: var preloadlink = document.createelement("link"); preloadlink.href = "myscript.js"; preloadlink.rel = "preload"; preloadlink.as = "script"; document.head.appendchild(preloadlink); this means that the browser will preload the myscript.js file, but not actually use it yet.
... to use it, you could do this: var preloadedscript = document.createelement("script"); preloadedscript.src = "myscript.js"; document.body.appendchild(preloadedscript); this is useful when you want to preload a script, but then defer execution until exactly when you need it.
HTML: Hypertext Markup Language
WebHTML
by uploading content to the internet and linking it to pages created by other people, you become an active participant in the world wide web.
... introduction to html this module sets the stage, getting you used to important concepts and syntax such as looking at applying html to text, how to create hyperlinks, and how to use html to structure a web page.
Basics of HTTP - HTTP
evolution of http http was created in the early 1990s and has been extended several times.
... connection management in http/2 http/2 completely revisited how connections are created and maintained.
Connection management in HTTP/1.x - HTTP
these connections were short-lived: a new one created each time a request needed sending, and closed once the answer had been received.
... two newer models were created in http/1.1.
Content-Location - HTTP
pointing to a new document (http 201 created) say you're creating a new blog post through a site's api: put /new/post host: example.com content-type: text/markdown # my first blog post!
...the server specifies where the new post is with content-location: http/1.1 201 created content-type: text/plain; charset=utf-8 content-location: /my-first-blog-post ✅ success!
Content-Security-Policy - HTTP
csp in workers workers are in general not governed by the content security policy of the document (or parent worker) that created them.
...in this case, the worker does inherit the content security policy of the document or worker that created it.
Iterators and generators - JavaScript
once created, an iterator object can be iterated explicitly by repeatedly calling next().
...its final return value is the size of the sequence it created, tracked by the variable iterationcount.
Keyed collections - JavaScript
(this can be bypassed using map = object.create(null).) these three tips can help you to decide whether to use a map or an object: use maps over objects when keys are unknown until run time, and when all keys are the same type and all values are the same type.
... let myset = new set(); myset.add(1); myset.add('some text'); myset.add('foo'); myset.has(1); // true myset.delete('foo'); myset.size; // 2 for (let item of myset) console.log(item); // 1 // "some text" converting between array and set you can create an array from a set using array.from or the spread operator.
JavaScript technologies overview - JavaScript
introduction whereas html defines a webpage's structure and content and css sets the formatting and appearance, javascript adds interactivity to a webpage and creates rich web applications.
... among other things, ecmascript defines: language syntax (parsing rules, keywords, control flow, object literal initialization, ...) error handling mechanisms (throw, try...catch, ability to create user-defined error types) types (boolean, number, string, function, object, ...) the global object.
extends - JavaScript
the extends keyword is used in class declarations or class expressions to create a class that is a child of another class.
... examples using extends the first example creates a class called square from a class called polygon.
Deprecated and obsolete features - JavaScript
proxy proxy.create and proxy.createfunction are deprecated.
... object.getnotifier() creates an object that allows to synthetically trigger a change.
TypeError: More arguments needed - JavaScript
message typeerror: argument is not an object and is not null (edge) typeerror: object.create requires at least 1 argument, but only 0 were passed typeerror: object.setprototypeof requires at least 2 arguments, but only 0 were passed typeerror: object.defineproperties requires at least 1 argument, but only 0 were passed error type typeerror.
... examples required arguments not provided the object.create() method requires at least one argument and the object.setprototypeof() method requires at least two arguments: var obj = object.create(); // typeerror: object.create requires at least 1 argument, but only 0 were passed var obj = object.setprototypeof({}); // typeerror: object.setprototypeof requires at least 2 arguments, but only 1 were passed you can fix this by setting null as the prototype, for example: var obj = object.create(null); var obj = object.setprototypeof({}, null); ...
TypeError: can't delete non-configurable array element - JavaScript
usually, properties in an object created by an array initializer are configurable.
... examples non-configurable properties created by object.defineproperty the object.defineproperty() creates non-configurable properties by default if you haven't specified them as configurable.
TypeError: "x" is not a constructor - JavaScript
examples invalid cases var car = 1; new car(); // typeerror: car is not a constructor new math(); // typeerror: math is not a constructor new symbol(); // typeerror: symbol is not a constructor function* f() {}; var obj = new f; // typeerror: f is not a constructor a car constructor suppose you want to create an object type for cars.
...to do this, you would write the following function: function car(make, model, year) { this.make = make; this.model = model; this.year = year; } now you can create an object called mycar as follows: var mycar = new car('eagle', 'talon tsi', 1993); in promises when returning an immediately-resolved or immediately-rejected promise, you do not need to create a new promise(...) and act on it.
TypeError: "x" is (not) "y" - JavaScript
also, certain methods, such as object.create() or symbol.keyfor(), require a specific type, that must be provided.
... examples invalid cases // undefined and null cases on which the substring method won't work var foo = undefined; foo.substring(1); // typeerror: foo is undefined var foo = null; foo.substring(1); // typeerror: foo is null // certain methods might require a specific type var foo = {} symbol.keyfor(foo); // typeerror: foo is not a symbol var foo = 'bar' object.create(foo); // typeerror: "foo" is not an object or null fixing the issue to fix null pointer to undefined values, you can use the typeof operator, for example.
Arrow function expressions - JavaScript
that.age++; }, 1000); } alternatively, a bound function could be created so that a preassigned this value would be passed to the bound target function (the growup() function in the example above).
...let's see what happens when we try to use them as methods: 'use strict'; var obj = { // does not create a new scope i: 10, b: () => console.log(this.i, this), c: function() { console.log(this.i, this); } } obj.b(); // prints undefined, window {...} (or the global object) obj.c(); // prints 10, object {...} arrow functions do not have their own this.
arguments[@@iterator]() - JavaScript
syntax arguments[symbol.iterator]() examples iteration using for...of loop function f() { // your browser must support for..of loop // and let-scoped variables in for loops for (let letter of arguments) { console.log(letter); } } f('w', 'y', 'k', 'o', 'p'); specifications specification ecmascript (ecma-262)the definition of 'createunmappedargumentsobject' in that specification.
... ecmascript (ecma-262)the definition of 'createmappedargumentsobject' in that specification.
getter - JavaScript
it is not possible to simultaneously have a getter bound to a property and have that property actually hold a value, although it is possible to use a getter and a setter in conjunction to create a type of pseudo-property.
... examples defining a getter on new objects in object initializers this will create a pseudo-property latest for object obj, which will return the last array item in log.
Array.isArray() - JavaScript
polyfill running the following code before any other code will create array.isarray() if it's not natively available.
... var iframe = document.createelement('iframe'); document.body.appendchild(iframe); xarray = window.frames[window.frames.length-1].array; var arr = new xarray(1,2,3); // [1,2,3] // correctly checking for array array.isarray(arr); // true // considered harmful, because doesn't work through iframes arr instanceof array; // false specifications specification ecmascript (ecma-262)the definition of 'array.isa...
Array.prototype.join() - JavaScript
the join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string.
... examples joining an array four different ways the following example creates an array, a, with three elements, then joins the array four times: using the default separator, then a comma and a space, then a plus and an empty string.
Array.prototype.pop() - JavaScript
examples removing the last element of an array the following code creates the myfish array containing four elements, then removes its last element.
... var myfish = ['angel', 'clown', 'mandarin', 'sturgeon']; var popped = myfish.pop(); console.log(myfish); // ['angel', 'clown', 'mandarin' ] console.log(popped); // 'sturgeon' using apply( ) or call ( ) on array-like objects the following code creates the myfish array-like object containing four elements and a length parameter, then removes its last element and decrements the length parameter.
Array.prototype.reverse() - JavaScript
examples reversing the elements in an array the following example creates an array a, containing three elements, then reverses the array.
... const a = [1, 2, 3]; console.log(a); // [1, 2, 3] a.reverse(); console.log(a); // [3, 2, 1] reversing the elements in an array-like object the following example creates an array-like object a, containing three elements and a length property, then reverses the array-like object.
Array.prototype.slice() - JavaScript
examples return a portion of an existing array let fruits = ['banana', 'orange', 'lemon', 'apple', 'mango'] let citrus = fruits.slice(1, 3) // fruits contains ['banana', 'orange', 'lemon', 'apple', 'mango'] // citrus contains ['orange','lemon'] using slice> in the following example, slice creates a new array, newcar, from mycar.
... // using slice, create newcar from mycar.
BigInt - JavaScript
description a bigint is created by appending n to the end of an integer literal — 10n — or by calling the function bigint().
... if (0n) { console.log('hello from the if!') } else { console.log('hello from the else!') } // ↪ "hello from the else!" 0n || 12n // ↪ 12n 0n && 12n // ↪ 0n boolean(0n) // ↪ false boolean(12n) // ↪ true !12n // ↪ false !0n // ↪ true constructor bigint() creates a new bigint value.
Boolean - JavaScript
all other values, including any object, an empty array ([]), or the string "false", create an object with an initial value of true.
... constructor boolean() creates a new boolean object.
DataView - JavaScript
precision may be lost'); return combined; } alternatively, if you need full 64-bit range, you can create a bigint.
...(right<<bigthirtytwo)|left : (left<<bigthirtytwo)|right; } constructor dataview() creates a new dataview object.
Error.prototype.toSource() - JavaScript
this string can be evaluated to create an (approximately) equal object.
... note: be aware that the properties used by the tosource method in the creation of this string are mutable and may not accurately reflect the function used to create an error instance or the filename or line number where the actual error occurred.
FinalizationRegistry() constructor - JavaScript
the finalizationregistry constructor creates a finalizationregistry object that uses the given callback.
... examples creating a new registry you create the registry passing in the callback: const registry = new finalizationregistry(heldvalue => { // ....
Intl.ListFormat() constructor - JavaScript
the intl.listformat() constructor creates objects that enable language-sensitive list formatting.
... examples using format the following example shows how to create a list formatter using the english language.
Intl.Locale - JavaScript
description the intl.locale object was created to allow for easier manipulation of unicode locales.
... constructor intl.locale() creates a new locale object.
JSON.stringify() - JavaScript
symbols: json.stringify({ x: undefined, y: object, z: symbol('') }); // '{}' json.stringify({ [symbol('foo')]: 'foo' }); // '{}' json.stringify({ [symbol.for('foo')]: 'foo' }, [symbol.for('foo')]); // '{}' json.stringify({ [symbol.for('foo')]: 'foo' }, function(k, v) { if (typeof k === 'symbol') { return 'a symbol'; } }); // undefined // non-enumerable properties: json.stringify( object.create(null, { x: { value: 'x', enumerable: false }, y: { value: 'y', enumerable: true } }) ); // '{"y":"y"}' // bigint values throw json.stringify({x: 2n}); // typeerror: bigint value can't be serialized in json the replacer parameter the replacer parameter can be either a function or an array.
...ux" }) //'{"foo":"bar","baz":"quux"}' var b = json.stringify({ baz: "quux", foo: "bar" }) //'{"baz":"quux","foo":"bar"}' console.log(a !== b) // true // some memoization functions use json.stringify to serialize arguments, // which may cause a cache miss when encountering 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 }); sessio...
Math.clz32() - JavaScript
however, a clon function can easily be created by inversing the bits of a number and passing the result to math.clz32.
... consider the following 32-bit word: var a = 32776; // 00000000000000001000000000001000 (16 leading zeros) math.clz32(a); // 16 var b = ~32776; // 11111111111111110111111111110111 (32776 inversed, 0 leading zeros) math.clz32(b); // 0 (this is equal to how many leading one's there are in a) using this logic, a clon function can be created as follows: var clz = math.clz32; function clon(integer){ return clz(~integer); } further, this technique could be extended to create jumpless "count trailing zeros" and "count trailing ones" functions as seen below.
Math.fround() - JavaScript
this can create confusion: checking a 64-bit float and a 32-bit float for equality may fail even though the numbers are seemingly identical.
... because fround() is a static method of math, you always use it as math.fround(), rather than as a method of a math object you created (math is not a constructor).
Number() constructor - JavaScript
the number() constructor creates a number object.
... syntax new number(value) parameters value the numeric value of the object being created.
Object() constructor - JavaScript
the object constructor creates an object wrapper for the given value.
... if the value is null or undefined, it will create and return an empty object.
Object.getOwnPropertyDescriptors() - JavaScript
examples creating a shallow clone whereas the object.assign() method will only copy enumerable and own properties from a source object to a target object, you are able to use this method and object.create() for a shallow copy between two unknown objects: object.create( object.getprototypeof(obj), object.getownpropertydescriptors(obj) ); creating a subclass a typical way of creating a subclass is to define the subclass, set its prototype to an instance of the superclass, and then define properties on that instance.
...instead, you can use this code to set the prototype: function superclass() {} superclass.prototype = { // define your methods and properties here }; function subclass() {} subclass.prototype = object.create( superclass.prototype, { // define your methods and properties here } ); specifications specification ecmascript (ecma-262)the definition of 'object.getownpropertydescriptors' in that specification.
Object.setPrototypeOf() - JavaScript
instead, create a new object with the desired [[prototype]] using object.create().
...rty, we can easily define object.setprototypeof if it isn't available already: if (!object.setprototypeof) { // only works in chrome and firefox, does not work in ie: object.prototype.setprototypeof = function(obj, proto) { if(obj.__proto__) { obj.__proto__ = proto; return obj; } else { // if you want to return prototype of object.create(null): var fn = function() { for (var key in obj) { object.defineproperty(this, key, { value: obj[key], }); } }; fn.prototype = proto; return new fn(); } } } examples using object.setprototypeof var dict = object.setprototypeof(...
Object.prototype.toSource() - JavaScript
a cyclically linked list or a tree that can be traversed both ways, tosource() will not recreate the self-reference, as of firefox 24.
... examples using tosource() the following code defines the dog object type and creates thedog, an object of type dog: function dog(name, breed, color, sex) { this.name = name; this.breed = breed; this.color = color; this.sex = sex; } thedog = new dog('gabby', 'lab', 'chocolate', 'female'); calling the tosource() method of thedog displays the javascript source that defines the object: thedog.tosource(); // returns ({name:"gabby", breed:"lab", color:"chocolate", sex:"fe...
handler.setPrototypeOf() - JavaScript
approach 1: returning false this approach means that any mutating operation that throws an exception on failure to mutate, must create the exception itself.
... for example, object.setprototypeof() will create and throw a typeerror itself.
RangeError - JavaScript
this can be encountered when: passing a value that is not one of the allowed string values to string.prototype.normalize(), or when attempting to create an array of an illegal length with the array constructor, or when passing bad values to the numeric methods number.prototype.toexponential(), number.prototype.tofixed() or number.prototype.toprecision().
... constructor rangeerror() creates a new rangeerror object.
RegExp.prototype[@@replace]() - JavaScript
function (replacement) a function to be invoked to create the new substring.
... if pattern argument is not a regexp object, string.prototype.replace() doesn't call this method, nor creates a regexp object.
Set - JavaScript
constructor set() creates a new set object.
... static properties get set[@@species] the constructor function that is used to create derived objects.
String.fromCharCode() - JavaScript
the static string.fromcharcode() method returns a string created from the specified sequence of utf-16 code units.
... because fromcharcode() is a static method of string, you always use it as string.fromcharcode(), rather than as a method of a string object you created.
TypedArray.prototype.filter() - JavaScript
the filter() method creates a new typed array with all elements that pass the test implemented by the provided function.
... examples filtering out all small values the following example uses filter() to create a filtered typed array that has all elements with values less than 10 removed.
TypedArray.prototype.map() - JavaScript
the map() method creates a new typed array with the results of calling a provided function on every element in this typed array.
... examples mapping a typed array to a typed array of square roots the following code takes a typed array and creates a new typed array containing the square roots of the numbers in the first typed array.
WeakRef - JavaScript
constructor weakref() creates a new weakref object.
... notes on weakrefs some notes on weakrefs: if your code has just created a weakref for a target object, or has gotten a target object from a weakref's deref method, that target object will not be reclaimed until the end of the current javascript job (including any promise reaction jobs that run at the end of a script job).
WeakSet - JavaScript
execrecursively(obj => console.log(obj), foo); here, a weakset is created on the first run, and passed along with every subsequent function call (using the internal _refs parameter).
... constructor weakset() creates a new weakset object.
WebAssembly.CompileError() constructor - JavaScript
the webassembly.compileerror() constructor creates a new webassembly compileerror object, which indicates an error during webassembly decoding or validation.
... examples creating a new compileerror instance the following snippet creates a new compileerror instance, and logs its details to the console: try { throw new webassembly.compileerror('hello', 'somefile', 10); } catch (e) { console.log(e instanceof compileerror); // true console.log(e.message); // "hello" console.log(e.name); // "compileerror" console.log(e.filename); // "somefile" console.log(e.linenumber); // 10 ...
WebAssembly.CompileError - JavaScript
constructor webassembly.compileerror() creates a new webassembly.compileerror object.
... examples creating a new compileerror instance the following snippet creates a new compileerror instance, and logs its details to the console: try { throw new webassembly.compileerror('hello', 'somefile', 10); } catch (e) { console.log(e instanceof compileerror); // true console.log(e.message); // "hello" console.log(e.name); // "compileerror" console.log(e.filename); // "somefile" console.log(e.linenumber); ...
WebAssembly.Global() constructor - JavaScript
a webassembly.global() constructor creates a new global object representing a global variable instance, accessible from both javascript and importable/exportable across one or more webassembly.module instances.
... examples creating a new global instance the following example shows a new global instance being created using the webassembly.global() constructor.
WebAssembly.Instance() constructor - JavaScript
the webassembly.instance() constructor creates a new instance object which is a stateful, executable instance of a webassembly.module.
... importobject optional an object containing the values to be imported into the newly-created instance, such as functions or webassembly.memory objects.
WebAssembly.LinkError() constructor - JavaScript
the webassembly.linkerror() constructor creates a new webassembly linkerror object, which indicates an error during module instantiation (besides traps from the start function).
... examples creating a new linkerror instance the following snippet creates a new linkerror instance, and logs its details to the console: try { throw new webassembly.linkerror('hello', 'somefile', 10); } catch (e) { console.log(e instanceof linkerror); // true console.log(e.message); // "hello" console.log(e.name); // "linkerror" console.log(e.filename); // "somefile" console.log(e.linenumber); // 10 console.log(e.co...
WebAssembly.LinkError - JavaScript
constructor webassembly.linkerror() creates a new webassembly.linkerror object.
... examples creating a new linkerror instance the following snippet creates a new linkerror instance, and logs its details to the console: try { throw new webassembly.linkerror('hello', 'somefile', 10); } catch (e) { console.log(e instanceof linkerror); // true console.log(e.message); // "hello" console.log(e.name); // "linkerror" console.log(e.filename); // "somefile" console.log(e.linenumber); ...
WebAssembly.Module() constructor - JavaScript
a webassembly.module() constructor creates a new module object containing stateless webassembly code that has already been compiled by the browser and can be efficiently shared with workers, and instantiated multiple times.
... examples synchronously compiling a webassembly module var importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; function createwasmmodule(bytes) { return new webassembly.module(bytes); } fetch('simple.wasm').then(response => response.arraybuffer() ).then(bytes => { let mod = createwasmmodule(bytes); webassembly.instantiate(mod, importobject) .then(result => result.exports.exported_func() ); }) specifications specification webassembly javascript interfacethe definition of 'webassem...
WebAssembly.Module - JavaScript
constructor webassembly.module() creates a new module object.
...when the module is received, we create an instance from it using the webassembly.instantiate() method and invoke an exported function from inside it.
WebAssembly.RuntimeError() constructor - JavaScript
the webassembly.runtimeerror() constructor creates a new webassembly runtimeerror object — the type that is thrown whenever webassembly specifies a trap.
... examples creating a new runtimeerror instance the following snippet creates a new runtimeerror instance, and logs its details to the console: try { throw new webassembly.runtimeerror('hello', 'somefile', 10); } catch (e) { console.log(e instanceof runtimeerror); // true console.log(e.message); // "hello" console.log(e.name); // "runtimeerror" console.log(e.filename); // "somefile" console.log(e.linenumber); // 10 ...
WebAssembly.RuntimeError - JavaScript
constructor webassembly.runtimeerror() creates a new webassembly.runtimeerror object.
... examples creating a new runtimeerror instance the following snippet creates a new runtimeerror instance, and logs its details to the console: try { throw new webassembly.runtimeerror('hello', 'somefile', 10); } catch (e) { console.log(e instanceof runtimeerror); // true console.log(e.message); // "hello" console.log(e.name); // "runtimeerror" console.log(e.filename); // "somefile" console.log(e.linenumber); ...
WebAssembly.Table.prototype.set() - JavaScript
examples using table.set the following example (see table2.html source code and live version) creates a new webassembly table instance with an initial size of 2 references.
... var tbl = new webassembly.table({initial:2, element:"anyfunc"}); console.log(tbl.length); console.log(tbl.get(0)); console.log(tbl.get(1)); we then create an import object that contains a reference to the table: var importobj = { js: { tbl:tbl } }; finally, we load and instantiate a wasm module (table2.wasm) using the webassembly.instantiatestreaming(), log the table length, and invoke the two referenced functions that are now stored in the table (the table2.wasm module (see text representation) adds two function references to the table, both of which print out a...
eval() - JavaScript
this means, for instance, that function declarations create global functions, and that the code being evaluated doesn't have access to local variables within the scope where it's being called.
...} , false); closures are also helpful as a way to create parameterized functions without concatenating strings.
async function - JavaScript
the second timer is not created until the first has already fired, so the code finishes after 3 seconds.
... in concurrentstart, both timers are created and then awaited.
class - JavaScript
the class declaration creates a new class with a given name using prototype-based inheritance.
... examples a simple class declaration in the following example, we first define a class named polygon, then extend it to create a class named square.
for await...of - JavaScript
the for await...of statement creates a loop iterating over async iterable objects as well as on sync iterables, including: built-in string, array, array-like objects (e.g., arguments or nodelist), typedarray, map, set, and user-defined async/sync iterables.
... this example first creates an async iterable for a stream of data, then uses it to find the size of the response from the api.
for - JavaScript
the for statement creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement (usually a block statement) to be executed in the loop.
...if you are omitting this expression, you must make sure to break the loop in the body in order to not create an infinite loop.
throw - JavaScript
the following example creates an object of type userexception and uses it in a throw statement.
... /* * creates a zipcode object.
Authoring MathML - MathML
for example the following function verifies the mathml support by testing the mspace element (you may replace mspace with mpadded): function hasmathmlsupport() { var div = document.createelement("div"), box; div.innerhtml = "<math><mspace height='23px' width='77px'/></math>"; document.body.appendchild(div); box = div.firstchild.firstchild.getboundingclientrect(); document.body.removechild(div); return math.abs(box.height - 23) <= 1 && math.abs(box.width - 77) <= 1; } alternatively, the following ua string sniffing will allow to detect the rendering engines with native ...
...use the elements and the special chars panels to create various advanced mathematical constructs.
MathML documentation index - MathML
WebMathMLIndex
19 <mmultiscripts> mathml, mathml reference, mathml:element, mathml:script and limit schemata the mathml <mmultiscripts> element allows you to create tensor-like objects.
... 34 <mtable> mathml, mathml reference, mathml:element, mathml:tabular math the mathml <mtable> element allows you to create tables or matrices.
Web audio codec guide - Web media technologies
(desktop) 58 (mobile) no no 11 container support mp4, ogg, flac rtp / webrtc compatible no licensing fully open and free of any licensing requirements g.711 (pulse code modulation of voice frequencies) the g.711 specification, published by the international telecommunications union (itu), was initially created in 1972 to define standards for encoding the voice frequencies on telephone lines into digital form.
...this capability was introduced on each platform in different firefox releases: mp3 support with external library, by platform, in firefox platform first firefox version with mp3 support windows (vista and later) 22 android 20 linux (depends on gstreamer) 26 macos 35 opus the opus audio format was created by the xiph.org foundation as a fully open audio format; it has been standardized by ietf as rfc 6716.
Web media technologies
over the years, the web's ability to present, create, and manage audio, video, and other media has grown at an increasing pace.
... accessibility guide for media in web design in this guide, we cover ways web designers and developers can create content that is accessible to people with different capabilities.
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.
...in summary, we should always try to create our animations using css transitions/animations where possible.
Web Performance
in summary, we should always try to create our animations using css transitions/animations where possible.
... user timing api create application specific timestamps using the user timing api's "mark" and "measure" entry types - that are part of the browser's performance timeline.
How to make PWAs installable - Progressive web apps (PWAs)
that banner is automatically created by the browser, based on the information from the manifest file.
... the icon and the theme and background colors are used to create this screen.
Progressive loading - Progressive web apps (PWAs)
it's not unusual to have megabytes of image data to download before announcing the site is ready, but this again creates a bad perception of performance.
... intersectionobserver((items, observer) => { items.foreach((item) => { if(item.isintersecting) { loadimages(item.target); observer.unobserve(item.target); } }); }); imagestoload.foreach((img) => { observer.observe(img); }); } else { imagestoload.foreach((img) => { loadimages(img); }); } if the intersectionobserver object is supported, the app creates a new instance of it.
Web technology reference
the open web is based on a number of technologies which, together, can be used to create everything from simple sites to powerful web applications.
...html provides a means to create structured documents made up of blocks called html elements that are delineated by tags, written using angle brackets.
clip - SVG: Scalable Vector Graphics
WebSVGAttributeclip
the value of auto defines a clipping path along the bounds of the viewport created by the given element.
... value auto | rect() default value auto animatable yes the value auto defines a clipping path along the bounds of the viewport created by the given element.the value rect() defines a clipping rectangle following the following syntax: rect(<top>, <right>, <bottom>, <left>).
<a> - SVG: Scalable Vector Graphics
WebSVGElementa
the <a> svg element creates a hyperlink to other web pages, files, locations in the same page, email addresses, or any other url.
... svg's <a> element is a container, which means you can create a link around text (like in html) but also around any shape.
<polyline> - SVG: Scalable Vector Graphics
WebSVGElementpolyline
the <polyline> svg element is an svg basic shape that creates straight lines connecting several points.
... typically a polyline is used to create open shapes as the last point doesn't have to be connected to the first point.
Getting started - SVG: Scalable Vector Graphics
finally, svg can be created dynamically with javascript and injected into the html dom.
... a word on webservers now that you have an idea of how to create basic svg files, the next stage is to upload them to a webserver.
mimeTypes.rdf corruption - SVG: Scalable Vector Graphics
one way to check is to create a new profile and restart mozilla using that profile.
... create and remove a bogus file association this solution should work for mimetypes.rdf corruption, and requires little technical knowledge.
SVG: Scalable Vector Graphics
WebSVG
additionally, this means they can be created and edited with any text editor or with drawing software.
...this allows developers to create rich animations and interactive images.
Secure contexts - Web security
however, it’s important to note that if a non-secure context causes a new window to be created (with or without specifying noopener), then the fact that the opener was insecure has no effect on whether the new window is considered secure.
... that’s because the determination of whether or not a particular document is in a secure context is based only on considering it within the top-level browsing context with which it is associated — and not whether a non-secure context happened to be used to create it.
<xsl:attribute> - XSLT: Extensible Stylesheet Language Transformations
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the <xsl:attribute> element creates an attribute in the output document, using any values that can be accessed from the stylesheet.
... syntax <xsl:attribute name=name namespace=uri> template </xsl:attribute> required attributes name specifies the name of the attribute to be created in the output document.
Caching compiled WebAssembly modules - WebAssembly
the function starts off by defining some necessary constants: function instantiatecachedurl(dbversion, url, importobject) { const dbname = 'wasm-cache'; const storename = 'wasm-cache'; setting up the database the first helper function contained inside instantiatecachedurl() — opendatabase() — creates an object store for storing wasm modules, and also handles clearing out the database if the dbversion is updated; it returns a promise resolving to the new database.
...est.onsuccess = () => { resolve(request.result) }; request.onupgradeneeded = event => { var db = request.result; if (db.objectstorenames.contains(storename)) { console.log(`clearing out version ${event.oldversion} wasm cache`); db.deleteobjectstore(storename); } console.log(`creating version ${event.newversion} wasm cache`); db.createobjectstore(storename) }; }); } looking up modules in the database our next function — lookupindatabase() — provides a simple promise-based operation for looking up the given url in the object store we created above.
Builder - Archive of obsolete content
the add-on builder was a web-based development environment that allowed developers to create add-ons using the sdk apis, but without needing to use the jpm command line tool.
Reddit Example - Archive of obsolete content
this example add-on creates a panel containing the mobile version of reddit.
port - Archive of obsolete content
for example, here's an add-on that creates a page-worker and a button.
Communicating using "port" - Archive of obsolete content
for example, here's an add-on that creates a page-worker and a button.
Content Scripts - Archive of obsolete content
second, it means that content scripts can create objects without worrying about whether they might clash with objects added by page scripts.
Content Processes - Archive of obsolete content
security wrappers are created automatically, by the underlying host application.
Contributor's Guide - Archive of obsolete content
classes and inheritance a class is a blueprint from which individual objects are created.
Porting the Library Detector - Archive of obsolete content
main.js will create an array of icons corresponding to the array of library names, and use that to build the widget's html content dynamically: function buildwidgetviewcontent(librarylist) { widgetcontent = htmlcontentpreamble; librarylist.foreach(function(library) { widgetcontent += buildiconhtml(icons[library.name], library.name + "&lt;br&gt;version: " + library.version); }); widgetcontent +...
Program ID - Archive of obsolete content
when you create an xpi with jpm xpi: if the package.json does not include an id field, then the id written into the install.rdf is the value of the name field prepended with "@".
Working with Events - Archive of obsolete content
the following add-on creates a button and assigns a listener to the onclick property of the options object supplied to the button's constructor.
Guides - Archive of obsolete content
this guide explains how it's created, what it's used for and how to define your own.
addon-page - Archive of obsolete content
create a page that does not contain navigational elements.
base64 - Archive of obsolete content
var base64 = require("sdk/base64"); var encodeddata = base64.encode("hello, world"); var decodeddata = base64.decode(encodeddata); globals functions encode(data, charset) creates a base-64 encoded ascii string from a string of binary data.
passwords - Archive of obsolete content
you create credential objects to pass into the api, and the api also returns credential objects to you.
private-browsing - Archive of obsolete content
windows module will not list any private browser windows, generate any events for private browser windows, or let the add-on open any private browser windows the tabs module will not list any tabs that belong to private browser windows, and the add-on won't receive any events for such tabs any ui components will not be displayed in private browser windows any menus or menu items created using the context-menu will not be shown in context menus that belong to private browser windows the page-mod module will not attach content scripts to documents belonging to private browser windows any panel objects will not be shown if the active window is a private browser window the selection module will not include any selections made in private browser windows add-ons...
selection - Archive of obsolete content
(discontiguous selections can be created by the user with ctrl+click-and-drag.) events select this event is emitted whenever the user makes a new selection in a page.
simple-storage - Archive of obsolete content
jpm run --no-copy --profile path/to/profile/dir if you specify a non-existent profile, the same will be created, don't worry.
console/plain-text - Archive of obsolete content
globals constructors plaintextconsole(print) creates a console instance.
content/loader - Archive of obsolete content
example: the following code creates a wrapper on a hidden frame that reloads a web page in the frame every time the contenturl property is changed: var hiddenframes = require("sdk/frame/hidden-frame"); var { loader } = require("sdk/content/content"); var pageloader = loader.compose({ constructor: function pageloader(options) { options = options || {}; if (options.contenturl) this.contenturl = options.contenturl; ...
net/xhr - Archive of obsolete content
globals constructors xmlhttprequest() creates an xmlhttprequest.
util/collection - Archive of obsolete content
globals constructors collection([array]) creates a new collection.
util/list - Archive of obsolete content
globals constructors list(element1, element2, ...) constructor can takes any number of elements and creates an instance of list populated with the specified elements.
util/match-pattern - Archive of obsolete content
globals constructors matchpattern(pattern) this constructor creates match pattern objects that can be used to test urls.
util/object - Archive of obsolete content
extend(source1, source2, source3) is the equivalent of merge(object.create(source1), source2, source3).
package.json - Archive of obsolete content
these json objects will be used to create a preferences interface for the add-on in the add-ons manager unless the preferencesurl field is specified.
Tools - Archive of obsolete content
jpmignore use .jpmignore to ignore files from your xpi builds created via jpm.
Logging - Archive of obsolete content
the console.log() method prints an informational message: console.log("hello world"); try it out: create a new directory, and navigate to it execute jpm init, accepting all the defaults open "index.js" and add the line above execute jpm run firefox will start, and the following line will appear in the command window you used to execute jpm run: info: hello world!
Modifying the Page Hosted by a Tab - Archive of obsolete content
this add-on creates a button with mozilla favicon as an icon.
Troubleshooting - Archive of obsolete content
you will need to create an account with bugzilla, mozilla's bug tracker.
Using XPCOM without chrome - Archive of obsolete content
we can then create an object from it and add it as an observer to the bookmarks service.
Customizing the download progress bar - Archive of obsolete content
in your overlay file, add a javascript file between the <overlay> and </overlay> tags: <script type="application/javascript" src="chrome://myextension/content/downloads-overlay.js" /> the javascript file will look something like this: var mydownloadmanager = { defaultcreatedownloaditem : null, init : function fdm_init() { mydownloadmanager.defaultcreatedownloaditem = window.createdownloaditem; window.createdownloaditem = function(aattrs) { var dl = mydownloadmanager.defaultcreatedownloaditem(aattrs); if (dl) { if (...whatever condition you use to decide whether to change this download...) { dl.setattribute("...
Dialogs and Prompts - Archive of obsolete content
describing dialog windows dialogs in mozilla whenever you want to create a dialog in your application, use <dialog> (instead of usual <window>) as root element in the xul file.
HTML in XUL for rich tooltips - Archive of obsolete content
specifically, we create a rich tooltip that uses html instead of plain text.
Label and description - Archive of obsolete content
absolutely nothing!</description> text can also be made to wrap by inserting an <html:br/> element regardless of the css style, but this creates a hard-break that does not change as parent elements resize.
On page load - Archive of obsolete content
creating an overlay first, you need to create an overlay to one (or more, depending on which applications you target) of the following xul documents: application uri to overlay firefox chrome://browser/content/browser.xul thunderbird chrome://messenger/content/messenger.xul navigator from seamonkey chrome://navigator/content/navigator.xul attaching a script attach a script to your over...
Progress Listeners - Archive of obsolete content
example create an object which implements nsiwebprogresslistener: const state_start = ci.nsiwebprogresslistener.state_start; const state_stop = ci.nsiwebprogresslistener.state_stop; var mylistener = { queryinterface: xpcomutils.generateqi(["nsiwebprogresslistener", "nsisupportsweakreference"]), onstatechange: function(awebprogress, arequest, aflag, astatus)...
QuerySelector - Archive of obsolete content
); }; example: <label value="test!"/> <script type="text/javascript"><![cdata[ xuldocument.prototype.$ = function (selector) { // only for xul return this.queryselector(selector); }; alert(document.$('label')); // [object xulelement] ]]></script> document.prototype.$ = function (selector) { // only for plain xml return this.queryselector(selector); }; var foo = document.implementation.createdocument('somens', 'foo', null); // create an xml document <foo xmlns="somens"/> var bar = foo.createelementns('somens', 'bar'); // add <bar xmlns="somens"/> foo.documentelement.appendchild(bar); alert(foo.$('bar').nodename); // gives 'bar' element.prototype.$ = function (selector) { // works for html, xul, and plain xml return this.queryselector(selector); }; html example: <h1><a>test!<a/><...
Running applications - Archive of obsolete content
var file = components.classes["@mozilla.org/file/local;1"] .createinstance(components.interfaces.nsilocalfile); file.initwithpath("c:\\myapp.exe"); file.launch(); references nsiprocess nsilocalfile if you need to launch an executable bundled in your xpi, see code snippets:file i/o#getting your extension's folder.
JavaScript timers - Archive of obsolete content
in javascript programming language, all daemons are processes created by javascript timers or by a worker instantiation.
Toolbar - Archive of obsolete content
adding a toolbar button there are two tutorials available: an elaborate step by step tutorial for beginners: custom toolbar button a tutorial describing the steps needed to add a toolbar button assuming you already have a working extension and know the basics of extension development: creating toolbar buttons adding button by default when you create and deploy your extension and include a toolbar button for it by overlaying the customize toolbarpalette, it is not available by default.
XML-related code snippets - Archive of obsolete content
how to create a dom tree using xmlhttprequest parsing and serializing xml using xpath jxon (lossless javascript xml object notation) xsl transforms xlink xinclude xml:id xml:base support in old browsers xpointer svg namespaces, or why http://www.mozilla.org/keymaster/gat...re.is.only.xul is at the top of every xul document.
XPath - Archive of obsolete content
ollowing was moved from document.evaluate) obj.evaluate(xpathexpression,contextnode,namespaceresolver,resulttype,result); //obj and contextnode should be the same object, if context is a ajax xml object (example: returnedxml) this should be used as : returnedxml.evaluate(xpathexpression,returnedxml,namespaceresolver,returntype,result); //contextnode should be used in the one in which it was created //add by mooring 2008-11-15 16:00 china var xhr = new ajax('post','demo.xml',parsexml,'xml'); //ajax is a class written by javascript 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(wind...
Code snippets - Archive of obsolete content
rd manager code used to read and write passwords to/from the integrated password manager bookmarks code used to read and write bookmarks javascript debugger service code used to interact with the javascript debugger service svg general general information and utilities svg animation animate svg using javascript and smil svg interacting with script using javascript and dom events to create interactive svg embedding svg in html and xul using svg to enhance html or xul based markup xul widgets html in xul for rich tooltips dynamically embed html into a xul element to attain markup in a tooltip label and description special uses and line breaking examples tree setup and manipulation of trees using xul and js scrollbar changing style of scrollbars.
Displaying web content in an extension without security issues - Archive of obsolete content
clonenode() always creates a copy and textcontent only manipulates text.
Downloading JSON and JavaScript in extensions - Archive of obsolete content
this usually happens because the extension is trying to keep some of its code fresh and dynamic, and the developers don't want to create a new version of the extension for each script change.
Extension Library - Archive of obsolete content
this page was auto-generated because a user created a sub-page to this page.
Extension Packaging - Archive of obsolete content
a special kind of extension xpi, called the multiple item package, explains how to create this kind of package.
Extension Samples - Archive of obsolete content
this page was auto-generated because a user created a sub-page to this page.
Inline options - Archive of obsolete content
this method does not require you to create a chrome.manifest and set it's path.
Install Manifests - Archive of obsolete content
it contains metadata identifying the add-on, providing information about who created it, where more information can be found about it, which versions of what applications it is compatible with, how it should be updated, and so on.
Installing Extensions and Themes From Web Pages - Archive of obsolete content
the install first creates a parameter block: var params = { "foo": { url: aevent.target.href, iconurl: aevent.target.getattribute("iconurl"), hash: aevent.target.getattribute("hash"), tostring: function () { return this.url; } }; this specifies the display name (foo) for use in the confirmation dialog, the url to the extension (which is the link href, recall), the icon url to display...
Offering a context menu for form controls - Archive of obsolete content
this article presents information based on ehsan akhgari's form control context menu extension, which was created specifically to demonstrate how to do this.
Adding sidebars - Archive of obsolete content
the tabbox element the « xul reference « element creates a tabbed view of one or more tabpanel elements.
Useful Mozilla Community Sites - Archive of obsolete content
it's a very powerful tool you have when developing on top of the mozilla platform, and you should take advantage of it in order to create a truly successful add-on .
User Notifications and Alerts - Archive of obsolete content
notification boxes are very easy to create, and are very customizable: let nb = gbrowser.getnotificationbox(); let acceptbutton = new object(); let declinebutton = new object(); let message = this._bundle.getstring("xulschoolhello.friendmessage.label"); let that = this; acceptbutton.label = this._bundle.getstring("xulschoolhello.acceptbutton.label"); acceptbutton.accesskey = this._bundle.getstring("xulschoolhello.acceptbutton.ac...
Session store API - Archive of obsolete content
after that, the following steps are taken for each tab being restored: either an existing tab is reused or a new tab is created.
Signing an extension - Archive of obsolete content
create a certificate database first, create a certificate database that will be used for signing.
Using the Stylesheet Service - Archive of obsolete content
adding a stylesheet to use the stylesheet service, you get a reference to the service, create a uri and pass the uri to the stylesheet service's loadandregistersheet method.
Adding preferences to an extension - Archive of obsolete content
inside that, we create a file, defaults.js, that describes the default value of our preferences: pref("extensions.stockwatcher2.symbol", "goog"); the standard for third-party preferences, such as those used in extensions, is to use the string "extensions", a period, the name of the extension, another period, then a preference name, as seen in the example above.
XML data - Archive of obsolete content
you create a sample xml document, and a stylesheet that you can use to display it in your browser.
XUL user interfaces - Archive of obsolete content
you create a simple demonstration that runs in your mozilla browser.
Index of archived content - Archive of obsolete content
npapi plugin developer guide npapi plugin reference browser-side plug-in api npapi plug-in side api npanycallbackstruct npbyterange npclass npembedprint npevent npfullprint npidentifier npn newstream npnvariable npn_createobject npn_destroystream npn_enumerate npn_evaluate npn_forceredraw npn_getauthenticationinfo npn_getintidentifier npn_getproperty npn_getstringidentifier npn_getstringidentifiers npn_geturl npn_geturlnotify npn_getvalue npn_getvalueforurl ...
Defining Cross-Browser Tooltips - Archive of obsolete content
authors are used to using the alt attribute to create "tooltips" in web browsers.
IO Guide - Archive of obsolete content
this page was auto-generated because a user created a sub-page to this page.
Images, Tables, and Mysterious Gaps - Archive of obsolete content
this would be especially true if there are many single-pixel cells intended to create cool stacked lines, or something like that.
Using XML Data Islands in Mozilla - Archive of obsolete content
for this demo, you must create an external document called purchase_order.xml: <!doctype html> <html> <head> <title>xml data block demo</title> <script> function rundemo() { var doc = document.getelementbyid("purchase-order").contentdocument; var lineitems = doc.getelementsbytagnamens("http://example.mozilla.org/purchaseorderml", "lineitem"); var firstprice = lineitems[0].getelementsbytagnamens("http://example.mozilla.or...
Using content preferences - Archive of obsolete content
var iosvc = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); var prefservice = components.classes["@mozilla.org/content-pref/service;1"] .getservice(components.interfaces.nsicontentprefservice); // create a uri object referencing the site to save a preference for var uri = iosvc.newuri("http://developer.mozilla.org/", null, null); // set the value of the "devmo.somesetting" preference to "foo".
How Mozilla finds its configuration files - Archive of obsolete content
all other files in that directory are dynamically created by mozilla on first start.
How Thunderbird and Firefox find their configuration files - Archive of obsolete content
all other files in that directory are dynamically created by mozilla on first start.
Introduction - Archive of obsolete content
our goal is to make it possible to automatically generate a mozilla configuration on the server for each user as soon as he is created.
Kill the XUL.mfl file for good - Archive of obsolete content
avoiding the creation of the xul.mfl file mozilla creates in its profile directory a file named xul.mfl, which contains pre-compiled ui elements.
Other Mozilla customization pages - Archive of obsolete content
other mozilla customization pages mcd, mission control desktop aka autoconfig pre-configuring mozilla mozexec, a mozilla launcher that writes a registry.bat before launching mozilla (contributed by petr kristan) mozptch: the main difference of the mozptch approach is, not to patch the registry.dat, but to create a new one with mozillas comandline option -createprofile.
Bookmark Keywords - Archive of obsolete content
in figure 2, we can see the bookmark has been filed into a folder called "widgets." you can create a folder with another name, or not put your keymarks into a folder at all.
Build - Archive of obsolete content
this page was auto-generated because a user created a sub-page to this page.
Chromeless - Archive of obsolete content
the aim is to enable developers to create full blown desktop applications using only web technologies.
Adding the structure - Archive of obsolete content
all xul elements can be given custom attributes in addition to the ones the xul rendering engine recognizes which get ignored by the engine, so adding this custom attribute does not create any problems or modify the way the widget is displayed (except for the ways we explicitly specify with css).
Conclusion - Archive of obsolete content
if the version you created in this tutorial doesn't work, compare it to this working version to help figure out the problem.
Enabling the behavior - retrieving tinderbox status - Archive of obsolete content
we use new to create a new instance of it, set the instance's onload property to updatetinderboxstatus(), the function we want to execute when the document finishes loading, call its open method with the type of http request we want to make and the url of the document to retrieve, and then call its send method to send the request.
Specifying the appearance - Archive of obsolete content
for this we have to first create four icons, one for each tinderbox state (none, success, test failed, and busted), then create a set of css rules that displays the icon corresponding to the current tinderbox state: statusbarpanel#tinderbox-status { list-style-image: url("chrome://navigator/content/tb-nostatus.png"); } statusbarpanel#tinderbox-status[status="success"] { list-style-image: url("chrome://navigator/content/tb-success.png"); } statusbarpanel#tinderbox-status[status="testfailed"] { list-style-image: url("chrome://navigator/content/tb-testfailed.png"); } statusbarpanel#tinderbox-status[status="busted"] { list-style-image: url("chrome://navigator/content/tb-buste...
Creating a Mozilla Extension - Archive of obsolete content
this tutorial describes how to create an extension for the old versions of mozilla suite (currently seamonkey).
Creating a Skin for Mozilla - Archive of obsolete content
introduction in order to create a skin for mozilla, you will need to know three things.
DTrace - Archive of obsolete content
the dtrace probes currently built into the codebase may be enabled by default in the future, but for now you'll need to create a build with --enable-dtrace (on mac os x you also have to use at least the 10.5 sdk for --with-macos-sdk, unlike the common configuration that uses the 10.4 sdk).
Dehydra Function Reference - Archive of obsolete content
this page was auto-generated because a user created a sub-page to this page.
Installing Dehydra - Archive of obsolete content
to run dehydra manually using g++, add the -fplugin and -fplugin-arg-gcc_dehydra-script/-fplugin-arg-gcc_treehydra-script flags to specify the location of the plugin and the location of the analysis script: g++ -quiet -fplugin=$home/dehydra/gcc_dehydra.so -fplugin-arg-gcc_dehydra-script=$dehydra_script \ -fshort-wchar $cppfile -s -o /dev/null for example, in the tests directory created by the installation procedure, i can run a dehydra script 'a.js' on a mozilla file like this: g++ -quiet -fplugin=../gcc_dehydra.so \ -fplugin-arg=a.js -fshort-wchar -fpreprocessed \ /home/dmandelin/builds/dehydra-gcc/browser/app/nsbrowserapp.ii -o /dev/null the -fshort-wchar is required for running against firefox, but not necessarily for other codebases.
Download Manager improvements in Firefox 3 - Archive of obsolete content
examples monitoring downloads an example showing how to use the new download manager apis to create a download log window that shows all past and present downloads and their status, including the start and end times of the downloads, the download speed, and more.
Content states and the style system - Archive of obsolete content
this list is created during the parsing of the stylesheets involved.
Documentation for BiDi Mozilla - Archive of obsolete content
it is created when resolving text containing a unicode bidi control character, a bdo tag, or right-to-left alignment caused by a dir tag or css.
Downloading Nightly or Trunk Builds - Archive of obsolete content
note that nightly builds may not be created for every platform for every night.
JSS build instructions for OSX 10.6 - Archive of obsolete content
nd_installing_nss/build_instructions https://developer.mozilla.org/jss_build_4.3.html ftp://ftp.mozilla.org/pub/mozilla.org/ <componente> /releases http://www.mozilla.org/projects/secu...using_jss.html steps: export all this: build_opt="1" cvsroot=":pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot" java_home=$(/usr/libexec/java_home") no_mdupdate="1" nsdistmode="copy" ns_use_gcc="1" create working dir: mkdir nss-jss cd nss-jss obtain source: altought manual said nspr_4_6_4_rtm, nss_3_11_4_rtm, jss_4_2_5_rtm, they didnt work for osx, giving many compiling errors.
Multiple Firefox profiles - Archive of obsolete content
this page was auto-generated because a user created a sub-page to this page.
Using microformats - Archive of obsolete content
loading the microformats api the microformats object is created using the new javascript script loader added to firefox 3.
Code snippets - Archive of obsolete content
components.utils.import("resource://services-sync/engines.js"); components.utils.import("resource://services-sync/engines/bookmarks.js"); let bme = weave.service.enginemanager.get("bookmarks"); let ids = object.keys(bme._store.getallids()); for each (let id in ids) { let record = bme._store.createrecord(id, "bookmarks"); let len = record.tostring().length; if (len > 1000) { console.log("id: " + id + ", len = " + len + ", " + record.title); } } print an alphabetically sorted list of members of a collection components.utils.import("resource://services-sync/main.js"); components.utils.import("resource://services-sync/resource.js"); let ids = json.parse(new resource(weave.service.s...
Syncing custom preferences - Archive of obsolete content
for example, if your add-on had a pref called extension.frobnaz.foobar, to have it synced, create a bool preference called services.sync.prefs.sync.extension.frobnaz.foobar and set it to true.
GRE Registration - Archive of obsolete content
xulrunner rpms/post-install scripts should register xulrunner as a gre by running <tt>xulrunner -register-global</tt> and not hand-create a .conf file.
Hidden prefs - Archive of obsolete content
see nsabquerystringtoexpression::createbooleanconditionstring() for other operators.
Isp Data - Archive of obsolete content
this page will explain how to create a .rdf or .xml file that you can place in the $installfolder/default/isp to do a variety of things.
Java in Firefox Extensions - Archive of obsolete content
these 2 objects let you make use of the standard jdk classes, e.g., var ajavalist = new java.util.linkedlist(); if you want to load your own jars, then you can create your own java class loader.
Jetpack Snippets - Archive of obsolete content
using firebug lite in a slidebar jetpack.future.import("slidebar");jetpack.slidebar.append({ html: <html><head></head><body> <p>some slidbar you want to debug</p> <a href="javascript:console.log('hello!')">test</a> <script><![cdata[ //firebug lite bookmarklet code: var firebug=document.createelement('script'); firebug.setattribute('src','http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js'); document.body.appendchild(firebug); (function(){if(window.firebug.version){firebug.init();}else{settimeout(arguments.callee);}})();void(firebug); ]]></script> </body></html>, width: 800, //wide enough to use firebu...
Dropbox - Archive of obsolete content
ArchiveMozillaJetpackUsersazaDropbox
this page was auto-generated because a user created a sub-page to this page.
aza - Archive of obsolete content
ArchiveMozillaJetpackUsersaza
this page was auto-generated because a user created a sub-page to this page.
Users - Archive of obsolete content
this page was auto-generated because a user created a sub-page to this page.
Meta - Archive of obsolete content
ArchiveMozillaJetpackdocsMeta
this page was auto-generated because a user created a sub-page to this page.
Storage - Archive of obsolete content
this page was auto-generated because a user created a sub-page to this page.
System - Archive of obsolete content
this page was auto-generated because a user created a sub-page to this page.
UI - Archive of obsolete content
ArchiveMozillaJetpackdocsUI
this page was auto-generated because a user created a sub-page to this page.
docs - Archive of obsolete content
this page was auto-generated because a user created a sub-page to this page.
statusBar - Archive of obsolete content
this page was auto-generated because a user created a sub-page to this page.
Metro browser chrome tests - Archive of obsolete content
sub directories for larger test suites may also be created.
Mozilla Application Framework - Archive of obsolete content
editor's note: this article should be rewritten to describe why use xulrunner to create your own application.
Bundles - Archive of obsolete content
how-to here is a simple way to build a basic web application bundle: create file called webapp.ini that contains something like: [parameters] id=unique-app-id@unique-author-id.whatever name=webapp name uri=http://[the-url-what-you-want-to-connect-to]/ status=yes location=no sidebar=no navigation=no zip the file to [whatever].webapp double-click the webapp bundle or use prism -webapp [path-to-webapp] structure a bundle can contain the following files.
Configuration - Archive of obsolete content
remember that other people can create different webapps using the same uri and this webapp is only your particular instance or mashup.
Prism - Archive of obsolete content
this includes the ability to create desktop shortcuts, to place the application icon in the tray or dock and to display pop-up notifications.
PyDOM - Archive of obsolete content
related topics pyxpcom: create and use xpcom components with python python-spidermonkey pydom samples: sample applications that use pydom pythonext: a firefox/xulrunner extension that can be used to install pydom ...
RDF API - Archive of obsolete content
this page was auto-generated because a user created a sub-page to this page.
Frequently Asked Questions - Archive of obsolete content
david continues to create svg enabled nightlies and answer build related questions as he has done for some time.
Static Analysis for Windows Code under Linux - Archive of obsolete content
dehydra requires patching gcc such that it can load plugins as shared libraries: # prepare a directory mkdir $home/dehydra cd $home/dehydra #obtain gcc 4.3 sources wget ftp://mirrors.kernel.org/gnu/gcc/gcc...-4.3.0.tar.bz2 tar jxvf gcc-4.3.0.tar.bz2 # get the patches which enable plugins cd gcc-4.3.0/ # create an hg repository.
Supporting private browsing mode - Archive of obsolete content
when private browsing mode is enabled, temporary, databases are created to be used for cookies and local storage; these databases are thrown away when private browsing mode is turned off, and the regular databases are re-activated.
Table Cellmap - Archive of obsolete content
<table> <tr><td>cell 1</td><td>cell 2</td></tr> <tr><td>cell 3</td><td>cell 4</td></tr> </table> this would create a cellmap with two rows and in each row 2 entries.
Table Layout Strategy - Archive of obsolete content
inside this routine the corresponding table layout strategy is created and initialized (basictablelayoutstrategy::initialize).
Abc Assembler Tests - Archive of obsolete content
* portions created by the initial developer are copyright (c) 2009 * the initial developer.
Tamarin Acceptance Test Template - Archive of obsolete content
* portions created by the initial developer are copyright (c) 2005-2010 * the initial developer.
Running Tamarin performance tests - Archive of obsolete content
ly display final summary --rebuildtests rebuild the tests only - do not run against vm --showtimes shows the time for each test --ascargs args to pass to asc on rebuild of test files --vmargs args to pass to vm --timeout max time to run all tests --testtimeout max time to let a test run, in sec (default -1 = never timeout) --html also create an html output file --notimecheck do not recompile .abc if timestamp is older than .as --java location of java executable (default=java) --javaargs arguments to pass to java --random run tests in random order --seed explicitly specify random seed for --random -s --avm2 second avmplus command to use --avmname nickname for avm t...
Tamarin Build System Documentation - Archive of obsolete content
create a user repository, instructions are https://developer.mozilla.org/en/publishing_mercurial_clones go to the request a sandbox build page http://tamarin-builds.mozilla.org/build_trigger/requestbuild.cfm enter the repository url, revision number, email address, and description.
Transforming XML with XSLT:Mozilla XSLT - Archive of obsolete content
this page was auto-generated because a user created a sub-page to this page.
Transforming XML with XSLT:The Netscape XSLT - Archive of obsolete content
this page was auto-generated because a user created a sub-page to this page.
Tuning Pageload - Archive of obsolete content
so if you have more than content.maxtextrun characters of text in a row, we'll create multiple textnodes for it.
URIScheme - Archive of obsolete content
preferences see gecko.handlerservice.schemes.* scripting interface see nsiprotocolhandler to create a new protocol/scheme.
Using addresses of stack variables with NSPR threads on win16 - Archive of obsolete content
oid forkedthread(void *arg) { shareddata *shared = (shareddata*)arg; while (--shared->counter > 0) pr_waitcondvar(shared->cv, pr_interval_no_timeout); return; } /* forkedthread */ printn main(printn argc, char **argv) { prthread *thread; shareddata shared; shared.ml = pr_newlock(); shared.cv = pr_newcondvar(shared.ml); shared.counter = 10; thread = pr_createthread( pr_user_thread, forkedthread, &shared, pr_priority_normal, pr_local_thread, pr_joinable_thread, 0); do { pr_sleep(pr_secondstointerval(1)); pr_lock(shared.ml); if (0 == shared.counter) break; pr_notifycondvar(shared.cv); pr_unlock(shared.ml); } while (pr_true); rv = pr_jointhread(thread); return (pr_success == rv...
Venkman - Archive of obsolete content
bandhauer then went on to reflect that api into java, and create his cross platform front end, eventually producing netscape javascript debugger 1.0 and 1.1.
Video presentations - Archive of obsolete content
(as quicktime; 122 mb and 110 mb) release builds - from source tree to exe (part 1, part 2) learn how release builds of firefox are created.
Anonymous Content - Archive of obsolete content
in addition to having a single explicit parent (the bound element) the explicit children also have an arbitrary set of anonymous parents (created by bindings when child insertion points were used).
Binding Attachment and Detachment - Archive of obsolete content
for elements that are created during or after the load event is fired, no assumptions can be made regarding order of binding attachment.
File.macAlias - Archive of obsolete content
file.macalias in this example, a mac alias is created for software (applecd audio player) that is installed locally.
copy - Archive of obsolete content
if destination does not exist a new file will be created.
dirGetParent - Archive of obsolete content
example f = getfolder("program", "mynewdirectory"); err = file.dircreate(f); err = file.getparent(f) // returns "program" ...
move - Archive of obsolete content
description you must create a filespecobject for the destination directory to pass in for this function.
addDirectory - Archive of obsolete content
you create this object by passing a string representing the directory to the getfolder method.
addFile - Archive of obsolete content
you create this object by passing a string representing the directory to the getfolder method.
cancelInstall - Archive of obsolete content
for a list of possible values, and any custom errorcode created by install writer, see return codes.
getComponentFolder - Archive of obsolete content
if the specified subdirectory doesn't exist, it is created.
getFolder - Archive of obsolete content
if the specified subdirectory doesn't exist, it is created.
getWinRegistry - Archive of obsolete content
description use the getwinregistry method to create an object for manipulating the contents of the windows registry.
logComment - Archive of obsolete content
description the install log is created in the product directory by default (where the browser executable is) if it can be, and if the installation doesn't have proper permission, the install log is written to the user's profile directory.
registerChrome - Archive of obsolete content
filespecobjects like that required by this function are created using the getfolder method on the install object.
setPackageFolder - Archive of obsolete content
you create this object by passing a string representing the directory to the getfolder or getcomponentfolder method.
setRootKey - Archive of obsolete content
when you create a winreg object, it is set to access keys under the hkey_classes_root portion of the registry.
WinRegValue - Archive of obsolete content
winregvalue constructor (windows only) creates a winregvalue object.
Rich Web - Archive of obsolete content
this page was auto-generated because a user created a sub-page to this page.
align - Archive of obsolete content
use the flex attribute to create elements that stretch in the opposite direction.
autocompletesearch - Archive of obsolete content
the components are created using the name @mozilla.org/autocomplete/search;1?name= where name is listed in this attribute.
checkState - Archive of obsolete content
« xul reference home checkstate type: integer, values 0, 1, or 2 this attribute may be used to create three state buttons, numbered 0, 1 and 2.
menuitem.type - Archive of obsolete content
« xul reference home type type: one of the values below can be used to create checkable menuitems or for radio button menuitems.
next - Archive of obsolete content
ArchiveMozillaXULAttributenext
this can be used to create wizards that do not have a linear sequence.
popupalign - Archive of obsolete content
the example below shows how to create the traditional buttons with attached left mouse menus that exist in the 4.x communicator product.
textbox.type - Archive of obsolete content
xbl-specific note beware that if you create an xbl binding for a textbox, you need to use the appropriate extends attribute and changing type attribute on the tree won't have effect.
Uploading and Downloading Files - Archive of obsolete content
function uploadput(posturl, filepath) { var req = new xmlhttprequest(); req.open("put", posturl); req.setrequestheader("content-type", "text/plain"); req.onload = function(event) { alert(event.target.responsetext); } req.send(new file(filepath)); } in this example, a new input stream is created for a file, and is passed to the xmlhttprequest's send method.
Moving, Copying and Deleting Files - Archive of obsolete content
two file objects are created, the first is the file to copy, and the second is the directory in which to copy the file to.
addSession - Archive of obsolete content
this can be used to create a customized autocomplete results list.
appendCustomToolbar - Archive of obsolete content
the method returns the dom element for the created toolbar.
menulist.appendItem - Archive of obsolete content
« xul reference home appenditem( label, value, description ) return type: element creates a new menuitem element and adds it to the end of the menulist.
openPopup - Archive of obsolete content
unanchored popups may be created by supplying null as the anchor node.
OpenClose - Archive of obsolete content
unanchored popups with openpopup if the first argument to the openpopup method is null, this creates an unanchored popup.
database - Archive of obsolete content
« xul reference database type: nsirdfcompositedatasource returns the composite datasource created when all the datasources of an element are combined.
next - Archive of obsolete content
ArchiveMozillaXULPropertynext
this can be used to create wizards that do not have a linear sequence.
Sorting and filtering a custom tree view - Archive of obsolete content
this will not work for other types of trees, for example rdf-backed or ones created with dom methods.
Building Trees - Archive of obsolete content
for example, if the properties attribute was set to the value "?creator", you could style the photos created by different people differently.
Containment Properties - Archive of obsolete content
what happens is that the builder generates additional possible values for the ?child variable, so it creates an additional result for each one.
Multiple Rules - Archive of obsolete content
we assume that anyone that isn't male is female and use the second rule to create a disabled radio button for females.
Result Generation - Archive of obsolete content
while the information network created by the template builder contains a number of different pieces of necessary information, for the purposes of this discussion, we will only be interested in the list of possible results.
Rule Compilation - Archive of obsolete content
this way, different kinds of output can be created based on the specifics of the result.
Template Logging - Archive of obsolete content
in addition, each result generated when the template is first created and initialized is logged.
The Joy of XUL - Archive of obsolete content
together, xpcom and xpconnect enable developers to create xul applications that require the raw processing power of compiled languages (c/c++) or access to the underlying operating system.
Code Samples - Archive of obsolete content
const path = "c:\\windows\\charmap.exe" var file = components .classes["@mozilla.org/file/local;1"] .createinstance(components.interfaces.nsilocalfile) file.initwithpath(path) file.launch() open a web page if your button is in firefox or seamonkey, use code like this to open a web page.
Toolbars - Archive of obsolete content
custom toolbar button another example of how to create a toolbar button, complete with a sample extension you can download and try.
Adding Event Handlers to XBL-defined Elements - Archive of obsolete content
the following alternate syntax can be used when the code in a handler is more complex: <binding id="binding-name"> <handlers> <handler event="event-name"> -- handler code goes here -- </handler> </handlers> </binding> handlers example the following example adds some key handlers to create a very primitive local clipboard: example 1 : source <binding id="clipbox"> <content> <xul:textbox/> </content> <implementation> <field name="clipboard"/> </implementation> <handlers> <handler event="keypress" key="x" modifiers="control" action="this.clipboard=document.getanonymousnodes(this)[0].value; document.getanonymousnodes(this)[0].value='';"/> <handler event...
Adding HTML Elements - Archive of obsolete content
<html:img src="banner.jpg"/> <html:input type="checkbox" value="true"/> <html:table> <html:tr> <html:td> a simple table </html:td> </html:tr> </html:table> these examples will create an image from the file banner.jpg, a checkbox and a single-cell table.
Adding more elements - Archive of obsolete content
find files example so far source view next, we will look at how to create stacks.
Additional Install Features - Archive of obsolete content
during installation, a log file is created that contains the operations that are performed.
Box Model Details - Archive of obsolete content
/gatekeeper/there.is.only.xul"> <vbox flex="3"> <label control="t1" value="search text:"/> <textbox id="t1" style="min-width: 100px;" flex="1"/> </vbox> <vbox style="min-width: 150px;" flex="1" align="start"> <checkbox id="c1" label="ignore case"/> <spacer flex="1" style="max-height: 30px;"/> <button label="find"/> </vbox> </window> here, two vertical boxes are created, one for the textbox and the other for the check box and button.
Broadcasters and Observers - Archive of obsolete content
example 3 : source view <broadcasterset> <broadcaster id="colorchanger" style="color: black"/> </broadcasterset> <button label="test"> <observes element="colorchanger" attribute="style" onbroadcast="alert('color changed');"/> </button> <button label="observer" oncommand="document.getelementbyid('colorchanger').setattribute('style','color: red');" /> two buttons have been created, one labeled test and the other labeled observer.
Commands - Archive of obsolete content
command elements the command element is used to create commands which can be used to carry out operations.
Introduction to RDF - Archive of obsolete content
alternatively, data in other formats can be used and code written that will read the file and create rdf data from it.
Keyboard Shortcuts - Archive of obsolete content
_f9 vk_f10 vk_f11 vk_f12 vk_f13 vk_f14 vk_f15 vk_f16 vk_f17 vk_f18 vk_f19 vk_f20 vk_f21 vk_f22 vk_f23 vk_f24 vk_num_lock vk_scroll_lock vk_comma vk_period vk_slash vk_back_quote vk_open_bracket vk_back_slash vk_close_bracket vk_quote vk_help for example, to create a shortcut that is activated when the user presses alt and f5, do the following: <keyset> <key id="test-key" modifiers="alt" keycode="vk_f5"/> </keyset> the example below demonstrates some more keyboard shortcuts: <keyset> <key id="copy-key" modifiers="accel" key="c"/> <key id="find-key" keycode="vk_f3"/> <key id="switch-key" modifiers="control alt" key="1"/> </keyset> the first key...
Modifying the Default Skin - Archive of obsolete content
this directory should be created when you create a profile and some examples placed there.
More Event Handlers - Archive of obsolete content
the event handler gets the clientx and clienty properties and creates a string from them.
Numeric Controls - Archive of obsolete content
you can also use the value popup which creates a combination of the two types.
Progress Meters - Archive of obsolete content
xul has a progressmeter element which can be used to create these.
Updating Commands - Archive of obsolete content
it is also possible to create your own.
XBL Example - Archive of obsolete content
<binding id="slideshow"> <content> <xul:vbox flex="1"> <xul:deck xbl:inherits="selectedindex" selectedindex="0" flex="1"> <children/> </xul:deck> <xul:hbox> <xul:button xbl:inherits="label=previoustext"/> <xul:label flex="1"/> <xul:button xbl:inherits="label=nexttext"/> </xul:hbox> </xul:vbox> </content> </binding> this binding creates the slideshow structure that we want.
Urlbar-icons - Archive of obsolete content
create new image or button child elements to add your own items.
Using Visual Studio as your XUL IDE - Archive of obsolete content
there is a very nice schema created by mihailo lalevic.
Using spell checking in XUL - Archive of obsolete content
checking the spelling of a word to check the spelling of a word, you must first create an interface to the mozispellcheckingengine component and then call the check() method on the string you wish to test.
XUL Accesskey FAQ and Policies - Archive of obsolete content
if methods like confirm(), confirmex() or prompt() are being used to create a dialog, use an & before the button or checkbox text to make the next character an accesskey.
XUL FAQ - Archive of obsolete content
a list of projects (dead and active) aiming to create a xul ide/editor is at wikimo:xul:ide.
XUL element attributes - Archive of obsolete content
use the flex attribute to create elements that stretch in the opposite direction.
XUL accessibility guidelines - Archive of obsolete content
use the oncontextmenu event handler or the context attribute to create context menus.
XUL and RDF - Archive of obsolete content
this page was auto-generated because a user created a sub-page to this page.
attribute.align - Archive of obsolete content
use the flex attribute to create elements that stretch in the opposite direction.
description - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] this element is used to create a block of text.
editor - Archive of obsolete content
set the value of the editortype attribute to html to create an editor document.
listcell - Archive of obsolete content
tips if you need to right-align a cell's contents, you can do so like this: cell = document.createelement("listcell"); cell.setattribute("label", "this is the cell's label"); cell.setattribute("style", "text-align:right"); related elements listbox, listcol, listcols, listhead, listheader, listitem ...
menuitem - Archive of obsolete content
type type: one of the values below can be used to create checkable menuitems or for radio button menuitems.
menuseparator - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] used to create a separator between menu items.
panel - Archive of obsolete content
ArchiveMozillaXULpanel
unanchored popups may be created by supplying null as the anchor node.
preferences - Archive of obsolete content
, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods void firechangedevent(in domelement preference); creates and dispatches a changed (non-bubbling) event to the specified preference element.
progressmeter - Archive of obsolete content
in addition, an indeterminate progressmeter may be created by setting the mode attribute to undetermined.
promptBox - Archive of obsolete content
method overview nsidomelement appendprompt(args, onclosecallback); void removeprompt(nsidomelement aprompt); nodelist listprompts(nsidomelement aprompt); methods appendprompt() creates a new prompt, adding it to the tab.
separator - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] creates a small separating gap between elements.
spinbuttons - Archive of obsolete content
spin buttons are not used as separate elements, but are used in combination with other elements to create a control that can be increased and decreased.
statusbar - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] an element used to create a status bar, usually placed along the bottom of a window.
toolbarseparator - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] creates a separator between groups of toolbar items.
toolbox - Archive of obsolete content
the method returns the dom element for the created toolbar.
tooltip - Archive of obsolete content
unanchored popups may be created by supplying null as the anchor node.
treecol - Archive of obsolete content
*/ list-style-image: url("chrome://global/skin/checkbox/cbox-check.gif"); } for example: create a css file.
window - Archive of obsolete content
to set an icon for the window, create a platform-specific icon file <windowid>.ico and/or <windowid>.xpm and place or install these files into the <mozilla-directory>/chrome/icons/default/ directory.
Article - Archive of obsolete content
this page was auto-generated because a user created a sub-page to this page.
How to enable locale switching in a XULRunner application - Archive of obsolete content
demo"); // render locale menulist by iterating through the query result from getlocalesforpackage() const xul_ns = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"; var localelistbox = document.getelementbyid("locale-listbox"); var selecteditem = null; while(availablelocales.hasmore()) { var locale = availablelocales.getnext(); var listitem = document.createelementns(xul_ns, "listitem"); listitem.setattribute("value", locale); listitem.setattribute("label", locale); if (locale == selectedlocale) { // is this the current locale?
MacFAQ - Archive of obsolete content
taking advantage of the core code "openurl" from "nscommandlineservicemac.cpp", you'll see that it looks for "browser.chromeurl" before defaulting to navigator.xul, and this is called when an xulrunner app is already running, so: create a default preference of "browser.chromeurl" that points to your new "hiddenwindow" as such: "chrome://myxul/content/hiddenwindow.xul" next take the code below and drop it in, to create the hiddenwindow.xul (note: the debug function and nsicommandline try/catch can be removed, all you need is the window.arguments[0]) <?xml version="1.0"?> <window xmlns="http://www.mozilla.org/keymaster/gatekee...
xbDesignMode.js - Archive of obsolete content
* portions created by the initial developer are copyright (c) 2003 * the initial developer.
Gecko Compatibility Handbook - Archive of obsolete content
you can now start using the user-agent string you've just created by clicking tools | user agent switcher |the name you have chosen.
Mozilla.dev.apps.firefox-2006-10-06 - Archive of obsolete content
a wiki and irc channel have been created to track their progress.
2006-10-06 - Archive of obsolete content
sunbird release notes lightning release notes sunbird_0_3_release tag being created lilmatt announced the sunbird 0.3 realse tag being created.
2006-10-06 - Archive of obsolete content
a wiki and irc channel have been created to track their progress.
2006-10-13 - Archive of obsolete content
(user feels print belongs on the context menu along with back, reload, etc.) questions about programming for firefox a student questions how to create an extension that changes fonts, and how to capture website content before it is displayed.
2006-10-20 - Archive of obsolete content
how to create firefox extension (chrome) to add images next to urls ?
2006-11-10 - Archive of obsolete content
favicon as microsummary/feed/other stuff indicator suggestion about making the favicon create a bookmark for the page with a microsummary.
2006-11-24 - Archive of obsolete content
discussions microsummary w/ script a user created patch that will allow script to run in a sandbox during the update of a microsummary.
2006-11-17 - Archive of obsolete content
how to create top-level folders in inbox with an imap account on courier server.
2006-10-06 - Archive of obsolete content
https://bugzilla.mozilla.org/show_bug.cgi?id=354866 taking moz180-linux-tbox down temporarily oct 6th early afternoon (pdt) on october 5th rob helmer announced that: he will be taking the 1.8.0 branch (en-us and l10n) linux tinderbox down tomorrow afternoon (oct 6th, pdt) in order to clone the disks and create a staging server for the release automation work.
2006-11-10 - Archive of obsolete content
this feature consists of creating buttons using a small program, that allows you to create shortcuts to a particular address.
2006-11-24 - Archive of obsolete content
gecko 1.9 intl rendering peformance november 20th: boris zbarskyannounced that: we need to create an intl performance page set or multiple intl performance page sets and run at least the pageload tests for all of these pagesets, and preferably also some sort of dhtml tests using pages of the different types.
2006-10-13 - Archive of obsolete content
summary: mozilla.dev.l10n - october 13, 2006 announcements seamonkey 1.0.5 he-il seamonkey 1.0.5 in hebrew was released a while ago firefox 2 rc2 is out firefox 2 rc2 is out, to download click here sunbird_0_3_release tag being created sunbird_0_3_release tag being created seamonkey 1.1 localization freeze and beta upcoming there are no open blockers left.
2006-11-10 - Archive of obsolete content
discussions help about firefox 3 a discussion on how to syncronise mozilla_1_8_branch with the trunk, which tag should be used to check-in files on trunk, and when files will be pulled from trunk to create another branch (mozilla_1_9_branch?) for firefox 3.
2006-09-29 - Archive of obsolete content
he also created a bug report to get rid of the help hooks in page info that lead nowhere.
2006-11-17 - Archive of obsolete content
recycle array objects a user trying to overcome the need of using huge number of arrays (as vectors) asks if its possible to reuse unreferenced array objects instead of create new ones in spidermonkey.
2006-12-01 - Archive of obsolete content
it is basically a java classloader that creates classes from javascript files.
JS-Engine FAQ - Archive of obsolete content
newly created threads in js from mozilla_1_8_branch causes to hang in windows patch from bug 351602 should fix the problem.
2006-12-08 - Archive of obsolete content
discussions xpcom cpp to js callback engaging discussion on a problem with trying to call back from c++ to a javascript object using an interface the developer created with an idl.
mozilla.dev.apps.calendar - Archive of obsolete content
this page was auto-generated because a user created a sub-page to this page.
mozilla.dev.tech.js-engine - Archive of obsolete content
this page was auto-generated because a user created a sub-page to this page.
NPAPI plugin developer guide - Archive of obsolete content
s unix event handling for windowed plug-ins windowless plug-ins specifying that a plug-in is windowless invalidating the drawing area forcing a paint message making a plug-in opaque making a plug-in transparent creating 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 ...
Monitoring plugins - Archive of obsolete content
below are a number of javascript snippets that would be useful to developers trying to use this feature: registration to register for runtime notifications with the observer service you must create a class with an observe method which receives 3 parameters (subject, topic and data) as well as a register method that contains the following code: var observerservice = components.classes["@mozilla.org/observer-service;1"] .getservice (components.interfaces.nsiobserverservice); observerservice.addobserver(this, "experimental-notify-plugin-call", false); observing...
NPN_DestroyStream - Archive of obsolete content
this stream can be either a stream that the browser created and passed to the plug-in in npp_newstream(), or a stream created by the plug-in through a call to npn_newstream().
NPP - Archive of obsolete content
description gecko creates an npp structure for each plug-in instance and passes a pointer to it to npp_new().
NPP_NewStream - Archive of obsolete content
description npp_newstream notifies the plug-in when a new stream is created.
NPP_SetWindow - Archive of obsolete content
« gecko plugin api reference « plug-in side plug-in api summary tells the plug-in when a window is created, moved, sized, or destroyed.
NPP_Write - Archive of obsolete content
after a stream is created by a call to npp_newstream, the browser calls npp_write either: if the plug-in requested a normal-mode stream, the data in the stream is delivered to the plug-in instance in a series of calls to npp_writeready and npp_write.
NP_GetValue - Archive of obsolete content
instance parameter is null because no instance has been created.
NP_Initialize - Archive of obsolete content
description the browser calls this function only once: when a plug-in is loaded, before the first instance is created.
NP_Shutdown - Archive of obsolete content
note: if enough memory is available, the browser can keep the plug-in library loaded if it expects to create more instances in the near future.
Writing a plugin for Mac OS X - Archive of obsolete content
xcode will create a "build" directory next to the project file, and if you built it in release mode, that folder in turn contains a "release" directory with the plugin inside it.
Plugins - Archive of obsolete content
logging and debugging for multi-process plugins how to create a plugin log to aid in debugging problems with multi-process plugins.
Article - Archive of obsolete content
this page was auto-generated because a user created a sub-page to this page.
Proposal - Archive of obsolete content
spec exists newsgator feed extension created to make rss feeds work better with newsgator software.
Version - Archive of obsolete content
different people and groups have largely unilaterally created specifications that they called rss.
SAX - Archive of obsolete content
to create one, use the following code: var xmlreader = components.classes["@mozilla.org/saxparser/xmlreader;1"] .createinstance(components.interfaces.nsisaxxmlreader); after you created the sax parser, you need to set the handlers for the events you're interested in and fire off the parsing process.
TCP/IP Security - Archive of obsolete content
designing a cryptographically sound application protocol is very difficult, and implementing it properly is even more challenging, so creating new application layer security controls is likely to create vulnerabilities.
Threats - Archive of obsolete content
many threats against data and resources are possible because of mistakes—either bugs in operating system and applications that create exploitable vulnerabilities, or errors made by end users and administrators.
Tamarin Tracing Build Documentation - Archive of obsolete content
use the following command to create a copy of the tamarin repository: $ hg clone http://hg.mozilla.org/tamarin-tracing tamarin-tracing building tamarin building tamarin will create all the libraries for the avmplus and garbage collector (mmgc), and create a standalone executable, avmshell, for executing files in the abc file format.
Creating a Skin for Firefox - Archive of obsolete content
introduction in order to create a skin for firefox, there are three things you need to know: how to edit images, how to extract zip files, and how to modify css.
Scratchpad - Archive of obsolete content
chpad code, insert the result as a comment ctrl + l cmd + l ctrl + l re-evaluate current function ctrl + e cmd + e ctrl + e reload the current page, then run scratchpad code ctrl + shift + r cmd + shift + r ctrl + shift + r save the pad ctrl + s cmd + s ctrl + s open an existing pad ctrl + o cmd + o ctrl + o create a new pad ctrl + n cmd + n ctrl + n close scratchpad ctrl + w cmd + w ctrl + w pretty print the code in scratchpad ctrl + p cmd + p ctrl + p show autocomplete suggestions ctrl + space ctrl + space ctrl + space show inline documentation ctrl + shift + space ctrl + shift + space ctrl + shift + space source edito...
Using SSH to connect to CVS - Archive of obsolete content
once you have entered a passphrase, ssh-keygen will create two files, ~/.ssh/id_dsa and ~/.ssh/id_dsa.pub do not sendid_dsa.
References - Archive of obsolete content
ompatible with mozilla from nicolás lichtmaier complete css guide from westciv.com css lessons and tutorials from alsacreations html and css lessons and tutorials from htmldog.com preparing for standard-compliant browsers, part 1 from makiko itoh preparing for standard-compliant browsers, part 2 from makiko itoh javascript best practices lists 15 of the most frequent coding practices which create problems for javascript and dhtml-driven webpages.
Using the W3C DOM - Archive of obsolete content
// detect whether the browser supports textcontent or innertext if (typeof spanel.textcontent == 'string') { spanel.textcontent = 'some gall'; } else if (typeof spanel.innertext == 'string') { spanel.innertext = 'some gall'; // if neither are supported, use other dom methods } else { while (spanel.firstchild) { spanel.removechild(spanel.firstchild); } spanel.appendchild(document.createtextnode('some gall')); } </script> </body> the first part of the code gets a reference to the element.
Using workers in extensions - Archive of obsolete content
if you haven't already created an extension, or would like to refresh your memory, take a look at the previous articles in this series: creating a status bar extension creating a dynamic status bar extension adding preferences to an extension localizing an extension updating an extension to support multiple mozilla applications download the sample you may download the complete example: download the example.
-moz-window-shadow - Archive of obsolete content
initial valuedefaultapplies toall elements that create native windows, e.g.
-ms-scrollbar-3dlight-color - Archive of obsolete content
)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle> examples the following example shows how to create a style rule that sets the -ms-scrollbar-3dlight-color property for a <textarea> element.
-ms-scrollbar-base-color - Archive of obsolete content
)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle> examples this example uses -ms-scrollbar-base-color and -ms-scrollbar-arrow-color to create two <div> objects with different scroll bar color schemes.
-ms-scrollbar-darkshadow-color - Archive of obsolete content
)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle> examples the following example shows how to create a style rule that sets the -ms-scrollbar-darkshadow-color property for a <textarea> element.
-ms-scrollbar-highlight-color - Archive of obsolete content
)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle> examples this example uses -ms-scrollbar-highlight-color, -ms-scrollbar-face-color, and -ms-scrollbar-arrow-color to create two <div> objects with different scroll bar color schemes.
-ms-scrollbar-shadow-color - Archive of obsolete content
)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle> examples the following example shows how to create a style rule that sets the -ms-scrollbar-shadow-color property for a <textarea> element.
-ms-scrollbar-track-color - Archive of obsolete content
)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle> examples this example uses -ms-scrollbar-track-color, -ms-scrollbar-face-color, and -ms-scrollbar-arrow-color to create two <div> elements with different scroll bar color schemes.
-ms-wrap-flow - Archive of obsolete content
initial valueautoapplies toblock-level elementsinheritednocomputed valueas specifiedanimation typediscrete syntax values auto for floated elements, an exclusion is created; for all other elements, an exclusion is not created.
-ms-wrap-margin - Archive of obsolete content
remarks offsets created by the -ms-wrap-margin property are offset from the outside of the exclusion.
:-moz-system-metric() - Archive of obsolete content
this page was auto-generated because a user created a sub-page to this page.
::-ms-check - Archive of obsolete content
the ::-ms-check css pseudo-element is a microsoft extension that represents checkboxes and radio button groups created by <input type="checkbox"> and <input type="radio">.
::-ms-clear - Archive of obsolete content
the ::-ms-clear css pseudo-element creates a clear button at the edge of an <input type="text"> text control that clears the current value.
::-ms-reveal - Archive of obsolete content
the ::-ms-reveal css pseudo-element is a microsoft extension that is used to display a password reveal button for use with a password field created by <input type="password">.
::-ms-ticks-after - Archive of obsolete content
to do so would create three sets of tick marks, but the best user experience is one set.
::-ms-ticks-before - Archive of obsolete content
to do so would create three sets of tick marks, but the best user experience is one set.
::-ms-track - Archive of obsolete content
to do so would create three sets of tick marks, but the best user experience is one set.
E4X for templating - Archive of obsolete content
createbundle('chrome://myeext/locale/myext.properties'); if (args){ args = array.prototype.slice.call(arguments, 1); return strs.formatstringfromname(msg,args,args.length); } return strs.getstringfromname(msg); } for example, <toolbarbutton label={$s('mytoolbar.label')}/> conditionals function _if (cond, h, _else) { if (cond && cond != undefined) { // we need undefined ...
Accessing XML children - Archive of obsolete content
this gives an xml document of <foo> <bar> <baz/> <quux/> </bar> </foo> note, however, that assigning a non-xml value to a child element that doesn't exist will create that element.
Descendants and Filters - Archive of obsolete content
the filtering conditional therefore creates a list with just fido and killer as members.
Using JavaScript Generators in Firefox - Archive of obsolete content
function closegenerator() { settimeout(function() { generator.close(); }, 0); } // our main steps function databaseoperation() { mozindexeddb.open("mytestdatabase").onsuccess = grabevent; var event = yield; var db = event.target.result; if (db.version != "1.0") { db.setversion("1.0").onsuccess = grabevent; event = yield; var transaction = event.transaction; db.createobjectstore("stuff"); transaction.oncomplete = grabevent; yield; } db.transaction(["stuff"]).objectstore("stuff").get("foo").onsuccess = grabevent; event = yield; alert("got result: " + event.target.result); // we're all done.
Object.getNotifier() - Archive of obsolete content
the object.getnotifer() method was used to create an object that allows to synthetically trigger a change, but has been deprecated and removed in browsers.
Object.observe() - Archive of obsolete content
.setprototypeof(obj, {}); // [{name: '__proto__', object: <obj>, type: 'setprototype', oldvalue: <prototype>}] object.seal(obj); // [ // {name: 'foo', object: <obj>, type: 'reconfigure'}, // {name: 'bar', object: <obj>, type: 'reconfigure'}, // {object: <obj>, type: 'preventextensions'} // ] data binding // a user model var user = { id: 0, name: 'brendan eich', title: 'mr.' }; // create a greeting for the user function updategreeting() { user.greeting = 'hello, ' + user.title + ' ' + user.name + '!'; } updategreeting(); object.observe(user, function(changes) { changes.foreach(function(change) { // any time name or title change, update the greeting if (change.name === 'name' || change.name === 'title') { updategreeting(); } }); }); custom change type /...
Object.prototype.watch() - Archive of obsolete content
if you later recreate the property, the watchpoint is still in effect.
Archived JavaScript Reference - Archive of obsolete content
.new in javascriptthis chapter contains information about javascript's version history and implementation status for mozilla/spidermonkey-based javascript applications, such as firefox.number.tointeger()the number.tointeger() method used to evaluate the passed value and convert it to an integer, but its implementation has been removed.object.getnotifier()the object.getnotifer() method was used to create an object that allows to synthetically trigger a change, but has been deprecated and removed in browsers.object.observe()the object.observe() method was used for asynchronously observing the changes to an object.
JSObject - Archive of obsolete content
when a javascript object is sent to java, the runtime engine creates a java wrapper of type jsobject; when a jsobject is sent from java to javascript, the runtime engine unwraps it to its original javascript object type.
java - Archive of obsolete content
created by the java object is a top-level, predefined javascript object.
netscape - Archive of obsolete content
created by the netscape object is a top-level, predefined javascript object.
sun - Archive of obsolete content
created by the sun object is a top-level, predefined javascript object.
RDF: Resource Description Framework for metadata - Archive of obsolete content
ArchiveWebRDF
rdf datasource how-to a cookbook-style document describing how to create a native, client-side datasource that works with mozilla's rdf implementation.
background-size - Archive of obsolete content
i'm guessing not, just asking because having both rules in for 3.6 creates a strange effect: -moz-border-image gets inherited by every element on the page user:robertc 2009-08-08 -moz-border-image should not inherit.
Developing Mozilla XForms - Archive of obsolete content
you should create a new, clean profile for debugging.
Mozilla XForms Specials - Archive of obsolete content
custom control interface we have added a lot of functionality to our user interface, which allows the form authors to create custom controls.
RFE to the Custom Controls Interfaces - Archive of obsolete content
if you need to have a custom control that works with complext content or you find our interfaces too limiting to create the type of control that you have in mind, then this is the right place to pass along your requirements and any usecase that you are trying to solve.
Requests For Enhancement - Archive of obsolete content
ArchiveWebXFormsRFE
if you find that you can't create a custom control due to limitations in our interfaces or the functionality of our controls, then this is the right place to pass along your requirements.
XForms Styling - Archive of obsolete content
processors such as chiba create "old-style" html forms from xforms documents, and must be styled accordingly.
XForms Group Element - Archive of obsolete content
groups can be nested to create complex hierarchies.
Using XForms and PHP - Archive of obsolete content
$newnode = $dom->create_element("boo"); $root->append_child($newnode); ...
XForms - Archive of obsolete content
xforms custom controls custom controls lets the form author "skin" each xforms control through xbl, and create f.x.
Archived open Web documentation - Archive of obsolete content
talk:javascript reference the guide section links to an interesting document discussing how to create and use private variables in objects, which is great if you want to protect the various properties within an object from being poked at accidentally.
Describing microformats in JavaScript - Archive of obsolete content
if it's virtual, the virtualgetter() method will be called to attempt to create the property if it doesn't exist.
Fixing Table Inheritance in Quirks Mode - Archive of obsolete content
this represented a violation of css inheritance rules, and led many authors to create workarounds such as: <style type="text/css"> body, table, td {font-size: 11px;} </style> recreating legacy behavior to avoid "breaking" older pages that were authored with old-browser behaviors in mind, mozilla and related browsers will mimic old browsers when in "quirks" mode.
Common causes of memory leaks in extensions - Extensions
for example, the following code snippets — part of a bootstrap.js — will leak: function leakref() {} function modifydocument(document) { var a = document.createelement("a"); document.body.appendchild(a); // the new dom node holding a reference to leakref will prevent // that function object from being garbage collected and hence // will leak the whole bootstrap compartment.
Game monetization - Game development
selling resources if you're a graphic designer, you can sell the assets from the games you've created, or something brand new exclusively for that purpose at online shops like envato market.
3D games on the Web - Game development
see the building up a basic demo with playcanvas subpage for higher-level details, and further articles showing how to create demos using the playcanvas library, and the online editor.
Collision detection - Game development
a collision detection function to kick this all off we want to create a collision detection function that will loop through all the bricks and compare every single brick's position with the ball's coordinates as each frame is drawn.
Paddle and keyboard controls - Game development
let's create a function that will draw the paddle on the screen.
Track the score and win - Game development
add the following into your javascript, after the rest of your variables: var score = 0; you also need a drawscore() function, to create and update the score display.
Collision detection - Game development
create this new function as the bottom of your code, just before the closing </script> tag, as follows: function ballhitbrick(ball, brick) { brick.kill(); } and that's it!
Game over - Game development
add the code below inside the create() function; just after you define the ball's attributes is fine: game.physics.arcade.checkcollision.down = false; this will make the three walls (top, left and right) bounce the ball back, but the fourth (bottom) will disappear, letting the ball fall off the screen if the paddle misses it.
Randomizing gameplay - Game development
grant extra bonus points if bricks are destroyed rapidly, several-in-a-row (or other bonuses of your choosing.) create levels with different brick layouts.
Scaling - Game development
resize — creates the canvas with the same size as the available width and height, so you have to place the objects inside your game dynamically; this is more of an advanced mode.
The score - Game development
var scoretext; var score = 0; adding score text to the game display now add this line at the end of the create() function: scoretext = game.add.text(5, 5, 'points: 0', { font: '18px arial', fill: '#0095dd' }); the text() method can take four parameters: the x and y coordinates to draw the text at.
2D breakout game using Phaser - Game development
next » in this step-by-step tutorial, we create a simple mobile mdn breakout game written in javascript, using the phaser framework.
Touch Event Horizon - Game development
this article is for touch event horizon and a game related to it touch gestures and events link the example game github repository live demo setting up the canvas counting the taps touchstart, touchend collecting the bonus touchmove future developments summary this tutorial shows how to use touch events to create a game on a <canvas>.
Visual typescript game engine - Game development
create examples demos in minimum 20 gameplay variants (table games, actions, platformers, basic demo throw the api doc etc.).
Gecko FAQ - Gecko Redirect 1
gecko is so fast and so powerful that it's being used to create the user interface of some applications ("chrome") as well.
Accessibility tree (AOM) - MDN Web Docs Glossary: Definitions of Web-related terms
browsers then create an accessibility tree based on the dom tree, which is used by platform-specific accessibility apis for assistive technologies, such as screen readers.
Base64 - MDN Web Docs Glossary: Definitions of Web-related terms
in javascript there are two functions respectively for decoding and encoding base64 strings: btoa(): creates a base-64 encoded ascii string from a "string" of binary data ("btoa" should be read as "binary to ascii").
CRUD - MDN Web Docs Glossary: Definitions of Web-related terms
crud (create, read, update, delete) is an acronym for ways one can operate on stored data.
Closure - MDN Web Docs Glossary: Definitions of Web-related terms
in javascript, functions create a closure context.
Code splitting - MDN Web Docs Glossary: Definitions of Web-related terms
code splitting is a feature supported by bundlers like webpack and browserify which can create multiple bundles that can be dynamically loaded at runtime.
Cryptanalysis - MDN Web Docs Glossary: Definitions of Web-related terms
cryptanalysis creates techniques to break ciphers, in particular by methods more efficient than a brute-force search.
DOM (Document Object Model) - MDN Web Docs Glossary: Definitions of Web-related terms
nodes can be created, moved and changed.
Developer Tools - MDN Web Docs Glossary: Definitions of Web-related terms
developer tools (or "development tools" or short "devtools") are programs that allow a developer to create, test and debug software.
frame rate (FPS) - MDN Web Docs Glossary: Definitions of Web-related terms
they are able to have fewer frames per second because the illusion of life is created with motion blurs.
Flex Container - MDN Web Docs Glossary: Definitions of Web-related terms
these values create a flex formatting context for the element, which is similar to a block formatting context in that floats will not intrude into the container, and the margins on the container will not collapse with those of the items.
Fragmentainer - MDN Web Docs Glossary: Definitions of Web-related terms
in multiple-column layout the fragmentainer is the column box created when columns are defined on a multicol container.
Grid Column - MDN Web Docs Glossary: Definitions of Web-related terms
in addition, columns may be created in the implicit grid when items are placed outside of columns created in the explicit grid.
Grid container - MDN Web Docs Glossary: Definitions of Web-related terms
the direct children can now lay themselves out on any explicit grid defined using grid-template-columns and grid-template-rows, or on the implicit grid created when an item is placed outside of the explicit grid.
Grid Row - MDN Web Docs Glossary: Definitions of Web-related terms
in addition, rows may be created in the implicit grid when items are placed outside of rows created in the explicit grid.
Gutters - MDN Web Docs Glossary: Definitions of Web-related terms
these can be created in css grid layout using the grid-column-gap, grid-row-gap, or grid-gap properties.
Instance - MDN Web Docs Glossary: Definitions of Web-related terms
an object created by a constructor is an instance of that constructor.
PAC - MDN Web Docs Glossary: Definitions of Web-related terms
*/ } ret = findproxyforurl(url, host) see proxy auto-configuration (pac) file for details about how these are used and how to create new ones.
Parse - MDN Web Docs Glossary: Definitions of Web-related terms
the browser then creates a render tree from both these structures to be able to paint the content to the screen.
Polyfill - MDN Web Docs Glossary: Definitions of Web-related terms
for example, the object.create polyfill only contains the functionalities that are possible in a non-native implementation of object.create.
Preflight request - MDN Web Docs Glossary: Definitions of Web-related terms
rg if the server allows it, then it will respond to the preflight request with an access-control-allow-methods response header, which lists delete: http/1.1 204 no content connection: keep-alive access-control-allow-origin: https://foo.bar.org access-control-allow-methods: post, get, options, delete access-control-max-age: 86400 the preflight response can be optionally cached for the requests created in the same url using access-control-max-age header like in the above example.
Python - MDN Web Docs Glossary: Definitions of Web-related terms
it was created by guido van rossum as a successor to another language (called abc) between 1985 and 1990, and is currently used on a large array of domains like web development, desktop applications, data science, devops, and automation/productivity.
RTF - MDN Web Docs Glossary: Definitions of Web-related terms
three programmers in the microsoft word team created rtf in the 1980s, and microsoft continued to develop the format until 2008.
SLD - MDN Web Docs Glossary: Definitions of Web-related terms
additional subdomains can be created in order to provide additional information about various functions of a server or to delimit areas under the same domain.
SMPTE (Society of Motion Picture and Television Engineers) - MDN Web Docs Glossary: Definitions of Web-related terms
the society of motion picture and television engineers (smpte) is the professional association of engineers and scientists that develop and define standards and technologies used to create, broadcast, store, and present entertainment media.
SVG - MDN Web Docs Glossary: Definitions of Web-related terms
as a vector image format, svg graphics can scale infinitely, making them invaluable in responsive design, since you can create interface elements and graphics that scale to any screen size.
Scope - MDN Web Docs Glossary: Definitions of Web-related terms
a function serves as a closure in javascript, and thus creates a scope, so that (for example) a variable defined exclusively within the function cannot be accessed from outside the function or within other functions.
Scroll container - MDN Web Docs Glossary: Definitions of Web-related terms
a scroll container is created by applying overflow: scroll to a container, or overflow: auto when there is enough content to cause overflow.
Scrollport - MDN Web Docs Glossary: Definitions of Web-related terms
a scroll container is created by applying overflow: scroll to a container, or overflow: auto when there is enough content to cause overflow.
Second-level Domain - MDN Web Docs Glossary: Definitions of Web-related terms
additional subdomains can be created in order to provide additional information about various functions of a server or to delimit areas under the same domain.
Semantics - MDN Web Docs Glossary: Definitions of Web-related terms
would you need to look at the code to understand what the function did if it was called build('peach'), or createliwithcontent('peach')?
Session Hijacking - MDN Web Docs Glossary: Definitions of Web-related terms
protection against session hijacking create a secure communication channel with ssh (secure shell) pass authentication cookies over https connection implement logout functionality so the user can end the session generate the session id after successful login pass encrypted data between the users and the web server use a string or long random number as a session key learn more general knowledge session hijacking on wikipedia ...
Signature (security) - MDN Web Docs Glossary: Definitions of Web-related terms
on receiving the message, the verification process authenticates the sender - uses the sender's public key to decrypt the signature and recover the hash, which can only be created with the sender's private key, and checks message integrity - compares the hash with a newly calculated one from the received document (the two hashes will differ if the document has been tampered with) the system fails if the private key is compromised or the recipient is deceitfully given the wrong public key.
Slug - MDN Web Docs Glossary: Definitions of Web-related terms
it may also just be the final component when a new document is created under a parent document; for example, this page's slug is glossary/slug .
Static method - MDN Web Docs Glossary: Definitions of Web-related terms
a static method (or static function) is a method defined as a member of an object but is accessible directly from an api object's constructor, rather than from an object instance created via the constructor.
TOFU - MDN Web Docs Glossary: Definitions of Web-related terms
trust on first use (tofu) is a security model in which a client needs to create a trust relationship with an unknown server.
Transmission Control Protocol (TCP) - MDN Web Docs Glossary: Definitions of Web-related terms
tcp uses virtual ports to create a virtual end-to-end connection that can reuse the physical connections between two computers.
Unicode - MDN Web Docs Glossary: Definitions of Web-related terms
by assigning each character a number, programmers can create character encodings, to let computers store, process, and transmit any combination of languages in the same file or program.
Validator - MDN Web Docs Glossary: Definitions of Web-related terms
validators can be created for any format or language, but in our context we speak of tools that check html, css, and xml.
Vendor Prefix - MDN Web Docs Glossary: Definitions of Web-related terms
lately, the trend is to add experimental features behind user-controlled flags or preferences, and to create smaller specifications which can reach a stable state much more quickly.
WebDAV - MDN Web Docs Glossary: Definitions of Web-related terms
author or creation date) link pages of any media type to related pages create sets of documents and retrieve hierarchical list copy and move webpages lock a document from being edited by more than one person at a time learn more general knowledge webdav on wikipedia technical reference rfc 2518 rfc 3253 rfc 3744 ...
WebIDL - MDN Web Docs Glossary: Definitions of Web-related terms
webidl is used in nearly every api specification for the web, and due to its standard format and syntax, the programmers who create web browsers can more easily ensure that their browsers are compatible with one another, regardless of how they choose to write the code to implement the api.
World Wide Web - MDN Web Docs Glossary: Definitions of Web-related terms
he created the first web server, web browser, and webpage on his computer at the cern physics research lab in 1990.
XHR (XMLHttpRequest) - MDN Web Docs Glossary: Definitions of Web-related terms
xmlhttprequest (xhr) is a javascript api to create ajax requests.
XInclude - MDN Web Docs Glossary: Definitions of Web-related terms
request2.setrequestheader('cache-control', 'no-cache'); request2.send(null); response = request2[responsetype]; // update the response for processing } // replace xinclude with the response as text var textnode = docu.createtextnode(response); xincludeparent.replacechild(textnode, xinclude); } // replace xinclude in doc with response now (as plain text or xml) } } } catch (e) { // use xi:fallback if xinclude retrieval above failed var xifallbackchildren = xifallback...
Safe - MDN Web Docs Glossary: Definitions of Web-related terms
what is important here is that by calling a safe method, the client doesn't request any server change itself, and therefore won't create an unnecessary load or burden for the server.
Speculative parsing - MDN Web Docs Glossary: Definitions of Web-related terms
don't add it via document.write() or document.createelement.
undefined - MDN Web Docs Glossary: Definitions of Web-related terms
example var x; //create a variable but assign it no value console.log("x's value is", x) //logs "x's value is undefined" learn more general knowledge undefined value on wikipedia technical reference javascript data types and data structures ...
Mobile accessibility - Learn web development
alternatively, mouse-specific events such as mousedown and mouseup create problems — their event handlers cannot be invoked using non-mouse controls.
Backgrounds and borders - Learn web development
you can create a gradient then copy and paste out the source code that generates it.
Handling different text directions - Learn web development
we create borders on the top, right, bottom, and left of a box, for example.
Test your skills: Images and Form elements - Learn web development
try updating the live code below to recreate the example as displayed in the image: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor.
Combinators - Learn web development
it is often better to create a simple class and apply that to the element in question.
Pseudo-classes and pseudo-elements - Learn web development
look at the css as you create your arrow and you will see the ::before and ::after pseudo-elements in use.
CSS values and units - Learn web development
for example, understanding that <image> also allows you to create a color gradient is useful but perhaps non-obvious knowledge to have!
Test Your Skills: Fundamental layout comprehension - Learn web development
project brief you have been provided with some raw html, basic css, and images — now you need to create a layout for the design, which should look just like the image below.
Normal Flow - Learn web development
es/9e/6ff6af6fd4.jpg"></p> body { width: 500px; margin: 0 auto; } p { background: rgba(255,84,104,0.3); border: 2px solid rgb(255,84,104); padding: 10px; margin: 10px; } span { background: white; border: 1px solid black; } summary now that you understand normal flow, and how the browser lays things out by default, move on to understand how to change this default display to create the layout needed by your design.
How CSS works - Learn web development
again, the html is as follows: <p> let's use: <span>cascading</span> <span>style</span> <span>sheets</span> </p> let's suppose we apply the following css to it: span { border: 1px solid black; background-color: lime; } the browser will parse the html and create a dom from it, then parse the css.
Using your new knowledge - Learn web development
if you prefer you could move this css to a separate file when you create the example on your local computer.
CSS FAQ - Learn web development
LearnCSSHowtoCSS FAQ
the use of such properties on production websites is not recommended — they have already created a huge web compatibility mess.
Use CSS to solve common problems - Learn web development
LearnCSSHowto
how to create fancy boxes (also see the styling boxes module, generally).
Styling lists - Learn web development
lution" style="margin: 10px 0 0 10px;"> </div> </div> var htmlinput = document.queryselector(".html-input"); var cssinput = document.queryselector(".css-input"); var reset = document.getelementbyid("reset"); var htmlcode = htmlinput.value; var csscode = cssinput.value; var output = document.queryselector(".output"); var solution = document.getelementbyid("solution"); var styleelem = document.createelement('style'); var headelem = document.queryselector('head'); headelem.appendchild(styleelem); function drawoutput() { output.innerhtml = htmlinput.value; styleelem.textcontent = cssinput.value; } reset.addeventlistener("click", function() { htmlinput.value = htmlcode; cssinput.value = csscode; drawoutput(); }); solution.addeventlistener("click", function() { htmlinput.value = ht...
Styling text - Learn web development
note: if you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as jsbin, codepen or glitch.
Learn to style HTML using CSS - Learn web development
you should have a basic work environment set up as detailed in installing basic software and understand how to create and manage files, as detailed in dealing with files — both of which are parts of our getting started with the web complete beginner's module.
What do common web layouts contain? - Learn web development
because the image on the top-right is l-shaped, because b1 looks like a column supporting the shifted main content, and because the "m" and "i" of the mica logo create a vertical line of force.
What is a URL? - Learn web development
the html language — which will be discussed later on — makes extensive use of urls: to create links to other documents with the <a> element; to link a document with its related resources through various elements such as <link> or <script>; to display media such as images (with the <img> element), videos (with the <video> element), sounds and music (with the <audio> element), etc.; to display other html documents with the <iframe> element.
Sending forms through JavaScript - Learn web development
this creates a formdata object that represents the data contained in the form.
Your first form - Learn web development
the controls can be single or multi-line text fields, dropdown boxes, buttons, checkboxes, or radio buttons, and are mostly created using the <input> element, although there are some other elements to learn about too.
Web forms — Working with user data - Learn web development
note: if you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as jsbin or glitch.
Front-end web developer - Learn web development
subjects covered the subjects covered are: basic setup and learning how to learn web standards and best practices (such as accessibility and cross-browser compatibility) html, the language that gives web content structure and meaning css, the language used to style web pages javascript, the scripting language used to create dynamic functionality on the web tooling that is used to facilitate modern client-side web development.
HTML basics - Learn web development
try to create a meaningful sequence of headings on your pages, without skipping levels.
Getting started with the Web - Learn web development
the story of your first website it's a lot of work to create a professional website, so if you're new to web development, we encourage you to start small.
Add a hitmap on top of an image - Learn web development
prerequisites: you should already know how to create a basic html document and how to add accessible images to a webpage.
Getting started with HTML - Learn web development
create a new file in your text editor.
Marking up a letter - Learn web development
create a new .html file using your text editor or use an online tool such as codepen, jsfiddle, or glitch to complete the tasks.
Structuring a page of content - Learn web development
create the example on your local computer, or alternatively use an online tool such as codepen, jsfiddle, or glitch to work on the tasks.
What’s in the head? Metadata in HTML - Learn web development
this means that your web page will be able to handle displaying any language; it's therefore a good idea to set this on every web page you create!
Images in HTML - Learn web development
these are created for exactly this purpose: to provide a semantic container for figures, and to clearly link the figure to the caption.
From object to iframe — other embedding technologies - Learn web development
a short history of embedding a long time ago on the web, it was popular to use frames to create websites — small parts of a website stored in individual html pages.
Video and audio content - Learn web development
create a new html file in the same directory, called index.html.
Multimedia and Embedding - Learn web development
note: if you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as jsbin or glitch.
Assessment: Structuring planet data - Learn web development
create all the content rows inside the table body, remembering to make all the row headings into headings semantically.
HTML Tables - Learn web development
LearnHTMLTables
note: if you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as jsbin or glitch.
General asynchronous programming concepts - Learn web development
n so that when clicked, it runs a time-consuming operation (calculates 10 million dates then logs the final one to the console) and then adds a paragraph to the dom: const btn = document.queryselector('button'); btn.addeventlistener('click', () => { let mydate; for(let i = 0; i < 10000000; i++) { let date = new date(); mydate = date } console.log(mydate); let pelem = document.createelement('p'); pelem.textcontent = 'this is a newly-added paragraph.'; document.body.appendchild(pelem); }); when running the example, open your javascript console then click the button — you'll notice that the paragraph does not appear until after the dates have finished being calculated and the console message has been logged.
Asynchronous JavaScript - Learn web development
note: if you are working on a computer/tablet/other device where you don't have the ability to create your own files, you can try out (most of) the code examples in an online coding program such as jsbin or glitch.
Image gallery - Learn web development
looping through the images we've already provided you with lines that store a reference to the thumb-bar <div> inside a constant called thumbbar, create a new <img> element, set its src attribute to a placeholder value xxx, and append this new <img> element inside thumbbar.
Function return values - Learn web development
it is a good idea to create your own library of utility functions to do these sorts of things.
JavaScript building blocks - Learn web development
note: if you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as jsbin or glitch.
Client-side web APIs - Learn web development
note: if you are working on a device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as jsbin or glitch.
Basic math in JavaScript — numbers and operators - Learn web development
after you've answered all the above questions correctly, feel free to play with the code some more or create your own challenges.
Test your skills: JSON - Learn web development
try updating the live code below to recreate the finished example: warning: to answer this question, you'll need to write your code into the live code window above.
JavaScript performance - Learn web development
in the next article we take a look at some html features that can impact performance, including some attributes specifically created to improve performance.
The "why" of web performance - Learn web development
to build websites and applications people want to use; to attract and retain site visitors, you need to create an accessible site that provides a good user experience.
Properly configuring server MIME types - Learn web development
if your content was created using a vendor's software application, read the vendor's documentation to see what mime types should be reported for different media types.
Server-side website programming - Learn web development
the dynamic websites – server-side programming topic is a series of modules that show how to create dynamic websites; websites that deliver customised information in response to http requests.
Beginning our React todo list - Learn web development
pre-project housekeeping create-react-app has made a few files we won't be using at all for our project.
Using Vue computed properties - Learn web development
to create a computed property, we need to add a computed property to our component object, much like the methods property we've used previously.
Vue resources - Learn web development
this will create a new dist directory containing all of your production ready files.
Introduction to cross browser testing - Learn web development
cross browser testing is the practice of making sure that the web sites and web apps you create work across an acceptable number of web browsers.
Git and GitHub - Learn web development
different team members will commonly want to create their own separate versions of the code (called branches in git), work on a new feature in that version, and then get it merged in a controlled manner (in github we use pull requests) with the master version when they are done with it.
ChromeWorkers and the Chrome worker loader
note: if you're contributing content to this section, create subpages using the "new sub-page" option in the "this page" menu.
Information for External Developers Dealing with Accessibility
mac keys: keyboard shortcuts quick reference for mac os x complete reference on keyboard for mac os x: this document list all functions of specified keys, known keyboard shortcuts, explains how to create keyboard shortcuts, explains appropriate use for the arrow keys, how to move the insertion point with keys, how to extent text selection with keys, functions of function keys, what are reserved keyboard shortcuts, how to create your own keyboard shortcuts, keyboard focus and navigation, type-ahead and key-repeat, etc.
Multiprocess on Windows
use the mozilla::mscom::to*uniqueptr functions in ipc/mscom/ptr.h to create new instances of these.
Lightweight themes
how to create your own lightweight theme lightweight themes are made up of a "header" graphic image file, which skins the default firefox ui background.
Adding a new CSS property
while we implement the string api in terms of the value api, we generally don't care much about the deprecated primitive value api, so in cases where there's some new structure, you should generally create the simplest structure of primitive values that will produce the right string.
Application cache implementation overview
then creates a new nsiapplicationcache for the given manifest url using nsiapplicationcacheservice::createapplicationcache().
A bird's-eye view of the Mozilla framework
to summarize, the xpcom object model specifies the structure of xpcom components, builds a central registry based on the xpcom components loaded at startup, generates xpcom component instances on demand using the registry, which specifies the supported interfaces, their corresponding implementation objects, and the nsifactory interface, provides api facilities clients can use to dynamically create xpcom components, and specifies the mechanism clients use to query an xpcom component for one of its interfaces, and to release the interface when it’s no longer needed.
What to do and what not to do in Bugzilla
if you need faster access to get canconfirm or editbugs, especially in order to triage bugs or to participate in a bug day, then you can ask in #bmo on irc, or you may create a bug requesting permissions.
Continuous Integration
hf - static rooting hazard analysis s - static analysis v - valgrind build and test jobs; these jobs create valgrind-compatible builds and run a small set of valgrind tests on them.
Cookies in Mozilla
creating a cookie log steps to create and attach a cookie log in order to aid in triaging a bug in cookies.
Debugging Chrome
i did trace_file=foo.txt and it created the trace file in "c:\users\jrmuizel\appdata\local\google\chrome sxs\application\22.0.1183.0\foo.txt".
Debugging JavaScript
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: portions of this content are © 1998–2007 by individual mozilla.org contributors; content available under a creative commons license | details.
Articles for new developers
to help you find the most critical stuff as quickly as possible, we've created this list of the articles you'll find most useful as you get yourself oriented and make your first contributions to the project.
Makefiles - Best practices and suggestions
prefer library rules whenever possible or create library rules that are missing.
Installing headers using EXPORTS
this is accomplished by setting make variables telling the build system which module the headers are for (since headers are organized by module under <tt>dist/include</tt>), and which headers need to be created from idl files by xpidl.
The Firefox codebase: CSS Guidelines
part of those adjustments include making all box-shadow invisible, so this is something to be aware of if you create a focus ring or a border using the box-shadow property: consider using a border or an outline if you want the border/focus ring to stay visible in high-contrast mode.
Commenting IDL for better documentation
* * to make it easier to document i have included that you can create an instance * of this interface by implementing: @mozilla.org/cookie-monster;1 */ // i can also just use a comment like this here as well and it will not be used.
Obsolete Build Caveats and Tips
you only need to follow the steps below if you want to customize the build (e.g., to create a debug build or a release build with debug symbols), you want to build something other than firefox, or you want to build pre-gecko 5.0 source.
Contributing to the Mozilla code base
with more than a million bugs filed in bugzilla, it can be hard to know where to start, so we've created these bug categories to make getting involved a little easier: codetribute - our site for finding bugs that are mentored, some are good first bugs, some are slightly harder.
Reviewer Checklist
make sure the patch doesn't create any unused code (e.g., remove strings when removing a feature) all caught exceptions should be logged at the appropriate level, bearing in mind personally identifiable information, but also considering the expense of computing and recording log output.
Frame script environment
domwindowcreated fires when a new content object is created.
Limitations of frame scripts
the exceptions are: content-document-global-created document-element-inserted outer-window-destroyed inner-window-destroyed dom-window-destroyed these must be registered in the content process.
Frame script environment
domwindowcreated fires when a new content object is created.
Limitations of frame scripts
the exceptions are: content-document-global-created document-element-inserted outer-window-destroyed inner-window-destroyed dom-window-destroyed these must be registered in the content process.
Performance
better: content-document-global-created notifications can be substituted with domwindowcreated events other observers and services should be registered in a process script or jsm instead load frame scripts on demand bad: // addon.js services.mm.loadframescript("framescript.js", /*delayed:*/ true) // stuff communicating with the framescript // framescript.js function onlyonceinabluemoon() { // we only need this during a ...
Firefox
learn how to create add-ons for firefox, how to develop and build firefox itself, and how the internals of firefox and its subprojects work.
Using the Browser API
MozillaGeckoChromeAPIBrowser APIUsing
demo to demonstrate basic usage of this api, we have created a simple browser api demo that provides buttons allowing you to (re)load web pages, stop loading, move forward and back in history, and zoom in and out of the page.
HTMLIFrameElement.getScreenshot()
examples var browser = document.queryselector('iframe'); var request = browser.getscreenshot(100, 100); request.onsuccess = function() { var blob = request.result; var url = url.createobjecturl(blob); } specification not part of any specification.
ChromeWorker
summary if you're developing privileged code, and would like to create a worker that can use js-ctypes to perform calls to native code, you can do so by using chromeworker instead of the standard worker object.
Chrome-only API reference
MozillaGeckoChromeAPI
it currently works in (privileged) chrome code on firefox desktop (version 47 and above).chromeworkerif you're developing privileged code, and would like to create a worker that can use js-ctypes to perform calls to native code, you can do so by using chromeworker instead of the standard worker object.
-moz-window-dragging
initial value drag applies to all elements that create native windows, e.g.
Roll your own browser: An embedding how-to
i have created a directory under embedding called config.
Gecko SDK
after the xulrunner build is complete running make sdk from your object directory will create a package of the sdk in dist.
How test harnesses work
python runner the python runner: sets up the testing environment sets up environment variables (mozrunner, currently) creates a profile (mozprofile via mozrunner) sets appropriate test preferences inserts a shim extension in the profile (for non-marionette tests) gathers the tests (manifestdestiny) potentially sets up an http server for test data (mozhttpd) invokes the binary (mozrunner) it is the job of the shim extension to shut down the browser logging (mozlog, in theory) ...
IPDL Best Practices
is there any chance that an ipdl function could be called after the protocol itself has been destroyed, or before it has been created?
IPDL Type Serialization
it is never acceptable to serialize/deserialize raw pointer values; if you are tempted, you probably should create a subprotocol for that data, so that ipdl can check the values and lifetime.
Implementing Download Resuming
resuming a download in order to resume a download, you should create a channel as usual (using nsiioservice).
Infallible memory allocation
when instantiating objects, the new operator creates them infallibly by default.
JavaScript libraries from Mozilla projects
in addition to firefox and other applications, mozilla developers have created a number of useful javascript libraries you can use in your projects.
AddonInstall
instances can be created using the getinstallforfile() or getinstallforurl() methods on the addonmanager.
InstallListener
installstarted(in addoninstall install) void oninstallended(in addoninstall install, in addon addon) void oninstallcancelled(in addoninstall install) void oninstallfailed(in addoninstall install) void onexternalinstall(in addon install, in addon existingaddon, in boolean needsrestart) methods onnewinstall() called when a new instance of addoninstall is created, primarily so ui can display some kind of progress for all installs.
Assert.jsm
, message); promise rejects(promise, expected, message); undefined greater(lhs, rhs, message); undefined greaterorequal(lhs, rhs, message); undefined less(lhs, rhs, message); undefined lessorequal(lhs, rhs, message); undefined setreporter(reporterfunc); undefined report(failed, actual, expected, message, operator); constructor creates a new assert object.
AsyncShutdown.jsm
instances of phase note that you cannot create an instance of phase yourself.
Interfacing with the Add-on Repository
"i", callback: function() { if (popupnotifications.install) { popupnotifications.install.install(); } else { popupnotifications.remove(box); } } }, null /* secondary action */ ); } the code here starts by stashing the passed-in addoninstall object for later use, then creates and displays the pop-up notification box with the text and button label passed into the method.
JNI.jsm
see the section "working with arrays" to see how this is used to create typed arrays.
JavaScript OS.Constants
o_creat create the file if it does not exist yet.
Log.jsm
// use dots to create a hierarchy, this way you can later change // the log level of sets of loggers under some common root let log = log.repository.getlogger("myextension.myclass"); log.level = log.level.debug; // a console appender logs to the browser console.
PopupNotifications.jsm
this lets you create a notification that will appear when the user clicks the anchor.
Deferred
method overview void resolve([optional] avalue); void reject([optional] areason); properties attribute type description promise read only promise a newly created promise, initially in the pending state.
PromiseUtils.jsm
to use it, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/promiseutils.jsm"); method overview deferred defer(); methods defer() creates a new pending promise and provides methods to resolve or reject this promise.
Using workers in JavaScript code modules
to create a chromeworker for this purpose, you need to use the nsiworkerfactory interface: var workerfactory = components.classes['@mozilla.org/threads/workerfactory;1'] .createinstance(components.interfaces.nsiworkerfactory); var worker = workerfactory.newchromeworker('script_url.js'); this will create a new chrome worker that will immediately begin to run the script at t...
WebChannel.jsm
the webchannel.jsm javascript code module provides an abstraction that uses the message manager and custom events apis to create a two-way communication channel between chrome and content code for specific origins (using a specific origin passed to the constructor or a lookup with nsipermissionmanager while also ensuring the scheme is https).
Webapps.jsm
nction(aid) installsystemapps: function() loadandupdateapps: function() updatedatastore: function(aid, aorigin, amanifesturl, amanifest) _registersystemmessagesforentrypoint: function(amanifest, aapp, aentrypoint) _registerinterappconnectionsforentrypoint: function(amanifest, aapp,) _registersystemmessages: function(amanifest, aapp) _registerinterappconnections: function(amanifest, aapp) _createactivitiestoregister: function(amanifest, aapp, aentrypoint, arunupdate) _registeractivitiesforapps: function(aappstoregister, arunupdate) _registeractivities: function(amanifest, aapp, arunupdate) _createactivitiestounregister: function(amanifest, aapp, aentrypoint) _unregisteractivitiesforapps: function(aappstounregister) _unregisteractivities: function(amanifest, aapp) _processmanifestfor...
JavaScript code modules
to which can be read, write, rename, create directories,etc.
Localizing extension metadata on addons.mozilla.org
create an account and then, using the “basic open-ended question” template, follow the instructions to upload the text of your amo page.
Uplifting a localization from Central to Aurora
you don't need to work on making the synchronization happen in either of your copies of the aurora or central repositories, but you can create a third one for this work.
Creating localizable web apps
this page was auto-generated because a user created a sub-page to this page.
Mozilla Framework Based on Templates (MFBT)
guardobjects.h provides macros which can be used to annotate an raii-style guard class, so that any attempt to create an unnamed temporary for it will assert.
Fonts for Mozilla's MathML engine
you can use fontforge and fonttools to edit the math table and create your own mathematical fonts.
Fonts for Mozilla 2.0's MathML engine
the fonts may be installed by extracting the font files (which have the .otf extension) from the zip archive, then following instructions for microsoft windows, or copying the files to a ~/library/fonts folder on mac os x, or to a ~/.fonts/ directory (which may need to be created) on unix/linux systems.
Mozilla MathML Project
create mathml documents authoring mathml editors converters stylesheets original document information author(s): roger b.
Mozilla Web Developer FAQ
createelementns() instead of createelement()).
Mozilla projects on GitHub
mozilla-appmaker the appmaker project -- a web tool to let non-programmers create apps.
Mozilla Style System
when script dynamically changes the data represented by a css style rule, we create a new nsistylerule object; keeping the old one around briefly helps to determine what changed and how we need to handle that change.
Memory reporting
for example: void foobar::addsizeofexcludingthis(nsmallocsizeoffun amallocsizeof, size_t *afoosizeout, size_t* abarsizeout) const { *afoosizeout += ...; *abarsizeout += ...; } alternatively, you could create a struct: struct foobarsizes { size_t mfoo; size_t mbar; foobarsizes() { mozilla::podzero(this); } } void foobar::addsizeofexcludingthis(nsmallocsizeoffun amallocsizeof, foobarsizes* asizes) const { asizes->mfoo += ...; asizes->mbar += ...; } note the add prefix that makes this incrementing behaviour clear.
Profiling with the Gecko Profiler and Local Symbols on Windows
generate the breakpad symbol files by running ./mach buildsymbols: https://developer.mozilla.org/en/building_firefox_with_debug_symbols#breakpad_symbol_files this will have created symbols under $objdir/dist/ , named after the binary name, architecture and version, so something like "firefox-40.0a1.en-us-win32.crashreporter-symbols.zip" point talos to this zipfile by passing its path to the --symbolspath flag.
TimerFirings logging
e_shot 0 ms): [content] chrome://browser/content/tabbrowser.xml:1816:0 711637568[7f3219c48000]: [6835] fn timer (one_shot 100 ms): [content] http://edition.cnn.com/:5:7231 711637568[7f3219c48000]: [6835] fn timer (one_shot 100 ms): [content] http://a.visualrevenue.com/vrs.js:6:9423 these js timers are annotated with [content] and show the javascript source location where they were created.
browser.dom.window.dump.file
it will be created if it doesn't exist yet.
Preference reference
if set to true, the data is stored as content preference.browser.pagethumbnails.capturing_disabledthe preference browser.pagethumbnails.capturing_disabled controls whether the application creates screenshots of visited pages which will be shown if the web page is shown in the grid of the "new tab page" (about:newtab) which offers the most often visited pages for fast navigation.browser.search.context.loadinbackgroundbrowser.search.context.loadinbackground controls whether a search from the context menu with "search <search engine> for <selected text>" opening a new tab will give focus to...
Preferences system
using this system it is possible to create preferences windows that display and operate appropriately on various platforms (windows, macos x and gnome).
JSHydra
in its back-end, it uses the parse tree created by the spidermonkey engine.
L20n HTML Bindings
<head> … <script src="l20n.js"></script> </head> create manifest use a localization manifest to define available languages and their resource files.
L20n Javascript API
if it is undefined, or if registerlocales hasn't been called at all, the context instance will create a special locale called i-default to be used as the default.
Leak And Bloat Tests
08/04/2008: prefs.js created via tb with the above settings, the first section is for preferences included in tinderbox, the second section is ones which don't currently get set.
MailNews automated testing
message synthesis: create messages by specifying what properties the messages should have.
Midas editor module security preferences
if there's no user.js file, create one.
Creating a Cookie Log
finally, attach the cookie-log.txt file to the bug where it was requested (by clicking on create new attachment).
NSPR build instructions
build the libraries build the test programs for example, # check out the source tree from mercurial hg clone https://hg.mozilla.org/projects/nspr # create a build directory mkdir target.debug cd target.debug # run the configure script ../nspr/configure [optional configure options] # build the libraries gmake # build the test programs cd pr/tests gmake on mac os x, use make, which is gnu make.
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 ...
Condition Variables
the association between a condition and a monitor is established when a condition variable is created, and the association persists for its life.
Date and Time
two often-used callback functions of this type are provided by nspr: prtimeparamfn pr_localtimeparameters and pr_gmtparameters functions the functions that create and manipulate time and date values are: pr_now pr_explodetime pr_implodetime pr_normalizetime ...
Linked Lists
linked list macros macros that create and operate on linked lists are: pr_init_clist pr_init_static_clist pr_append_link pr_insert_link pr_next_link pr_prev_link pr_remove_link pr_remove_and_init_link pr_insert_before pr_insert_after pr_clist_is_empty pr_list_head pr_list_tail ...
Locks
lock type prlock lock functions pr_newlock creates a new lock object.
NSPR Error Handling
pr_file_exists_error attempt to create or rename a file when the new name is already being used.
NSPR LOG MODULES
if not specified, the existing contents of nspr_log_file will be lost as a new file is created with the same filename.
NSPR Types
here are some simple examples of the use of these types: in dowhim.h: pr_extern( void ) dowhatimean( void ); static void pr_callback rootfunction(void *arg); in dowhim.c: pr_implement( void ) dowhatimean( void ) { return; }; prthread *thread = pr_createthread(..., rootfunction, ...); algebraic types nspr provides the following type definitions with unambiguous bit widths for algebraic operations: 8-, 16-, and 32-bit integer types 64-bit integer types floating-point number type for convenience, nspr also provides type definitions with platform-dependent bit widths: native os integer types 8-, 16-, and 32-bit integer types signed ...
PLHashTable
a new hash table is created by the pl_newhashtable function, and destroyed by the pl_hashtabledestroy function.
PL_HashTableAdd
pl_hashtableadd returns null if there is not enough memory to create a new entry.
PL_HashTableDestroy
the entries are freed by the freeentry function (with the ht_free_entry flag) in the allocops structure supplied when the table was created.
PRLogModuleInfo
to log your program's activity, create a prlogmoduleinfo structure using pr_newlogmodule .
PRMonitor
clients create them when needed and must destroy them when no longer needed.
PRThread
the identifier remains valid until it returns from its root function and, if the thread was created joinable, is joined.
PRThreadScope
the scope of an nspr thread, specified as a parameter to pr_createthread or returned by pr_getthreadscope.
PR_Accept
pr_accept accepts the first connection from the queue of pending connections and creates a new socket for the newly accepted connection.
PR_AcceptRead
description pr_acceptread accepts a new connection and retrieves the newly created socket's descriptor and the connecting peer's address.
PR_Bind
description when a new socket is created, it has no address bound to it.
PR_CloseFileMap
description when a file mapping created with a call to pr_createfilemap is no longer needed, it should be closed with a call to pr_closefilemap.
PR_DeleteSemaphore
syntax #include <pripcsem.h> nspr_api(prstatus) pr_deletesemaphore(const char *name); parameter the function has the following parameter: name the name of a semaphore that was previously created via a call to pr_opensemaphore.
PR_DestroyPollableEvent
syntax nspr_api(prstatus) pr_destroypollableevent(prfiledesc *event); parameter the function has the following parameter: event pointer to a prfiledesc structure previously created via a call to pr_newpollableevent.
PR_GetDefaultIOMethods
you can pass your own layer's methods table to pr_createiolayerstub to create your new layer.
PR_GetNameForIdentity
description a string may be associated with a layer when the layer is created.
PR_GetOSError
for portability, clients should not create dependencies on the values of os-specific error codes.
PR ImportTCPSocket
returns the function returns one of the following values: upon successful completion, a pointer to the prfiledesc object created for the newly imported native tcp socket.
PR_JoinThreadPool
syntax #include <prtpool.h> nspr_api(prstatus) pr_jointhreadpool( prthreadpool *tpool ); parameter the function has the following parameter: tpool a pointer to a prthreadpool structure previously created by a call to pr_createthreadpool.
PR_Listen
it creates a queue for pending connections and starts to listen for connection requests on the socket.
PR_NewCondVar
creates a new condition variable.
PR_NewLogModule
creates a new log module.
PR_NewPollableEvent
create a pollable event file descriptor.
PR_OpenAnonFileMap
creates or opens a named semaphore with the specified name syntax #include <prshma.h> nspr_api( prfilemap *) pr_openanonfilemap( const char *dirname, prsize size, prfilemapprotect prot ); parameters the function has the following parameters: dirname a pointer to a directory name that will contain the anonymous file.
PR_QueueJob
syntax #include <prtpool.h> nspr_api(prjob *) pr_queuejob( prthreadpool *tpool, prjobfn fn, void *arg, prbool joinable ); parameters the function has the following parameters: tpool a pointer to a prthreadpool structure previously created by a call to pr_createthreadpool.
PR_QueueJob_Accept
syntax #include <prtpool.h> nspr_api(prjob *) pr_queuejob_accept( prthreadpool *tpool, prjobiodesc *iod, prjobfn fn, void *arg, prbool joinable ); parameters the function has the following parameters: tpool a pointer to a prthreadpool structure previously created by a call to pr_createthreadpool.
PR_QueueJob_Connect
syntax #include <prtpool.h> nspr_api(prjob *) pr_queuejob_connect( prthreadpool *tpool, prjobiodesc *iod, const prnetaddr *addr, prjobfn fn, void * arg, prbool joinable ); parameters the function has the following parameters: tpool a pointer to a prthreadpool structure previously created by a call to pr_createthreadpool.
PR_QueueJob_Read
syntax #include <prtpool.h> nspr_api(prjob *) pr_queuejob_read( prthreadpool *tpool, prjobiodesc *iod, prjobfn fn, void *arg, prbool joinable ); parameters the function has the following parameters: tpool a pointer to a prthreadpool structure previously created by a call to pr_createthreadpool.
PR_QueueJob_Timer
syntax #include <prtpool.h> nspr_api(prjob *) pr_queuejob_timer( prthreadpool *tpool, printervaltime timeout, prjobfn fn, void * arg, prbool joinable ); parameters the function has the following parameters: tpool a pointer to a prthreadpool structure previously created by a call to pr_createthreadpool.
PR_QueueJob_Write
syntax #include <prtpool.h> nspr_api(prjob *) pr_queuejob_write( prthreadpool *tpool, prjobiodesc *iod, prjobfn fn, void *arg, prbool joinable ); parameters the function has the following parameters: tpool a pointer to a prthreadpool structure previously created by a call to pr_createthreadpool.
PR_SetLogFile
description creates a log file with the specified file name.
PR_SetPollableEvent
syntax nspr_api(prstatus) pr_setpollableevent(prfiledesc *event); parameter the function has the following parameter: event pointer to a prfiledesc structure previously created via a call to pr_newpollableevent.
PR_ShutdownThreadPool
syntax #include <prtpool.h> nspr_api(prstatus) pr_shutdownthreadpool( prthreadpool *tpool ); parameter the function has the following parameter: tpool a pointer to a prthreadpool structure previously created by a call to pr_createthreadpool.
PR_WaitForPollableEvent
syntax nspr_api(prstatus) pr_waitforpollableevent(prfiledesc *event); parameter the function has the following parameter: event pointer to a prfiledesc structure previously created via a call to pr_newpollableevent.
NSS CERTVerify Log
to create a log: #include "secport.h" #include "certt.h" certverifylog *log; arena = port_newarena(512); log = port_arenaznew(arena,log); log->arena = arena; you can then pass this log into your favorite cert verify function.
CERT_FindCertByIssuerAndSN
t.h> certcertificate *cert_findcertbyissuerandsn ( certcertdbhandle *handle, certissuerandsn *issuerandsn ); parameters handle in pointer to a certcertdbhandle representing the certificate database to look in issuerandsn in pointer to a certissuerandsn that must be properly formed to contain the issuer name and the serial number (see [example]) description this function creates a certificate key using the issuerandsn and it then uses the key to find the matching certificate in the database.
Getting Started With NSS
a new set of samples is currently under development and review, see create new nss samples.
NSS_3.12.2_release_notes.html
bug 444974: crash upon reinsertion of e-identity smartcard bug 447563: modutil -add prints no error explanation on failure bug 448431: pk11_createmergelog() declaration causes gcc warning when compiling with -wstrict-prototypes bug 449334: pk12util has duplicate options letters bug 449725: signver is still using static libraries.
NSS 3.19.2.3 release notes
an attacker could create a specially-crafted certificate which, when parsed by nss, would cause a crash or execution of arbitrary code with the permissions of the user.
NSS 3.19.2 release notes
however, this change in behaviour unintentionally broke existing nss applications that need to generate or use such keys, via apis such as seckey_creatersaprivatekey or seckey_createdhprivatekey.
NSS 3.20 release notes
each time this api is called for the first time in a process, a fresh set of weak dhe parameters will be randomly created, which may take a long amount of time.
NSS 3.21.1 release notes
an attacker could create a specially-crafted certificate which, when parsed by nss, would cause a crash or execution of arbitrary code with the permissions of the user.
NSS 3.22.2 release notes
an attacker could create a specially-crafted certificate which, when parsed by nss, would cause a crash or execution of arbitrary code with the permissions of the user.
NSS 3.22 release notes
pk11_createpbev2algorithmid() now supports sec_oid_pkcs5_pbkdf2 with cipheralgtag and prfalgtag set to sec_oid_hmac_sha256, sec_oid_hmac_sha224, sec_oid_hmac_sha384, or sec_oid_hmac_sha512.
NSS 3.23 release notes
an attacker could create a specially-crafted certificate which, when parsed by nss, would cause a crash or execution of arbitrary code with the permissions of the user.
NSS 3.34 release notes
certificates with rsa-pss or rsa-pkcs#1v1.5 keys can be used to create an rsa-pss signature on a certificate, using the --pss-sign argument to certutil.
NSS 3.45 release notes
bug 1551129 - support static linking on windows bug 1552262 - expose a function pk11_findrawcertswithsubject for finding certificates with a given subject on a given slot bug 1546229 - add ipsec ike support to softoken bug 1554616 - add support for the elbrus lcc compiler (<=1.23) bug 1543874 - expose an external clock for ssl this adds new experimental functions: ssl_settimefunc, ssl_createantireplaycontext, ssl_setantireplaycontext, and ssl_releaseantireplaycontext.
NSS 3.47 release notes
e-2019-11756) bug 1494063 - support tls exporter in tstclnt and selfserv bug 1581024 - heap overflow in nss utility "derdump" bug 1582343 - soft token mac verification not constant time bug 1578238 - handle invald tag sizes for ckm_aes_gcm bug 1576295 - check all bounds when encrypting with seed_cbc bug 1580286 - nss rejects tls 1.2 records with large padding with sha384 hmac bug 1577448 - create additional nested s/mime test messages for thunderbird bug 1399095 - allow nss-try to be used to test nspr changes bug 1267894 - libssl should allow selecting the order of cipher suites in clienthello bug 1581507 - fix unportable grep expression in test scripts bug 1234830 - [cid 1242894][cid 1242852] unused values bug 1580126 - fix build failure on aarch64_be while building freebl/gcm bug ...
NSS 3.48 release notes
because using an iteration count higher than 1 with the legacy dbm (key3.db) storage creates files that are incompatible with previous versions of nss, applications that wish to enable it for key3.db are required to set environment variable nss_allow_legacy_dbm_iteration_count=1.
NSS Sample Code sample6
* to decrypt, you need the ciphertext and the id of the key that was used * to encrypt * * before running this example, create the nss database * certutil -n -d .
PKCS #11 Module Specs
a new ck_c_initialize_args structure is defined as typedef struct ck_c_initialize_args { ck_createmutex createmutex; ck_destroymutex destroymutex; ck_lockmutex lockmutex; ck_unlockmutex unlockmutex; ck_flags flags; ck_void_ptr libraryparameters; ck_void_ptr preserved; } ck_c_initialize_args; applications/libraries must set libraryparameters to null if no parameter value is specified.
PKCS 12 functions
function name/documentation source code nss versions sec_pkcs12addcertandkey mxr 3.2 and later sec_pkcs12addpasswordintegrity mxr 3.2 and later sec_pkcs12createexportcontext mxr 3.2 and later sec_pkcs12createpasswordprivsafe mxr 3.2 and later sec_pkcs12createunencryptedsafe mxr 3.2 and later sec_pkcs12decoderfinish mxr 3.2 and later sec_pkcs12decodergetcerts mxr 3.4 and later sec_pkcs12decoderimportbags mxr ...
PKCS 7 functions
3.2 and later sec_pkcs7containscertsorcrls mxr 3.4 and later sec_pkcs7contentisencrypted mxr 3.4 and later sec_pkcs7contentissigned mxr 3.4 and later sec_pkcs7contenttype mxr 3.2 and later sec_pkcs7copycontentinfo mxr 3.4 and later sec_pkcs7createcertsonly mxr 3.3 and later sec_pkcs7createdata mxr 3.2 and later sec_pkcs7createencrypteddata mxr 3.2 and later sec_pkcs7createenvelopeddata mxr 3.2 and later sec_pkcs7createsigneddata mxr 3.2 and later sec_pkcs7decodeitem mxr 3.2 and later ...
FC_DeriveKey
description fc_derivekey derives (decrypts) a key and creates a new key object.
FC_GetObjectSize
name fc_getobjectsize - create a copy of an object.
FC_UnwrapKey
description fc_unwrapkey unwraps (decrypts) a key and creates a new key opbject.
FIPS mode of operation
fc_createobject fc_copyobject fc_destroyobject fc_getobjectsize fc_getattributevalue fc_setattributevalue fc_findobjectsinit fc_findobjects fc_findobjectsfinal encryption functions these functions support triple des and aes in ecb and cbc modes.
NSS tools : pk12util
ror read from import file o 16 - pkcs12 decode error o 17 - pkcs12 decoder verify error o 18 - pkcs12 decoder validate bags error o 19 - pkcs12 decoder import bags error o 20 - key db conversion version 3 to version 2 error o 21 - cert db conversion version 7 to version 5 error o 22 - cert and key dbs patch error o 23 - get default cert db error o 24 - find cert by nickname error o 25 - create export context error o 26 - pkcs12 add password itegrity error o 27 - cert and key safes creation error o 28 - pkcs12 add cert and key error o 29 - pkcs12 encode error examples importing keys and certificates the most basic usage of pk12util for importing a certificate or key is the pkcs#12 input file (-i) and some way to specify the security database being accessed (either -d for a dire...
NSS tools : vfychain
this tool can also create certificate, key, and module security database files.
NSS Tools dbck-tasks
nss security tools: dbck tasks newsgroup: mozilla.dev.tech.crypto task list in analyze mode, there should be an option to create a file containing a graph of the certificate database without any information about the user's certificates (no common names, email addresses, etc.).
NSS Tools pk12util
12 decoder start error 15 - error read from import file 16 - pkcs12 decode error 17 - pkcs12 decoder verify error 18 - pkcs12 decoder validate bags error 19 - pkcs12 decoder import bags error 20 - key db conversion version 3 to version 2 error 21 - cert db conversion version 7 to version 5 error 22 - cert and key dbs patch error 23 - get default cert db error 24 - find cert by nickname error 25 - create export context error 26 - pkcs12 add password itegrity error 27 - cert and key safes creation error 28 - pkcs12 add cert and key error 29 - pkcs12 encode error ...
NSS tools : pk12util
de error o 17 - pkcs12 decoder verify error o 18 - pkcs12 decoder validate bags error o 19 - pkcs12 decoder import bags error o 20 - key db conversion version 3 to version 2 error o 21 - cert db conversion version 7 to version 5 error o 22 - cert and key dbs patch error o 23 - get default cert db error o 24 - find cert by nickname error o 25 - create export context error o 26 - pkcs12 add password itegrity error o 27 - cert and key safes creation error o 28 - pkcs12 add cert and key error o 29 - pkcs12 encode error examples importing keys and certificates the most basic usage of pk12util for importing a certificate or key is the pkcs#12 input file (-i) and some way to specify the security database being ...
NSS tools : vfychain
this tool can also create certificate, key, and module security database files.
Necko Interfaces Overview
http) maps uri string to nsiuri instance via newuri method creates nsichannel instance from nsiuri instance via newchannel method nsistreamlistener : nsirequestobserver implemented by the consumer of a nsichannel instance passed to nsichannel::asyncopen method nsirequestobserver::onstartrequest - notifies start of async download nsistreamlistener::ondataavailable - notifies presence of downloaded data nsirequestobserver::onstoprequest - notifies complet...
Multithreading in Necko
for example, on xp_win an invisible window is created with a message pump on a background thread for processing wsa asynchronous dns events.
Renaming With Pork
convince gcc to create annotated .ii files while compiling the analysis copy.
Rhino Examples
multithreaded script execution dynamicscopes.java is a program that creates a single global scope object and then shares it across multiple threads.
Rhino overview
first, every context that is created must be supplied an instance of an object that implements the securitysupport interface.
The JavaScript Runtime
when scripts are compiled in interpretive mode, an internal representation of the compiled form is created and stored rather than generating a java class.
Creating JavaScript tests
jstests automatically load js/src/tests/shell.js before they run, which creates a ton of functions.
How to embed the JavaScript engine
and say: ok = js_definefunctions(cx, global, my_functions); how to call javascript functions from c first, create arguments for the call, here i create arguments with 2 items: // [spidermonkey 24] js::autovaluearray is not defined.
Exact Stack Rooting
there is also a static constructor method frommarkedlocation() that creates a handle from an arbitrary location.
Self-hosted builtins in SpiderMonkey
if it doesn't fit into any of those, create a new .js file in that directory and add it to the selfhosted.inputs list in moz.build.
Introduction to the JavaScript shell
you can use this to create interactive shell programs in javascript.
JIT Optimization Outcomes
the interpreted callee function requires an arguments object to be created.
JS::Construct
on success, *rval receives the newly created object from the constructor call.
JS::DoubleNaNValue
this article covers features introduced in spidermonkey 24 create a not-a-number (nan) floating-point number as a value of type js::value.
JS::MutableHandle
a js::mutablehandle<t> can be created from a js::rooted&lt;t&gt; by using |js::rooted<t>::operator&()|.
JSClass.flags
then scripts may cause nonstandard behavior by replacing standard constructors or prototypes (such as function.prototype.) objects that can end up with the wrong prototype object, if this flag is not present, include: arguments objects (ecma 262-3 §10.1.8 specifies "the original object prototype"), function objects (ecma 262-3 §13.2 specifies "the original function prototype"), and objects created by many standard constructors (ecma 262-3 §15.4.2.1 and others).
JSFunctionSpec
an application typically has an array of jsfunctionspec to define all the functions for an object and calls js_definefunctions or js_initclass to create the functions and assign them to an object.
JSIteratorOp
description the javascript engine calls the jsextendedclass.iteratorobject callback to create an iterator object for a given object.
JSNative
in particular, apis such as js_initclass and js_definefunctions create custom methods on javascript objects that are implemented as jsnative callbacks provided by the application, written in c/c++ code.
JSPropertyDescriptor
examples the following example demonstrates how to use the object.defineproperty() function to create a property under an object in a javascript via a descriptor.
JSPropertyOp
getters and setters when a jsapi application creates a property on an object (for example, using js_defineproperty or js_defineproperties) it can specify getter and setter callbacks for the new property.
JSPropertySpec
pass to js_defineproperties or js_initclass to create the properties and assign them to an object.
JSScript
for now, i'll just say that this class represents a section of compiled javascript code, and the functions to create, run, and analyize it.
JS_CompileUTF8FileHandle
if principals is non-null, it points to a jsprincipals object that is associated with the new script and any functions it creates.
JS_ConcatStrings
syntax jsstring * js_concatstrings(jscontext *cx, js::handlestring left, js::handlestring right); name type description cx jscontext * the context in which both the strings have been created.
JS_DecompileFunction
if you decompile a function that does not make a native c call, then the text created by js_decompilefunction is a complete function declaration suitable for re-parsing.
JS_DefineOwnProperty
descriptor is supposed to be a property descriptor, this means you need to create an object with properties such as value, writable, get or set.
JS_DumpNamedRoots
description each call to js_addnamedroot creates a record in a table of named roots maintained by the garbage collector.
JS_ForgetLocalRoot
(here the term gc-thing refers to any value that is subject to garbage collection: a jsobject, jsstring, jsfunction, or jsdouble.) js_forgetlocalroot works on any gc-thing allocated in the current local root scope, but it's more time-efficient when called on references to more recently created gc-things.
JS_GC
when your scripts create many objects, you may want to call js_gc directly in your code, particularly when a script terminates or when the application has idle time.
JS_GetFunctionFlags
once a function is created, its flags cannot be modified.
JS_GetFunctionName
the return value is either the name of a function, or the string "anonymous", which indicates that the function was not assigned a name when created.
JS_GetGlobalForObject3
this page was auto-generated because a user created a sub-page to this page.
JS_GetGlobalObject
if a function is executing, the global object used by that function is determined when the function is created.
JS_GetInstancePrivate
obsolete since jsapi 32 this must be one of the following: an argv pointer created by the javascript engine and passed to a jsnative callback; js_argv(cx, vp) where vp is a pointer created by the engine and passed to a jsfastnative callback; or null.
JS_GetRuntime
each context is associated with a particular jsruntime when it is created (see js_newcontext); js_getruntime provides a convenient, programmatic way to look up the association.
JS_GetStringCharAt
syntax bool js_getstringcharat(jscontext *cx, jsstring *str, size_t index, char16_t *res); char16_t js_getflatstringcharat(jsflatstring *str, size_t index); name type description cx jscontext * the context in which to create the new string.
JS_GetStringEncodingLength
you can use this value to create a buffer to encode the string into using the js_encodestringtobuffer function.
JS_GetVersion
when a context is created, its version is initially jsversion_default.
JS_Init
in the past js_init once had the signature jsruntime * js_init(uint32_t maxbytes) and was used to create new jsruntime instances.
JS_InitStandardClasses
these global objects, functions, constructors, and constants are created as properties of obj.
JS_IsExternalString
this article covers features introduced in spidermonkey 17 determines whether or not the specified jsstring is an external string (that is, a string created by calling js_newexternalstring rather than js_newexternalstringwithclosure).
JS_LeaveLocalRootScope
leaving a nested local root scope causes all objects created since the matching js_enterlocalrootscope call to become subject to garbage collection.
JS_NewDateObjectMsec
this article covers features introduced in spidermonkey 1.8.5 creates a new date object instance, configured to represent the date and time indicated by the specified time in milliseconds since the unix epoch.
JS_NewRuntime
(the engine may use helper threads internally, though.) on success, js_newruntime returns a pointer to the newly created runtime, which the caller must later destroy using js_destroyruntime.
JS_NumberValue
otherwise, a new floating-point js::value is created.
JS_ObjectIsFunction
description js_objectisfunction tests whether obj is a function object (faster than comparing obj's class name to function, but equivalent unless someone has overwritten the function identifier with a different constructor and then created instances using that constructor that might be passed in as obj).
JS_ParseJSON
index jsint (in js_parsejsonwithreviver only) a reviver function to apply to the created value after parsing; see json.parse.
JS_SaveExceptionState
the jsexceptionstate created by this function automatically roots any pending exception object which needs to be protected from the gc.
JS_SetArrayLength
you can call js_setarraylength either to set the number of elements for an array object you created without specifying an initial number of elements, or to change the number of elements allocated for an array.
JS_SetCheckObjectAccessCallback
this callback is also used to check access to the caller property of function objects (as, for example, when the javascript engine creates a stack trace) and to check access from scripts to properties with scripted getters or setters.
JS_SetParent
but an application may instead use js_setparent after the object is created.
JS_ShutDown
this method should be called after all other jsapi data has been properly cleaned up: every jsruntime created with js_newruntime must have been destroyed with js_destroyruntime, every jscontext created with js_newcontext must have been destroyed with js_destroycontext, and so on.
JS_SuspendRequest
since then, a jsruntime is tied to the thread that created it; it may not be accessed by any other thread.
JS_THREADSAFE
sharing contexts among threads ordinarily, a jscontext is created, used, and destroyed by a single thread.
JS_ThrowStopIteration
in for…in and for each…in loops, the javascript engine can create an iterator object and call its .next method repeatedly, as described in new in javascript 1.7: iterators.
JS_YieldRequest
jsapi 1.7 and earlier js_yieldrequest did not cause cx to relinquish objects it created to other threads that are blocked waiting for them.
Property attributes
assigning to obj.x, where obj inherits a non-shared property from its prototype, creates a new own data property on obj; the prototype's .x is not shared with its children.
SpiderMonkey 1.8.5
global objects global objects have been specialized, and must be be created with either js_newglobalobject or js_newcompartmentandglobalobject.
SpiderMonkey 1.8.7
global objects global objects have been specialized, and must be be created with either js_newglobalobject or js_newcompartmentandglobalobject.
SpiderMonkey 31
js_init is a new function which must be used to initialize the js engine before any jsruntimes are created or other jsapi methods are called.
SpiderMonkey 38
js::clonefunctionobject (bug 1088228) interned_string_to_jsid (bug 1045900) js::construct (bug 1017109) js::createerror (bug 984048) js::falsehandlevalue (bug 959787) js::handlesymbol (bug 645416) js::identifystandardconstructor (bug 976148) js::iscallable (bug 1065811) js::isconstructor (bug 1065811) js::mutablehandlesymbol (bug 645416) js::ordinarytoprimitive (bug 1103152) js::propertyspecnameequalsid (bug 1082672) js::propertyspecnameissymbol (bug 1082672) js::propertyspecnametopermanentid (bug 1...
SpiderMonkey releases
we have periodically created "releases", but they are best-effort and incomplete.
Setting up CDT to work on SpiderMonkey
start eclipse and create a workspace somewhere.
Zest tools
the following tools currently support zest: owasp zed attack proxy the zap add-on allows the user to create, edit and run zest scripts.
Mozilla Projects
many of these are components of firefox or are tools used to create firefox, but may be used by other projects as well.
The Rust programming language
rust is a new open-source systems programming language created by mozilla and a community of volunteers, designed to help developers create fast, secure applications which take full advantage of the powerful features of modern multi-core processors.
Gecko
this page was auto-generated because a user created a sub-page to this page.
AT APIs Support
gecko based applications gecko can be used in two ways to create application: embedded clients embedded clients use gecko only in the content window, at the moment for html and generic xml only.
Feed content access API
ar data = httprequest.responsetext; var ioservice = components.classes['@mozilla.org/network/io-service;1'] .getservice(components.interfaces.nsiioservice); var uri = ioservice.newuri(feedurl, null, null); if (data.length) { var parser = components.classes["@mozilla.org/feed-processor;1"] .createinstance(components.interfaces.nsifeedprocessor); var listener = new feedtestresultlistener(); try { parser.listener = listener; parser.parsefromstring(data, uri); } catch(e) { alert("error parsing feed."); } } } httprequest = new xmlhttprequest(); httprequest.open("get", feedurl, true); try { httpr...
Using the Places annotation service
lifetime of annotations annotation expiration can be explicitly stated when the annotation is created.
Using the Places keywords API
keywords in firefox are currently created through the add keyword for this search contextual menu option in form text fields.
Places
using the places livemark service how to create and manage livemarks.
Preferences API
you can also create a xul-based options window easily to allow user modify some preferences.
Aggregating the In-Memory Datasource
private: nscomptr<nsisupports> minner; }; construct the datasource delegate when your object is constructed (or, at worst, when somebody qi's for it): rv = nscomponentmanager::createinstance( krdfinmemorydatasourcecid, this, /* the "outer" */ nscomtypeinfo<nsisupports>::getiid(), getter_addrefs(minner)); note passing this as the "outer" parameter.
Creating a Python XPCOM component
for example: xpidl.exe -m typelib -w -v -i c:\source\mozilla\obj-i686-pc-mingw32\dist\idl foo.idl xpidl will then create nsipysimple.xpt, which should be placed correctly (e.g., in the 'components' directory).
Generating GUIDs
guids are used in mozilla programming for identifying several types of entities, including xpcom interfaces (this type of guids is callled iid), components (cid), and legacy add-ons—like extensions and themes—that were created prior to firefox 1.5.
XPCOM glue
MozillaTechXPCOMGlue
please see xpcom glue without mozalloc to learn how to create xpcom components that aren't dependant on mozalloc, and thus are compatible with versions of xulrunner prior to 2.0.
Packaging WebLock
using xpinstall, you can create web-based installations for gecko-based applications, mozilla extensions, or individual components.
Making cross-thread calls using runnables
etask(picallback callback, int digits) : mcallback(callback) , mdigits(digits) { } ns_imethod run() { nscstring result; calculatepi(mdigits, result); nscomptr<nsirunnable> resultrunnable = new piresulttask(mcallback, result); ns_dispatchtomainthread(resultrunnable); } private: picallback mcallback; int mdigits; }; putting it all together to start a new thread, create it using the thread manager: #include "nsxpcomcidinternal.h" void calculatepiasynchronously(int digits, picallback callback) { // to create a new thread, get the thread manager nscomptr<nsithreadmanager> tm = do_getservice(ns_threadmanager_contractid); nscomptr<nsithread> mythread; nsresult rv = tm->newthread(0, 0, getter_addrefs(mythread)); if (ns_failed(rv)) { // in case of failu...
Receiving startup notifications
ly call its nsicategorymanager.addcategoryentry() method: categorymanager->addcategoryentry(appstartup_category, "mycomponentname", "contract-id", pr_true, pr_true, getter_copies(previous)); this causes your component to be instantiated using nsicomponentmanager.createinstance().
Components.Exception
summary components.exception is a javascript constructor to create nsixpcexception objects.
Components.interfaces
this includes nsisupports.queryinterface(), the optional parameter accepted by nsijscid.getservice(), nsijscid.createinstance() when called from javascript, and nsiclassinfo.getinterfaces().
Components.isSuccessCode
if (!components.issuccesscode(statuscode)) copyfailed = true; }, queryinterface: function(aiid) { if (aiid.equals(ci.nsirequestobserver) || aiid.equals(ci.nsisupports)) return this; throw cr.ns_error_no_interface; } }; var copier = cc["@mozilla.org/network/async-stream-copier;1"] .createinstance(ci.nsiasyncstreamcopier); copier.init(instream, outstream, null, true, false, 8192, true, true); copier.asynccopy(copyobserver, null); } ...
Components.utils.getGlobalForObject
this is the global object in place at the time the object was created, which is to say the global object used when executing the script that created the object.
Components.utils.importGlobalProperties
var domfile = services.appshell.hiddendomwindow.file('/path/to/file'); xpcom components some objects have an xpcom alternative, which typically allows more flexibility then the dom version here is an example of how to use the dom xmlhttprequest through xpcom interface of nsixmlhttprequest: var oreq = cc["@mozilla.org/xmlextras/xmlhttprequest;1"].createinstance(ci.nsixmlhttprequest); ...
Components.utils.makeObjectPropsNormal
example for an example, see components.utils.createobjectin().
PyXPCOM
creating a python xpcom component an example of how to create a simple xpcom component with python.
Using components
uctor] queryinterface=function queryinterface() { [native code] } interfacesbyid=[object nsxpccomponents_interfacesbyid] classesbyid=[object nsxpccomponents_classesbyid] stack=js frame :: scratchpad/4 :: cdump :: line 8 manager=[xpconnect wrapped nsicomponentmanager] id=[object nsxpccomponents_id] exception=[object nsxpccomponents_exception] reporterror=function reporterror() { [native code] } cancreatewrapper=function cancreatewrapper() { [native code] } cancallmethod=function cancallmethod() { [native code] } cangetproperty=function cangetproperty() { [native code] } cansetproperty=function cansetproperty() { [native code] } ...
Profiling XPCShell
a profile will look like this: file:///users/michiel/mozilla/tree1/...js/calutils.js [2,25420] createdatetime() {60-62} 579 {min 0, max 3, avg 0, sum 427, self 427} [2,56810] cp_qi() {860-866} 835 {min 0, max 1, avg 0, sum 950, self 950} the first line tells which file was profiled.
XPCShell Reference
for example, if you created anobject with a property named value and then called clear(anobject), the property value would no longer exist.
nsLocalFile
createinstance(components.interfaces.nsilocalfile); file.initwithpath(path); return file.filesize; } see also components, nsicomponentmanager ...
nsScriptableInputStream
example code const nsiscriptableinputstream = components.interfaces.nsiscriptableinputstream; function consumestream(inputstream) { var factory = components.classes["@mozilla.org/scriptableinputstream;1"]; var sis = factory.createinstance(nsiscriptableinputstream); sis.init(inputstream); try { while (true) { var chunk = sis.read(512); if (chunk.length == 0) break; // ok, chunk now contains a portion of the stream's data.
NS_InitXPCOM2
the one exception is that you may call ns_newlocalfile or ns_newnativelocalfile to create a nsifile needed for the abindirectory parameter to ns_initxpcom2.
NS_InitXPCOM3
the one exception is that you may call ns_newlocalfile or ns_newnativelocalfile to create a nsifile needed for the abindirectory parameter to ns_initxpcom3.
Core XPCOM functions
ns_newlocalfilethe ns_newlocalfile function creates an instance of nsilocalfile that provides a platform independent representation of a file path.ns_newnativelocalfilethe ns_newnativelocalfile function creates an instance of nsilocalfile that provides a platform independent representation of a file path.ns_reallocreallocates a block of memory using the xpcom memory manager.ns_shutdownxpcomthe ns_shutdownxpcom function terminates use of xpcom in ...
nsAutoRef
nsautoref has a role similar to nsautoptr and nsrefptr but does not require that the handle is a pointer to an object that was created with new or has addref() and release() methods.
Clone
« xpcom api reference summary the clone function creates a copy of an existing memory block up to the size specified.
nsMemory
clone the clone function creates a copy of an existing memory block up to the size specified.
IAccessible2
one means of implementing this would be to create a factory with a 32 bit number generator and a reuse pool.
IAccessibleTable
lists, trees, and tables can have a large number of children and thus it's possible that the child objects for those controls would only be created as needed.
IAccessibleTable2
lists, trees, and tables can have a large number of children and thus it's possible that the child objects for those controls would only be created as needed.
imgIDecoderObserver
onstartframe() this is a decode notification which is called when each frame is created.
imgILoader
cachekey arequest a newly created, unused imgirequest object or null for one to be created for you.
imgIRequest
getstaticrequest() if this request is for an animated image, the method creates a new request which contains the current frame of the image.
jsdIStackFrame
isdebugger boolean true if stack frame represents a frame created as a result of a debugger evaluation.
mozIAsyncFavicons
1.0 66 introduced gecko 6.0 inherits from: nsisupports last changed in gecko 11.0 (firefox 11.0 / thunderbird 11.0 / seamonkey 2.8) nsifaviconservice handles this interface, so you do not need to directly create a new service.
mozIStorageBindingParams
last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) inherits from: nsisupports you can only create mozistoragebindingparams objects by calling the mozistoragebindingparamsarray.newbindingparams().
mozIStorageStatementParams
for example, say you create a statement like so: var statement = dbconn.createstatement("select * from table_name where id = :item_id"); this object would have one property, item_id, that you can use to bind a value to that named parameter like so: statement.params.item_id = 2; for more details on why you should bind parameters as opposed to hard-coding them into your statement, please see the overview document about binding parameters.
mozIStorageStatementRow
for example, say you create a statement like so: var statement = dbconn.createstatement("select id, name from table_name"); the object would have two properties, id and name, that can be used to get the value of the column after you have called mozistoragestatement.executestep() like so: while (statement.executestep()) { let id = statement.row.id; let name = statement.row.name; } see also storage mozistoragestatement ...
mozIStorageStatementWrapper
when you call the mozistorageconnection interface's createstatement() method, you get a mozistoragestatement which has just direct bindings to sqlite.
mozIStorageVacuumParticipant
1.0 66 introduced gecko 2.0 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) to create an instance of this interface, use the category manger, with the category "vacuum-participant".
nsIAccessible
mozilla creates the implementations of nsiaccessible on demand.
nsIAccessibleProvider
constants common use constants constant value description noaccessible 0 do not create an accessible for this object this is useful if an ancestor binding already implements nsiaccessibleprovider, but no accessible is desired for the inheriting binding.
nsIApplicationCache
clients can open a session with nsicacheservice.createsession() using this client id and a storage policy of store_offline to access this cache.
nsIAuthPrompt
to create an instance, use: var authprompt = components.classes["@mozilla.org/login-manager/prompter;1"] .createinstance(components.interfaces.nsiauthprompt); method overview boolean prompt(in wstring dialogtitle, in wstring text, in wstring passwordrealm, in pruint32 savepassword, in wstring defaulttext, out wstring result); boolean promptpassword(in wstring dialogtitle, in wstring text, in wstring passwordrealm, in pruint32 savepassword, i...
nsIAuthPrompt2
to create an instance, use: var authprompt2 = components.classes["@mozilla.org/login-manager/prompter;1"] .createinstance(components.interfaces.nsiauthprompt2); method overview nsicancelable asyncpromptauth(in nsichannel achannel, in nsiauthpromptcallback acallback, in nsisupports acontext, in pruint32 level, in nsiauthinformation authinfo); boolean promptauth(in nsic...
nsICRLInfo
lastupdate prtime the time this crl was created at.
nsICachingChannel
a cache key retrieved from a particular instance of nsicachingchannel could be set on another instance of nsicachingchannel provided the underlying implementations are compatible and provided the new channel instance was created with the same uri.
nsICategoryManager
the category and/or entry are created if they do not exist.
nsIChannel
inherits from: nsirequest last changed in gecko 19.0 (firefox 19.0 / thunderbird 19.0 / seamonkey 2.16) once a channel is created (via nsiioservice.newchannel()), parameters for that request may be set by using the channel attributes, or by calling queryinterface() to retrieve a subclass of nsichannel for protocol-specific parameters.
nsIChannelPolicy
channels can be created with this interface placed in the property bag and upon redirect, the interface can be transferred from the old channel to the new channel.
nsICommandController
to create an instance, use: var commandcontroller = components.classes["@mozilla.org/embedcomp/base-command-controller;1"] .createinstance(components.interfaces.nsicommandcontroller); method overview void docommandwithparams(in string command, in nsicommandparams acommandparams); void getcommandstatewithparams( in string command, in nsicommandparams acommandparams); methods docommandwithparams() executes the specified command with a set of parameters contained in an nsicom...
nsIConsoleService
function mylogtoconsole(amessage, asourcename, asourceline, alinenumber, acolumnnumber, aflags, acategory) { var consoleservice = components.classes["@mozilla.org/consoleservice;1"] .getservice(components.interfaces.nsiconsoleservice); var scripterror = components.classes["@mozilla.org/scripterror;1"] .createinstance(components.interfaces.nsiscripterror); scripterror.init(amessage, asourcename, asourceline, alinenumber, acolumnnumber, aflags, acategory); consoleservice.logmessage(scripterror); } amessage — the string to be logged.
nsIContentPrefService
to create an instance, use: var contentprefservice = components.classes["@mozilla.org/content-pref/service;1"] .getservice(components.interfaces.nsicontentprefservice); method overview void addobserver(in astring aname, in nsicontentprefobserver aobserver); nsivariant getpref(in nsivariant agroup, in astring aname, [optional] in nsicontentprefcallback acallback);...
nsIContentSecurityPolicy
void refinepolicy( in astring policystring, in nsiuri selfuri ); parameters policystring selfuri scanrequestdata() called after the content security policy object is created to fill in the appropriate request and request header information needed in case a report needs to be sent.
nsIContentSniffer
let charset = "iso-8859-1"; try { // this pref has been removed, see bug 910192 charset = services.prefs.getcomplexvalue("intl.charset.default", ci.nsipreflocalizedstring).data; } catch (e) { } let conv = cc["@mozilla.org/intl/scriptableunicodeconverter"] .createinstance(ci.nsiscriptableunicodeconverter); conv.charset = charset; try { let str = conv.convertfrombytearray(adata, alength); if (str.substring(0, 5) == "%pdf-") return "application/pdf"; // we detected a pdf file } catch (e) { // try to get information from arequest } ...
nsIContentViewManager
this lets you, for example, take the coordinates at which the user clicked (or touched) the screen, and expand outward to create a rectangle from that point.
nsIContentViewer
to create an instance, use: var contentviewer = components.classes["@mozilla.org/????????????????????????????"] .createinstance(components.interfaces.nsicontentviewer); method overview void clearhistoryentry(); void close(in nsishentry historyentry); void destroy(); [noscript,notxpcom,nostdcall] nsiviewptr findcontainerview(); void getbounds(in nsintrectref abounds); native code only!
nsIConverterInputStream
to create an instance, use: var converterinputstream = components.classes["@mozilla.org/intl/converter-input-stream;1"] .createinstance(components.interfaces.nsiconverterinputstream); method overview void init(in nsiinputstream astream, in string acharset, in long abuffersize, in prunichar areplacementchar); constants constant value description default_replacement_cha...
nsIConverterOutputStream
to create an instance, use: var converteroutputstream = components.classes["@mozilla.org/intl/converter-output-stream;1"] .createinstance(components.interfaces.nsiconverteroutputstream); method overview void init(in nsioutputstream aoutstream, in string acharset, in unsigned long abuffersize, in prunichar areplacementcharacter); methods init() initialize this stream.
nsICookieManager2
to create an object implementing this interface: components.utils.import("resource://gre/modules/services.jsm"); var cookieservice = services.cookies; method overview void add(in autf8string ahost, in autf8string apath, in acstring aname, in acstring avalue, in boolean aissecure, in boolean aishttponly, in boolean aissession, in print64 aexpiry); boolean cookieexists(in nsicookie2 acookie)...
nsICryptoHMAC
to create the key object use for instance: var keyobject = components.classes["@mozilla.org/security/keyobjectfactory;1"] .getservice(components.interfaces.nsikeyobjectfactory) .keyfromstring(components.interfaces.nsikeyobject.hmac, rawkeydata); exceptions thrown ns_error_invalid_arg if an unsupported algorithm type is passed.
nsICurrentCharsetListener
to create an instance, use: var currentcharsetlistener = components.classes["@mozilla.org/intl/currentcharsetlistener;1"] .createinstance(components.interfaces.nsicurrentcharsetlistener); method overview void setcurrentcharset(in wstring charset); void setcurrentcomposercharset(in wstring charset); void setcurrentmailcharset(in wstring charset); methods setcurrentcharset() void setcurrentcharset( in wstring charset ); parameters charset setcurrentcomposercharset() void setcurrentcomposercharset( in wstring charset ); parameters ...
nsIDOMChromeWindow
if some xul applications create a dialog like window which has a default button but it's not created by the dialog/wizard element, the applications should call this method for the accessibility and the usability on windows at onload event.
nsIDOMFileReader
to create an instance, use: var filereader = components.classes["@mozilla.org/files/filereader;1"].createinstance(components.interfaces.nsidomfilereader); this interface implements the dom filereader object; see that documentation for details.
nsIDOMGlobalPropertyInitializer
an alternative way to expose an object to the web content is to add the property in response to the content-document-global-created notification.
nsIDOMMozNetworkStats
to create an instance, use: var networkstatsmanager = components.classes["@mozilla.org/networkstats;1"] .createinstance(components.interfaces.nsidomnetworkstats); attributes attribute type description connectiontype domstring connection type of the stats.
nsIDOMMozNetworkStatsManager
to create an instance, use: var networkstatsmanager = components.classes["@mozilla.org/networkstatsmanager;1"] .createinstance(components.interfaces.nsidomnetworkstatsmanager); furthermore, the networkstatsmanager is published through a moznetworkstats child object within the navigator object.
nsIDOMSerializer
to create an instance, use: var domserializer = components.classes["@mozilla.org/xmlextras/xmlserializer;1"] .createinstance(components.interfaces.nsidomserializer); method overview void serializetostream(in nsidomnode root, in nsioutputstream stream, in autf8string charset); astring serializetostring(in nsidomnode root); methods serializetostream() the subtree rooted by the specified elemen...
nsIDOMStorage2
items stored in local storage may only be accessed by the same origin that created the items in the first place.
nsIDOMWindowInternal
url nsidommozurlproperty readonly: a dom url object, which provides the window.url.createobjecturl() and window.url.revokeobjecturl() methods.
nsIDOMXULElement
gets or creates a box object for the element; browser, editor, iframe, listbox, menu, menupopup, scrollbox, tooltip and tree elements receive specialized box objects allowing access to additional properties not normally available from script.
nsIDirectoryServiceProvider
example this code creates a global, read-only string called currdir with the value of the current working directory.
nsIDownloadProgressListener
rather, the developer must create an object with the methods provided below to implement it.
nsIEditorDocShell
methods makeeditable() make this docshell editable, setting a flag that causes an editor to get created, either immediately, or after a url has been loaded.
nsIEditorSpellCheck
to create an instance, use: var editorspellcheck = components.classes["@mozilla.org/editor/editorspellchecker;1"] .createinstance(components.interfaces.nsieditorspellcheck); method overview void addwordtodictionary(in wstring word); boolean canspellcheck(); void checkcurrentdictionary(); boolean checkcurrentword(in wstring suggestedword); boolean checkcurrentwordnosuggest(in wstring suggestedword); astring getcurrentdictionary(); void...
nsIEventListenerService
to create an instance, use: var eventlistenerservice = components.classes["@mozilla.org/eventlistenerservice;1"] .getservice(components.interfaces.nsieventlistenerservice); universalxpconnect privileges are required to use this service.
nsIExternalProtocolService
aoshandlerexists was the object above created for an extant os default handler?
nsIFeedProcessor
to create an instance, use: var feedprocessor = components.classes["@mozilla.org/feed-processor;1"] .createinstance(components.interfaces.nsifeedprocessor); method overview void parseasync(in nsirequestobserver requestobserver, in nsiuri uri); void parsefromstream(in nsiinputstream stream, in nsiuri uri); void parsefromstring(in astring str, in nsiuri uri);...
nsIFileInputStream
if open_on_read is defined, and the file was recreated after the first delete, the file will be deleted again when it is closed again.
nsIFileProtocolHandler
a local file will be created if the url string begins with file://.
nsIFileStreams
if open_on_read is defined, and the file was recreated after the first delete, the file will be deleted again when it is closed again.
nsIFormHistory2
removeentriesbytimeframe() removes entries that were created between the specified times.
nsIGSettingsService
1.0 66 introduced gecko 6.0 inherits from: nsisupports last changed in gecko 6.0 (firefox 6.0 / thunderbird 6.0 / seamonkey 2.3) implemented by: @mozilla.org/gsettings-service;1 as a service: var gsettingsservice = components.classes["@mozilla.org/gsettings-service;1"] .createinstance(components.interfaces.nsigsettingsservice); method overview nsigsettingscollection getcollectionforschema(in autf8string schema); methods getcollectionforschema() nsigsettingscollection getcollectionforschema( in autf8string schema ); parameters schema return value ...
nsIGlobalHistory3
1.0 66 introduced gecko 1.8 obsolete gecko 9.0 inherits from: nsiglobalhistory2 last changed in gecko 1.9 (firefox 3) this interface was originally created as part of nsiglobalhistory2, but was split off during the transition to places.
nsIIdleService
to create an instance, use: var idleservice = components.classes["@mozilla.org/widget/idleservice;1"] .getservice(components.interfaces.nsiidleservice); method overview void addidleobserver(in nsiobserver observer, in unsigned long time); void removeidleobserver(in nsiobserver observer, in unsigned long time); attributes attribute type descript...
nsIInstallLocation
you should not use the exact values here, you should offset from these values each time you create a new install location.
nsIJSID
inherits from: nsisupports last changed in gecko 1.9 (firefox 3) the following methods return objects that implement this interface: components.interfaces.name components.classes[contract] components.interfacesbyid[uuid] components.classesbyid[cid] the first two cases create a named jsid while the last two cases create an unnamed jsid.
nsIJSON
to create an instance, use: var nativejson = components.classes["@mozilla.org/dom/json;1"] .createinstance(components.interfaces.nsijson); method overview note: the idl file has portions of the idl commented out because they represent things that can't actually be properly described by idl; however, for the purposes of this article, we'll pretend they can be and ignore that issue.
nsIJumpListItem
to add types, create the specific interface here, add an implementation class to winjumplistitem, and add support to addlistbuild and removed items processing.
nsILocaleService
newlocale() create a new nsilocale from a locale string.
nsILoginManagerIEMigrationHelper
note: in some cases, multiple logins may be created from a single input when the format is ambiguous.
nsILoginManagerStorage
gecko 1.9.1 note default values for the nsiloginmetainfo properties are created if the specified login doesn't explicitly specify them.
nsIMemoryReporter
1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 8.0 (firefox 8.0 / thunderbird 8.0 / seamonkey 2.5) any piece of code that wishes to allow its memory use to be monitored may create an nsimemoryreporter object and then register it by calling nsimemoryreportermanager.registerreporter().
nsIMessageWakeupService
the method to call to instantiate the component (either "getservice" or "createinstance").
Building an Account Manager Extension
devmoaccountmanagerextension.prototype.contractid = "@mozilla.org/accountmanager/extension;1?name=example@mozilla.org"; // add the component to the mailnews-accountmanager-extensions category devmoaccountmanagerextension.prototype._xpcom_categories: [{ category: "mailnews-accountmanager-extensions" }], // create entry point for the module if (xpcomutils.generatensgetfactory) var nsgetfactory = xpcomutils.generatensgetfactory([devmoaccountmanagerextension]); else var nsgetmodule = xpcomutils.generatensgetmodule([devmoaccountmanagerextension]); step3: create the new panel as next step we create the xul and the property file for your new panel.
nsIMsgCompFields
achments ( ); header methods void setheader(char* name, char* value); references this interface is the type of the following properties: nsimsgcompose.compfields, nsimsgcomposeparams.composefields this interface is passed as an argument to the following methods: nsimsgcomposesecure.begincryptoencapsulation, nsimsgcomposesecure.requirescryptoencapsulation, nsimsgsend.createandsendmessage, nsimsgsend.sendmessagefile, nsismimejshelper.getnocertaddresses, nsismimejshelper.getrecipientcertsinfo ...
nsIMsgCustomColumnHandler
the nsimsgcustomcolumnhandler interface allows you to create custom handlers for columns.
nsIMsgDBView
to create an instance, use: var dbview = components.classes[@mozilla.org/messenger/msgdbview;1?type=] .createinstance(components.interfaces.nsimsgdbview); where type designates different types of view's available.
nsIMsgFilterList
void nsimsgfilterlist::movefilterat ( in unsigned long filterindex, in nsmsgfiltermotionvalue motion ) insertfilterat() void nsimsgfilterlist::insertfilterat ( in unsigned long filterindex, in nsimsgfilter filter ) movefilter() void nsimsgfilterlist::movefilter ( in nsimsgfilter filter, in nsmsgfiltermotionvalue motion ) createfilter() nsimsgfilter nsimsgfilterlist::createfilter ( in astring name ) savetofile() void nsimsgfilterlist::savetofile ( in nsioutputstream stream ) parsecondition() void nsimsgfilterlist::parsecondition ( in nsimsgfilter afilter, in string condition ) savetodefaultfile() void nsimsgfilterlist::savetodefaultfile ( ) applyfilterstohdr() void nsimsgfilterlist::applyfiltersto...
nsIMsgHeaderParser
inherits from: nsisupports last changed in gecko 1.9 (firefox 3) to create an instance, use: var msgheaderparser = components.classes["@mozilla.org/messenger/headerparser;1"] .createinstance(components.interfaces.nsimsgheaderparser); method overview string extractheaderaddressmailboxes(in string line); void extractheaderaddressname(in string line, out string name); void extractheaderaddressnames(in string line, out string usernames); astring makefulladdress(in astring aname, in astring aaddress); string makefulladdressstri...
nsIMsgSendLater
to create an instance, use var msgsendlater = components.classes["@mozilla.org/messengercompose/sendlater;1"] .getservice(components.interfaces.nsimsgsendlater); method overview void sendunsentmessages(in nsimsgidentity identity); void removelistener(in nsimsgsendlaterlistener listener); void addlistener(in nsimsgsendlaterlistener listener); nsimsgfolder getunsentmessagesfolder](in nsimsgidentity identity); attributes attribute type description msgwindow nsimsgwindow methods send...
nsIMsgWindow
to create an instance, use: msgwindow = components.classes["@mozilla.org/messenger/msgwindow;1"] .createinstance(components.interfaces.nsimsgwindow); in thunderbird the default message window is stored in the global variable msgwindow.
nsIMutableArray
note also that null elements can be created as a side effect of insertelementat().
nsINavBookmarkObserver
when a new item is created, all the items following it in the same folder will have their index shifted down, but no additional notifications will be sent.
nsINavHistoryResult
if you need a different view, you'll need to create your own viewer interface.
nsINavHistoryResultNode
dateadded prtime if the node is an item (bookmark, folder, or separator), this value is the time at which the item was created.
nsINavHistoryResultObserver
when an item is moved between containers, a new node is created for the item, and the itemremoved/itemadded methods are used.
nsINavHistoryResultViewer
when an item is moved between containers, a new node is created for the item, and the itemremoved/itemadded methods are used.
nsIParentalControlsService
to create an instance, use: var parentalcontrolsservice = components.classes["@mozilla.org/parental-controls-service;1"] .createinstance(components.interfaces.nsiparentalcontrolsservice); method overview void log(in short aentrytype, in boolean aflag, in nsiuri asource, [optional] in nsifile atarget); boolean requesturioverride(in nsiuri atarget, [optiona...
nsIPasswordManager
to create an instance, use: var passwordmanager = components.classes["@mozilla.org/passwordmanager;1"] .getservice(components.interfaces.nsipasswordmanager); method overview void adduser(in autf8string ahost, in astring auser, in astring apassword); void removeuser(in autf8string ahost, in astring auser); void addreject(in autf8string ahost); void removereject(in autf8strin...
nsIPrivateBrowsingService
in addition, temporary, databases are created to be used for cookies and local storage; these databases are thrown away when private browsing mode is turned off, and the regular databases are re-activated.
nsIProcess2
to create an instance, use: var process2 = components.classes["@mozilla.org/process/util;1"] .createinstance(components.interfaces.nsiprocess2); method overview void runasync([array, size_is(count)] in string args, in unsigned long count, [optional] in nsiobserver observer, [optional] in boolean holdweak); methods runasync() asynchronously runs the process with which...
nsIProtocolHandler
if you wish to create a new protocol handler, you need to implement this interface.
nsIRadioInterfaceLayer
to create an instance, use: var radiointerfacelayer = components.classes["@mozilla.org/telephony/system-worker-manager;1"] .getservice(components.interfaces.nsiinterfacerequestor) .createinstance(components.interfaces.nsiradiointerfacelayer); method overview void answercall(in unsigned long callindex); void deactivatedatacall(in domstring cid, in domstring r...
nsIScriptError2
timestamp long long elapsed time, in milliseconds, from a platform-specific zero time to the time the message was created.
nsIScriptableUnicodeConverter
to create an instance, use: var converter = components.classes["@mozilla.org/intl/scriptableunicodeconverter"] .createinstance(components.interfaces.nsiscriptableunicodeconverter); method overview acstring convertfromunicode(in astring asrc); acstring finish(); astring converttounicode(in acstring asrc); astring convertfrombytearray([const,array,size_...
nsISearchEngine
this should only be called on engines created via nsibrowsersearchservice.addenginewithdetails().
nsISelectionPrivate
native code only!setancestorlimiter void setancestorlimiter( in nsicontent acontent ); parameters acontent native code only!setpresshell internal utility method to set the pres shell on a newly created selection.
nsISessionStore
nsidomnode duplicatetab( in nsidomwindow awindow, in nsidomnode atab ); parameters awindow the window in which the duplicated tab will be created.
nsISocketTransport
to create an instance, call nsisockettransportservice.createtransport() method overview prnetaddr getpeeraddr(); native code only!
nsISound
to use this interface, use: var sound = components.classes["@mozilla.org/sound;1"] .createinstance(components.interfaces.nsisound); method overview void beep(); void init(); void play(in nsiurl aurl); void playeventsound(in unsigned long aeventid); void playsystemsound(in astring soundalias); constants sound event constants constant value description even...
nsIStandardURL
to create an instance, use: var standardurl = components.classes["@mozilla.org/network/standard-url;1"] .createinstance(components.interfaces.nsistandardurl); method overview void init(in unsigned long aurltype, in long adefaultport, in autf8string aspec, in string aorigincharset, in nsiuri abaseuri); attributes attribute type description mutable boolean control whether or not...
nsIStringBundle
alternatively, a string bundle can be created within a javascript context with nsistringbundleservice.
nsIStringBundleOverride
to create an instance, use: var stringbundleservice = components.classes["@mozilla.org/intl/stringbundle/text-override;1"] .getservice(components.interfaces.nsistringbundleoverride); note: you should never need to use this service directly.
nsIStyleSheetService
to create an instance, use: var stylesheetservice = components.classes["@mozilla.org/content/style-sheet-service;1"] .getservice(components.interfaces.nsistylesheetservice); method overview void loadandregistersheet(in nsiuri sheeturi, in unsigned long type); boolean sheetregistered(in nsiuri sheeturi, in unsigned long type); void unregistersheet(in nsiuri sheeturi, in unsigned long ty...
nsITaskbarTabPreview
you can't directly instantiate this interface; instead, call the nsiwintaskbar.createtaskbartabpreview().
nsITextInputProcessorCallback
createinstance(components.interfaces.nsitextinputprocessor); } if (!this._tip.begininputtransaction(window, this._callback)) { return false; } ...
nsITextInputProcessorNotification
"notify-detached" when the nsitextinputprocessor instance loses the rights to create composition, this is notified.
nsIToolkit
null can be passed in, in which case a new thread gets created and a message pump will run in that thread.
nsIToolkitProfile
inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) you should not create these objects yourself; to obtain them, use the nsitoolkitprofileservice interface to create and obtain them.
nsITreeView
to add properties for a particular row, you must use the nsiatomservice to create an nsiatom string, which can then be appended to the array to alter the style (see also styling a tree) getrowproperties: function(index, properties) { var atomservice = components.classes["@mozilla.org/atom-service;1"].getservice(components.interfaces.nsiatomservice); var atom = atomservice.getatom("dummy"); properties.appendelement(atom); } hasnextsibling() used to determine if the ro...
nsIURIFixupInfo
fixupcreatedalternateuri boolean if we created an alternative uri.
nsIUpdateTimerManager
method the method used to instantiate the interface; this should be either getservice or createinstance, depending on your component.
nsIVariant
return value returns the underlying js value, if the variant was created by passing a js object into xpconnect.
nsIWebBrowser
the embedder must create one chrome object for each browser object that is instantiated.
nsIWebBrowserChrome
in this case the implementer is responsible for taking the new webbrowser object and doing any necessary initialization or setup as if it had created the webbrowser itself.
nsIWebNavigation
document nsidomdocument retrieves the current dom document for the frame, or lazily creates a blank document if there is none.
nsIWebProgressListener
for definitions of the remaining functions see related documentation onprogresschange: function(awebprogress, arequest, curself, maxself, curtot, maxtot) {}, onstatuschange: function(awebprogress, arequest, astatus, amessage) {}, onsecuritychange: function(awebprogress, arequest, astate) {} } let filter = cc["@mozilla.org/appshell/component/browser-status-filter;1"] .createinstance(ci.nsiwebprogress); filter.addprogresslistener(mylistener, ci.nsiwebprogress.notify_all); let webprogress = docshell.queryinterface(ci.nsiinterfacerequestor) .getinterface(ci.nsiwebprogress); webprogress.addprogresslistener(filter, ci.nsiwebprogress.notify_all); xulbrowserwindow.onstatechange (etc.) reporterlistener.onlocationchange ...
nsIWorker
methods postmessage() used to allow the worker to send a message back to the web application that created it.
nsIXMLHttpRequest
example code this is a simple example code for opening a simple http request from a xul application (like a mozilla extension) without using observers: var req = components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"].createinstance(); req.open('post', "http://www.foo.bar:8080/nietzsche.do", true); req.send('your=data&and=more&stuff=here'); example 2 var {cu: utils, cc: classes, ci: instances} = components; cu.import('resource://gre/modules/services.jsm'); function xhr(url, cb) { let xhr = cc["@mozilla.org/xmlextras/xmlhttprequest;1"].createinstance(ci.nsixmlhttprequest); let handler = ev => { e...
nsIXPCException
return value native code only!stowjsval void stowjsval( in xpcexjscontextptr cx, in xpcexjsval val ); parameters cx val remarks components.exception is a javascript constructor to create nsixpcexception objects.
nsIXULAppInfo
to create an instance, use: var xulappinfo = components.classes["@mozilla.org/xre/app-info;1"] .getservice(components.interfaces.nsixulappinfo); the nsixulruntime interface is also implemented by "xre/app-info".
nsIXULBuilderListener
example create an object which implements nsixulbuilderlistener: var mylistener = { queryinterface: function(aiid) { if (aiid.equals(components.interfaces.nsixulbuilderlistener) || aiid.equals(components.interfaces.nsisupports)) return this; throw components.results.ns_nointerface; }, willrebuild : function(builder) {}, didrebuild : function(builder) { } } attach the listener to ...
nsIXULRuntime
this will cause components to be auto registered and all fast load data to be re-created.
nsMsgFolderFlagType
imapotheruser = 0x00200000; /// whether this is the template folder const nsmsgfolderflagtype templates = 0x00400000; /// this folder is one of your personal folders that is shared with other users const nsmsgfolderflagtype personalshared = 0x00800000; /// this folder is an imap \\noselect folder const nsmsgfolderflagtype imapnoselect = 0x01000000; /// this folder created offline const nsmsgfolderflagtype createdoffline = 0x02000000; /// this imap folder cannot have children :-( const nsmsgfolderflagtype imapnoinferiors = 0x04000000; /// this folder configured for offline use const nsmsgfolderflagtype offline = 0x08000000; /// this folder has offline events to play back const nsmsgfolderflagtype offlineevents = 0x10000000; /// t...
NS_CStringContainerInit2
when ns_cstringcontainerinit2 is told to copy adata, the copy it creates is null-terminated.
Performance
when you execute a sql statement in isolation, an implicit transaction is created around that statement.
The Thread Manager
application/extension javascript should consider using a chromeworker instead.") interfaces there are several interfaces that provide threading support: nsithreadmanager the thread manager itself lets you create threads.
Troubleshooting XPCOM components registration
often the first time you create an xpcom component, it may fail to register correctly.
Using IndexedDB in chrome
if you are creating a sandbox, and want indexeddb to be available in it, use the wantglobalproperties option in the sandbox constructor: var options = { "wantglobalproperties": ["indexeddb"] } var principal = cc["@mozilla.org/systemprincipal;1"].createinstance(ci.nsiprincipal); var sandbox = components.utils.sandbox(principal, options); // the sandbox will have access to indexeddb var sandboxscript = 'var req = indexeddb.open("my-database");'; components.utils.evalinsandbox(sandboxscript, sandbox); before firefox 33, you would access indexeddb from chrome code using the initwindowless method of the nsiindexeddatabasemanager service.
Status, Recent Changes, and Plans
added do_createinstance.
Using nsIDirectoryService
to do this for application-level locations, create a provider based on appfilelocprovider.
Using nsISimpleEnumerator
using nsisimpleenumerator <stringbundle>.strings var enumerator = document.getelementbyid('astringbundleid').strings; var s = ""; while (enumerator.hasmoreelements()) { var property = enumerator.getnext().queryinterface(components.interfaces.nsipropertyelement); s += property.key + ' = ' + property.value + ';\n'; } alert(s); example using javascript 1.7 features // creates a generator iterating over enum's values function generatorfromsimpleenumerator(enum, interface) { while (enum.hasmoreelements()) { yield enum.getnext().queryinterface(interface); } } var b = document.getelementbyid("stringbundleset").firstchild var props = generatorfromenumerator(b.strings, components.interfaces.nsipropertyelement); var s = ""; for (let property in props) { s += property.key + ' ...
XPCOM tasks
p3 we need to check for aggregation in createinstance().
Xptcall Porting Guide
the tree mozilla/xpcom/reflect/xptcall +--public // exported headers +--src // core source | \--md // platform specific parts | +--mac // mac ppc | +--unix // all unix | \--win32 // win32 | +--test // simple tests to get started \--tests // full tests via api porters are free to create subdirectories under the base md directory for their given platforms and to integrate into the build system as appropriate for their platform.
pyxpidl
xpidl option description pyxpidl equivalent -a emit annotations to typelib n/a (feature removed) -w turn on warnings n/a (this is now the default and can't be turned off) -v verbose mode (nyi) n/a (feature removed) -t creates a typelib of a specific version number n/a (feature removed, and probably never actually worked) -i add an entry to start of include path for #include "nsifoo.idl" -i (unchanged) -o specify the base name for output (-o /tmp/nsifoo for example) -o outputfile (this isn't just the base name, but needs to include the extension; for example -o /tmp/nsifoo.idl) ...
xpidl
MozillaTechXPIDLxpidl
for testing purposes, or one-off interface compilation, xpidl can be run from the command line: usage: ./xpidl -m mode [-w] [-v] [-t version number] [-d filename.pp] [-i path] [-o basename | -e filename.ext] filename.idl -a emit annotations to typelib -w turn on warnings (recommended) -v verbose mode (nyi) -t create a typelib of a specific version number -i add entry to start of include path for ``#include "nsithing.idl" -o use basename (e.g.
Autoconfig file format
how to create a config file file format definition ...
Autoconfiguration in Thunderbird
configuration file this is described at how to create a configuration file and defined on the sub-pages.
DB Views (message lists)
if the user does a quick search or picks a view from the view menu, we create an nsmsgquicksearchdbview.
MailNews Protocols
the service class creates and initializes the url object for the operation, and hands that off to a protocol object to run.
Mail and RDF
what else do we store?) datasources are created when each window's javascript is loaded by declaring the datasource variables in the source javascript as global variables.
Mail client architecture overview
rdf will use the datasource to create user interfaces based on this data.
Mailnews and Mail code review requirements
rubber-stamp approvals for intermittently failing ("orange") test fixes/debugging in order to make it easier to debug and fix tests that fail intermittently ("intermittent orange" tests), we have created the following two rubber-stamps based on this proposal on the tb-planning mailing list.
Building a Thunderbird extension 3: install manifest
open the file called install.rdf that you created at the top of your extension's directory hierarchy and paste the following text into the file: <?xml version="1.0"?> <rdf xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:em="http://www.mozilla.org/2004/em-rdf#"> <description about="urn:mozilla:install-manifest"> <em:id>myfirstext@jen.zed</em:id> <em:name>my first extension</em:name> <em:version>1.0</em:version> <em:creator>jenzed</em:creator> <em:targetapplication> <description> <em:id>{3550f703...
Building a Thunderbird extension 6: Adding JavaScript
in this step we will create a small piece of javascript code that inserts the current date into our statusbar widget.
Access StringBundle from Overlay
access it from javascript as follows: var str = document.getelementbyid("your-extension-strings"); //get the stringbundle object itself str.getstring("propertyname"); //get a string (and do something with it) alternative way let stringbundleservice = cc["@mozilla.org/intl/stringbundle;1"].getservice(ci.nsistringbundleservice); let bundle = stringbundleservice.createbundle("chrome://your_extension/locale/overlay.properties"); let str = bundle.getstringfromname("propertyname"); see nsistringbundleservice ...
Tips and Tricks from the newsgroups
extensions load an extension in its own tab run shell scripts from an extension (for example, to create a symlink) get extension metadata call java from thunderbird extensions (also an example here, written for firefox but compatible with thunderbird 3.x) define a custom protocol handler to call an external program save attachment and send it repeat image display using css sprites messages use reminderfox to open a message in the default thunderbird message ...
customDBHeaders Preference
erfluous"); }, isstring: function() {return true;}, getcellproperties: function(row, col, props){}, getimagesrc: function(row, col) {return null;}, getsortlongforrow: function(hdr) {return 0;} } function addcustomcolumnhandler() { gdbview.addcolumnhandler("colsuperfluous",columnhandler); dump("column handler being added: " + columnhandler + "\n"); } var createdbobserver = { // components.interfaces.nsiobserver observe: function(amsgfolder, atopic, adata) { dump("here here!"); addcustomcolumnhandler(); } } function doonceloaded(){ var observerservice = components.classes["@mozilla.org/observer-service;1"].getservice(components.interfaces.nsiobserverservice); observerservice.addobserver(createdbobserver, "msgcreatedbview", fa...
Using the Mozilla source server
the nightly debug builds are now also source indexed so that by following a couple of simple steps you can also have the source code served to you for debugging without a local build what you'll need windbg or visual studio (note: express editions will not work, but windbg is a free download) a nightly build that was created after april 15, 2008; go to the /pub/firefox/nightly/latest-mozilla-central/ folder and grab the installer for builds predating the switch to mercurial, you'll need cvs.exe, added to your path (the cvs.exe from mozillabuild has problems, use this one instead) note: do not use the cvs from mozillabuild, it will not work!
Httpd.js
this page was auto-generated because a user created a sub-page to this page.
Memory Management
memory management if js code creates a structure or an array, that memory will be valid as long as the js object stays alive.
Working with ArrayBuffers
ing codeblock provides a basic example of getting and setting uint8clampedarray and arraybuffer of imagedata: // context is a canvasrenderingcontext2d of some canvas var imagedata = context.getimagedata(x, y, w, h); var array = imagedata.data; // array is a uint8clampedarray var buffer = imagedata.data.buffer; // buffer is a arraybuffer // incomingbuffer is a typedarray var imagedata2 = context.createimagedata(w, h); imagedata2.data.set(incomingbuffer); further, if you have a byte array pixelbuffer, and you need to create imagedata from it.
CType
these objects have assorted methods and properties that let you create objects of these types, find out information about them, and so forth.
FunctionType
function pointer is created with functiontype.ptr.
PointerType
return value a ctype object describing the newly created data type.
Browser Side Plug-in API - Plugins
npn_geturl asks the browser to create a stream for the specified url.
Preferences System
using this system it is possible to create preferences windows that display and operate appropriately on various platforms (windows, macos x and gnome).
Browser Console - Firefox Developer Tools
on windows, the following code will add a new item to the browser's main menu: var parent = window.document.getelementbyid("appmenuprimarypane"); var makethetea = gbrowser.ownerdocument.defaultview.document.createelementns("http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul", "menuitem"); makethetea.setattribute("label", "a nice cup of tea?"); parent.appendchild(makethetea); on macos, this similar code will add a new item to the "tools" menu: var parent = window.document.getelementbyid("menu_toolspopup"); var makethetea = gbrowser.ownerdocument.defaultview.document.createelementns("http://www.
Browser Toolbox - Firefox Developer Tools
you can use the inspector's node picker to select that panel, and examine and modify its content: you can use the same technique to debug popups created by add-ons.
Set a breakpoint - Firefox Developer Tools
add condition: add a condition and create a conditional breakpoint (see below).
Use a source map - Firefox Developer Tools
the javascript sources executed by the browser are often transformed in some way from the original sources created by a developer.
UI Tour - Firefox Developer Tools
within the scopes pane, you can create watchpoints that pause the debugger when a value is read or assigned.
Debugger.Script - Firefox Developer Tools
for scripts created by eval or the function constructor, this may be a synthesized filename, starting with a valid url and followed by information tracking how the code was introduced into the system; the entire string is not a valid url.
Tutorial: Show Allocations Per Call Path - Firefox Developer Tools
</div> <script> function makefactory(type) { return function factory(content) { var elt = document.createelement(type); elt.textcontent = content; return elt; }; } var divfactory = makefactory('div'); var spanfactory = makefactory('span'); function divsandspans() { for (i = 0; i < 10; i++) { var div = divfactory('div #' + i); div.appendchild(spanfactory('span #' + i)); document.body.appendchild(div); } } function dodivsandspans() { divsandspans...
Deprecated tools - Firefox Developer Tools
we have created this list of deprecated or removed panels.
All keyboard shortcuts - Firefox Developer Tools
chpad code, insert the result as a comment ctrl + l cmd + l ctrl + l re-evaluate current function ctrl + e cmd + e ctrl + e reload the current page, then run scratchpad code ctrl + shift + r cmd + shift + r ctrl + shift + r save the pad ctrl + s cmd + s ctrl + s open an existing pad ctrl + o cmd + o ctrl + o create a new pad ctrl + n cmd + n ctrl + n close scratchpad ctrl + w cmd + w ctrl + w pretty print the code in scratchpad ctrl + p cmd + p ctrl + p show autocomplete suggestions ctrl + space ctrl + space ctrl + space show inline documentation ctrl + shift + space ctrl + shift + space ctrl + shift + space eyedropper...
Basic operations - Firefox Developer Tools
to create a diff, click the button that looks like a venn diagram next to the camera icon (before firefox 47, this looked like a "+/-" icon): you'll be prompted to select the snapshot to use as a baseline, then the snapshot to compare.
Dominators - Firefox Developer Tools
they can just create and use objects, and when the objects are no longer needed, the runtime takes care of cleaning up, and frees the memory the objects occupied.
Dominators view - Firefox Developer Tools
we'll use the monster allocation example, which creates three arrays, each containing 5000 monsters, each monster having a randomly-generated name.
Network request details - Firefox Developer Tools
connecting time taken to create a tcp connection.
Paint Flashing Tool - Firefox Developer Tools
well, when you use transform, the browser creates a separate layer for the element.
Intensive JavaScript - Firefox Developer Tools
tlesscomputationsbutton.disabled = false; console.log(message.data.primes); worker.removeeventlistener("message", handleworkercompletion); } } worker.addeventlistener("message", handleworkercompletion, false); worker.postmessage({ "multiplier": multiplier, "iterations": iterations }); } the main difference here, compared with the original, is that we need to: create a worker send it a message when we are ready to calculate listen for a message called "done", which indicates that the worker has finished.
Shader Editor - Firefox Developer Tools
at first you'll just see a blank window with a button asking you to reload the page: to get started, load a page which creates a webgl context and loads a program into it.
Cache Storage - Firefox Developer Tools
under the cache storage type within the storage inspector you can see the contents of any dom caches created using the cache api.
Cookies - Firefox Developer Tools
created — date and time when the cookie was created.
Web Audio Editor - Firefox Developer Tools
with the web audio api, developers create an audio context.
Web Console Helpers - Firefox Developer Tools
:screenshot creates a screenshot of the current page with the supplied filename.
Rich output - Firefox Developer Tools
for example, by expanding the array in the above list, i get the following: console.log(todolist) (4) […] ​ 0: object { status: "done", description: "morning pages", datecreated: 1552404478137 } ​ 1: object { status: "in progress", description: "refactor styles", datecreated: 1552404493169 } ​ 2: object { status: "to do", description: "create feedback form", datecreated: 1552404512630 } ​ 3: object { status: "to do", description: "normalize table", datecreated: 1552404533790 } ​ length: 4 ​ <prototype>: array [] debugger eval code:1:9 undefined highlighting a...
The JavaScript input interpreter - Firefox Developer Tools
create a screenshot of the current page with the supplied filename.
about:debugging - Firefox Developer Tools
if you used a higher version of firefox prior to installing firefox esr, you will be prompted to create a new user profile, in order to protect your user data.
AbortController.abort() - Web APIs
we first create a controller using the abortcontroller() constructor, then grab a reference to its associated abortsignal object using the abortcontroller.signal property.
AbortController.signal - Web APIs
we first create a controller using the abortcontroller() constructor, then grab a reference to its associated abortsignal object using the abortcontroller.signal property.
AbortSignal: abort event - Web APIs
bubbles no cancelable no interface event event handler onabort examples in the following snippets, we create a new abortcontroller object, and get its abortsignal (available in the signal property).
AbortSignal.aborted - Web APIs
syntax var isaborted = abortsignal.aborted; value a boolean examples in the following snippet, we create a new abortcontroller object, and get its abortsignal (available in the signal property).
AbortSignal.onabort - Web APIs
}; examples in the following snippet, we create a new abortcontroller object, and get its abortsignal (available in the signal property).
AbortSignal - Web APIs
we first create a controller using the abortcontroller() constructor, then grab a reference to its associated abortsignal object using the abortcontroller.signal property.
AbsoluteOrientationSensor - Web APIs
the absoluteorientationsensor constructor creates a new absoluteorientationsensor object which describes the device's physical orientation in relation to the earth's reference coordinate system.
AbsoluteOrientationSensor - Web APIs
constructor absoluteorientationsensor.absoluteorientationsensor() creates a new absoluteorientationsensor object.
Accelerometer.Accelerometer() - Web APIs
the accelerometer constructor creates a new accelerometer object which returns the acceleration of the device along all three axes at the time it is read.
Accelerometer - Web APIs
constructor accelerometer.accelerometer() creates a new accelerometer object.
AmbientLightSensor.AmbientLightSensor() - Web APIs
the ambinentlightsensor() constructor creates a new ambientlightsensor object, which returns the current light level or illuminance of the ambient light around the hosting device.
AmbientLightSensor - Web APIs
constructor ambientlightsensor.ambientlightsensor() creates a new ambientlightsensor object.
AnalyserNode.AnalyserNode() - Web APIs
the analysernode constructor of the web audio api creates a new analysernode object instance.
Animation() - Web APIs
examples in the follow the white rabbit example, the animation() constructor is used to create an animation for the rabbitdownkeyframes using the document's timeline: var rabbitdownanimation = new animation(rabbitdownkeyframes, document.timeline); specifications specification status comment web animationsthe definition of 'animation()' in that specification.
Animation.finished - Web APIs
every time the animation leaves the finished play state (that is, when it starts playing again), a new promise is created for this property.
Animation.onremove - Web APIs
this could result in a huge animations list, which could create a memory leak.
Animation.pause() - Web APIs
WebAPIAnimationpause
example animation.pause() is used many times in the alice in web animations api land growing/shrinking alice game, largely because animations created with the element.animate() method immediately start playing and must be paused manually if you want to avoid that: // animation of the cupcake slowly getting eaten up var nommingcake = document.getelementbyid('eat-me_sprite').animate( [ { transform: 'translatey(0)' }, { transform: 'translatey(-80%)' } ], { fill: 'forwards', easing: 'steps(4, end)', duration: alicechange.effect.timi...
Animation.persist() - Web APIs
WebAPIAnimationpersist
this could result in a huge animations list, which could create a memory leak.
Animation.ready - Web APIs
WebAPIAnimationready
a new promise is created every time the animation enters the "pending" play state as well as when the animation is canceled, since in both of those scenarios, the animation is ready to be started again.
Animation.replaceState - Web APIs
this could result in a huge animations list, which could create a memory leak.
Animation.startTime - Web APIs
*/ function addcat(){ var newcat = document.createelement("div"); newcat.classlist.add("cat"); return newcat; } /* this is the function that adds a cat to the waapi column */ function animatenewcatwithwaapi() { // make a new cat var newcat = addcat(); // animate said cat with the waapi's "animate" function var newanimationplayer = newcat.animate(keyframes, timing); // set the animation's start time to be the same as the original ...
AnimationEvent() - Web APIs
the animationevent() constructor returns a newly created animationevent, representing an event in relation with an animation.
Attr.namespaceURI - Web APIs
WebAPIAttrnamespaceURI
you can create an attribute with the specified namespaceuri using the dom level 2 method element.setattributens.
AudioBuffer() - Web APIs
the audiobuffer constructor of the web audio api creates a new audiobuffer object.
AudioBuffer.copyToChannel() - Web APIs
example var myarraybuffer = audioctx.createbuffer(2, framecount, audioctx.samplerate); var anotherarray = new float32array; // copy channel data from second channel of myarraybuffer.
AudioBufferSourceNode.AudioBufferSourceNode() - Web APIs
the audiobuffersourcenode() constructor creates a new audiobuffersourcenode object instance.
AudioBufferSourceNode.loop - Web APIs
you can run the full example live (or view the source.) function getdata() { source = audioctx.createbuffersource(); request = new xmlhttprequest(); request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; source.playbackrate.value = playbackcontrol.value; source.
AudioBufferSourceNode.loopEnd - Web APIs
function getdata() { source = audioctx.createbuffersource(); request = new xmlhttprequest(); request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; songlength = buffer.duration; source.buffer = mybuffer; source.playbackrate.value =...
AudioBufferSourceNode.loopStart - Web APIs
function getdata() { source = audioctx.createbuffersource(); request = new xmlhttprequest(); request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; songlength = buffer.duration; source.buffer = mybuffer; source.playbackrate.value = p...
AudioBufferSourceNode.playbackRate - Web APIs
<input class="playback-rate-control" type="range" min="0.25" max="3" step="0.05" value="1"> <span class="playback-rate-value">1.0</span> function getdata() { source = audioctx.createbuffersource(); request = new xmlhttprequest(); request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; source.playbackrate.value = playbackcontrol.value; source.
AudioConfiguration - Web APIs
examples //create media configuration to be tested const mediaconfig = { type : 'file', // 'record', 'transmission', or 'media-source' audio : { contenttype : "audio/ogg", // valid content type channels : 2, // audio channels used by the track bitrate : 132700, // number of bits used to encode 1s of audio samplerate : 5200 // number of audio samples making up that 1s.
AudioDestinationNode.maxChannelCount - Web APIs
example the following would set up a simple audio graph, featuring an audiodestinationnode with maxchannelcount of 2: var audioctx = new audiocontext(); var source = audioctx.createmediaelementsource(mymediaelement); source.connect(gainnode); audioctx.destination.maxchannelcount = 2; gainnode.connect(audioctx.destination); to see a more complete implementation, check out one of our mdn web audio examples, such as voice-change-o-matic or violent theremin.
AudioDestinationNode - Web APIs
their speakers), so you can get it hooked up inside an audio graph using only a few lines of code: var audioctx = new audiocontext(); var source = audioctx.createmediaelementsource(mymediaelement); source.connect(gainnode); gainnode.connect(audioctx.destination); to see a more complete implementation, check out one of our mdn web audio examples, such as voice-change-o-matic or violent theremin.
AudioNode.context - Web APIs
WebAPIAudioNodecontext
example const audiocontext = window.audiocontext || window.webkitaudiocontext; const audioctx = new audiocontext(); const oscillator = audioctx.createoscillator(); const gainnode = audioctx.creategain(); oscillator.connect(gainnode).connect(audioctx.destination); console.log(oscillator.context); // audiocontext console.log(oscillator.context === audioctx); // true specifications specification status comment web audio apithe definition of 'context' in that specification.
AudioNode.disconnect() - Web APIs
example var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var oscillator = audioctx.createoscillator(); var gainnode = audioctx.creategain(); oscillator.connect(gainnode); gainnode.connect(audioctx.destination); gainnode.disconnect(); specifications specification status comment web audio apithe definition of 'disconnect' in that specification.
AudioNode.numberOfInputs - Web APIs
example const audioctx = new audiocontext(); const oscillator = audioctx.createoscillator(); const gainnode = audioctx.creategain(); oscillator.connect(gainnode).connect(audioctx.destination); console.log(oscillator.numberofinputs); // 0 console.log(gainnode.numberofinputs); // 1 console.log(audioctx.destination.numberofinputs); // 1 specifications specification status comment web audio apithe definition of 'numberofinputs' in that specification.
AudioNode.numberOfOutputs - Web APIs
example const audioctx = new audiocontext(); const oscillator = audioctx.createoscillator(); const gainnode = audioctx.creategain(); oscillator.connect(gainnode).connect(audioctx.destination); console.log(oscillator.numberofoutputs); // 1 console.log(gainnode.numberofoutputs); // 1 console.log(audioctx.destination.numberofoutputs); // 0 specifications specification status comment web audio apithe definition of 'numberofoutputs' in that specification.
AudioParam.cancelAndHoldAtTime() - Web APIs
syntax var audioparam = audioparam.cancelandholdattime(canceltime) parameters canceltime a double representing the time (in seconds) after the audiocontext was first created after which all scheduled changes will be cancelled.
AudioParam.defaultValue - Web APIs
example const audioctx = new audiocontext(); const gainnode = audioctx.creategain(); const defaultval = gainnode.gain.defaultvalue; console.log(defaultval); // 1 console.log(defaultval === gainnode.gain.value); // true specifications specification status comment web audio apithe definition of 'defaultvalue' in that specification.
AudioParam.maxValue - Web APIs
example const audioctx = new audiocontext(); const gainnode = audioctx.creategain(); console.log(gainnode.gain.maxvalue); // 3.4028234663852886e38 specifications specification status comment web audio apithe definition of 'maxvalue' in that specification.
AudioParam.minValue - Web APIs
example const audioctx = new audiocontext(); const gainnode = audioctx.creategain(); console.log(gainnode.gain.minvalue); // -3.4028234663852886e38 specifications specification status comment web audio apithe definition of 'minvalue' in that specification.
AudioParam.value - Web APIs
WebAPIAudioParamvalue
const audioctx = new audiocontext(); const gainnode = audioctx.creategain(); gainnode.gain.value = 0.4; //which is identical to: gainnode.gain.setvalueattime(0.4, audioctx.currenttime); specifications specification status comment web audio apithe definition of 'value' in that specification.
AudioScheduledSourceNode.stop() - Web APIs
context = new audiocontext(); osc = context.createoscillator(); osc.connect(context.destination); /* let's play a sine wave for one second.
AudioScheduledSourceNode - Web APIs
you can't create an audioscheduledsourcenode object directly.
AudioTrack.sourceBuffer - Web APIs
the read-only audiotrack property sourcebuffer returns the sourcebuffer that created the track, or null if the track was not created by a sourcebuffer or the sourcebuffer has been removed from the mediasource.sourcebuffers attribute of its parent media source.
AudioWorkletGlobalScope - Web APIs
a read-only property of a baseaudiocontext // and is set only during its instantiation console.log(samplerate) // you can declare any variables and use them in your processors // for example it may be an arraybuffer with a wavetable const usefulvariable = 42 console.log(usefulvariable) registerprocessor('test-processor', testprocessor) next, in our main scripts file we'll load the processor, create an instance of audioworkletnode — passing the name of the processor to it — and connect the node to an audio graph.
AudioWorkletNode() - Web APIs
the audioworkletnode() constructor creates a new audioworkletnode object, which represents an audionode that uses a javascript function to perform custom audio processing.
AudioWorkletProcessor.process - Web APIs
examples in this example we create an audioworkletprocessor that outputs white noise to its first output.
AuthenticatorAssertionResponse - Web APIs
the assertion signature is created with the private key of keypair that was created during the navigator.credentials.create() call and verified using the public key of that same keypair.
BaseAudioContext.destination - Web APIs
var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); // older webkit/blink browsers require a prefix var oscillatornode = audioctx.createoscillator(); var gainnode = audioctx.creategain(); oscillatornode.connect(gainnode); gainnode.connect(audioctx.destination); specifications specification status comment web audio apithe definition of 'destination' in that specification.
BasicCardRequest - Web APIs
those are: amex cartebancaire diners discover jcb mastercard mir unionpay visa examples in the following example, the paymentrequest() constructor is used to create a new payment request, which takes three objects as parameters — one containing details of the payment methods that can be used for the payment, one containing details of the actual order (such as items bought and shipping options), and an optional object that describes what data is needed to fullfil the payment (e.g., a shipping address).
BasicCardResponse - Web APIs
examples in the following example, the paymentrequest() constructor is used to create a new payment request, which takes three objects as parameters — one containing details of the payment methods that can be used for the payment, one containing details of the actual order (such as items bought and shipping options), and an optional object containing further options.
Beacon API - Web APIs
another technique is to create a no-op loop for several seconds within the unload handler to delay the unload and submit data to a server.
BeforeInstallPromptEvent - Web APIs
x="116" y="1" width="240" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="236" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">beforeinstallpromptevent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor beforeinstallpromptevent() creates a new beforeinstallpromptevent.
BiquadFilterNode() - Web APIs
the biquadfilternode() constructor of the web audio api creates a new biquadfilternode object, which represents a simple low-order filter, and is created using the audiocontext.createbiquadfilter() method.
Blob.slice() - Web APIs
WebAPIBlobslice
the blob interface's slice() method creates and returns a new blob object which contains data from a subset of the blob on which it's called.
BlobEvent.BlobEvent() - Web APIs
the blobevent() constructor returns a newly created blobevent object with an associated blob.
BlobEvent - Web APIs
WebAPIBlobEvent
constructor blobevent() creates a blobevent event with the given parameters.
Body.text() - Web APIs
WebAPIBodytext
when getdata() is run, we create a new request using the request() constructor, then use it to fetch a specific .txt file.
Body - Web APIs
WebAPIBody
html content <img class="my-image" src="https://udn.realityripple.com/samples/46/29059a2b39.png"> js content const myimage = document.queryselector('.my-image'); fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/delete_key1.jpg') .then(res => res.blob()) .then(res => { const objecturl = url.createobjecturl(res); myimage.src = objecturl; }); specifications specification status comment fetchthe definition of 'body' in that specification.
BroadcastChannel - Web APIs
get="_top"><rect x="151" y="1" width="160" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="231" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">broadcastchannel</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor broadcastchannel() creates an object linking to the named channel.
ByteLengthQueuingStrategy.ByteLengthQueuingStrategy() - Web APIs
the bytelengthqueuingstrategy() constructor creates and returns a bytelengthqueuingstrategy object instance.
ByteLengthQueuingStrategy - Web APIs
constructor bytelengthqueuingstrategy() creates a new bytelengthqueuingstrategy object instance.
CSSImageValue - Web APIs
examples we create an element <button>magic wand</button> we add some css, including a background image requesting a binary file: button { display: inline-block; min-height: 100px; min-width: 100px; background: no-repeat 5% center url(https://mdn.mozillademos.org/files/16793/magicwand.png) aqua; } we get the element's style map.
CSSKeywordValue.CSSKeywordValue() - Web APIs
the csskeywordvalue constructor creates a new csskeywordvalue object which represents css keywords and other identifiers.
CSSMathProduct.CSSMathProduct() - Web APIs
the cssmathproduct() constructor creates a new cssmathproduct object which creates a new cssmathproduct object which syntax var cssmathproduct = new cssmathproduct() parameters arg a value for the cssmathproduct object to be constructed either a double integer or a cssnumericvalue.
CSSMathProduct - Web APIs
constructor cssmathproduct.cssmathproduct() creates a new cssmathproduct object.
CSSMathSum.CSSMathSum() - Web APIs
the cssmathsum() constructor creates a new cssmathsum object which creates a new csskeywordvalue object which represents the result obtained by calling add(), sub(), or tosum() on cssnumericvalue.
CSSMathValue.operator - Web APIs
interface value cssmathsum "sum" cssmathproduct "product" cssmathmin "min" cssmathmax "max" cssmathclamp "clamp" cssmathnegate "negate" cssmathinvert "invert" examples we create an element with a width determined using a calc() function, then console.log() the operator.
CSSMathValue - Web APIs
examples we create an element with a width determined using a calc() function, then console.log() the operator.
CSSPositionValue.CSSPositionValue() - Web APIs
the csspositionvalue constructor creates a new csspositionvalue object which represents values for properties that take a position, for example object-position.
CSSPositionValue - Web APIs
constructor csspositionvalue.csspositionvalue() creates a new csspositionvalue object.
CSSStyleDeclaration - Web APIs
cssstyledeclaration.setproperty() modifies an existing css property or creates a new css property in the declaration block.
CSSStyleSheet.insertRule() - Web APIs
* @param {array} rules accepts an array of json-encoded declarations * @example addstylesheetrules([ ['h2', // also accepts a second argument as an array of arrays instead ['color', 'red'], ['background-color', 'green', true] // 'true' for !important rules ], ['.myclass', ['background-color', 'yellow'] ] ]); */ function addstylesheetrules (rules) { var styleel = document.createelement('style'); // append <style> element to <head> document.head.appendchild(styleel); // grab style element's sheet var stylesheet = styleel.sheet; for (var i = 0; i < rules.length; i++) { var j = 1, rule = rules[i], selector = rule[0], propstr = ''; // if the second argument of a rule is an array of arrays, correct our variables.
CSSUnitValue.CSSUnitValue() - Web APIs
the cssunitvalue() constructor creates a new cssunitvalue object which returns a new cssunitvalue object which represents values that contain a single unit type.
CSSUnitValue.unit - Web APIs
WebAPICSSUnitValueunit
examples the following creates a csspositionvalue from individual cssunitvalue constructors, then queries the cssunitvalue.unit.
CSSUnitValue.value - Web APIs
examples the following creates a csspositionvalue from individual cssunitvalue constructors, then queries the cssunitvalue.value.
CSSUnitValue - Web APIs
constructor cssstylevalue.cssunitvalue() creates a new cssunitvalue object.
CSSUnparsedValue.CSSUnparsedValue() - Web APIs
the cssunparsedvalue() constructor creates a new cssunparsedvalue object which represents property values that reference custom properties.
CSSUnparsedValue - Web APIs
constructor cssunparsedvalue.cssunparsedvalue() creates a new cssunparsedvalue object.
CSSVariableReferenceValue() - Web APIs
creates a new cssvariablereferencevalue.
Cache.add() - Web APIs
WebAPICacheadd
this consists of calling cachestorage.open to create a new cache, then using cache.add to add an asset to it.
CacheStorage.keys() - Web APIs
WebAPICacheStoragekeys
the keys() method of the cachestorage interface returns a promise that will resolve with an array containing strings corresponding to all of the named cache objects tracked by the cachestorage object in the order they were created.
CanvasGradient.addColorStop() - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); let gradient = ctx.createlineargradient(0, 0, 200, 0); gradient.addcolorstop(0, 'green'); gradient.addcolorstop(.7, 'white'); gradient.addcolorstop(1, 'pink'); ctx.fillstyle = gradient; ctx.fillrect(10, 10, 200, 100); result specifications specification status comment html living standardthe definition of 'canvasgradient.addcolorstop' in that specification.
CanvasGradient - Web APIs
it is returned by the methods canvasrenderingcontext2d.createlineargradient() or canvasrenderingcontext2d.createradialgradient().
CanvasPattern - Web APIs
the canvaspattern interface represents an opaque object describing a pattern, based on an image, a canvas, or a video, created by the canvasrenderingcontext2d.createpattern() method.
CanvasRenderingContext2D.arc() - Web APIs
syntax void ctx.arc(x, y, radius, startangle, endangle [, anticlockwise]); the arc() method creates a circular arc centered at (x, y) with a radius of radius.
CanvasRenderingContext2D.drawImage() - Web APIs
for example, if you load an image and specify the optional size parameters in its constructor, you will have to use the naturalwidth and naturalheight properties of the created instance to properly calculate things like crop and scale regions, rather than element.width and element.height.
CanvasRenderingContext2D.fill() - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // create path let region = new path2d(); region.moveto(30, 90); region.lineto(110, 20); region.lineto(240, 130); region.lineto(60, 130); region.lineto(190, 20); region.lineto(270, 90); region.closepath(); // fill path ctx.fillstyle = 'green'; ctx.fill(region, 'evenodd'); result specifications specification status comment html living standardthe definition of 'canvasrendering...
CanvasRenderingContext2D.fillText() - Web APIs
this code creates a context 400 pixels wide and 150 pixels across.
CanvasRenderingContext2D.imageSmoothingQuality - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); let img = new image(); img.src = 'https://mdn.mozillademos.org/files/222/canvas_createpattern.png'; img.onload = function() { ctx.imagesmoothingquality = 'low'; ctx.drawimage(img, 0, 0, 300, 150); }; result specifications specification status comment html living standardthe definition of 'imagesmoothingquality' in that specification.
CanvasRenderingContext2D.isPointInPath() - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // create circle const circle = new path2d(); circle.arc(150, 75, 50, 0, 2 * math.pi); ctx.fillstyle = 'red'; ctx.fill(circle); // listen for mouse moves canvas.addeventlistener('mousemove', function(event) { // check whether point is inside circle if (ctx.ispointinpath(circle, event.offsetx, event.offsety)) { ctx.fillstyle = 'green'; } else { ctx.fillstyle = 'red'; } // draw circle ...
CanvasRenderingContext2D.isPointInStroke() - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // create ellipse const ellipse = new path2d(); ellipse.ellipse(150, 75, 40, 60, math.pi * .25, 0, 2 * math.pi); ctx.linewidth = 25; ctx.strokestyle = 'red'; ctx.fill(ellipse); ctx.stroke(ellipse); // listen for mouse moves canvas.addeventlistener('mousemove', function(event) { // check whether point is inside ellipse's stroke if (ctx.ispointinstroke(ellipse, event.offsetx, event.offsety)) { ctx.s...
CanvasRenderingContext2D.moveTo() - Web APIs
examples creating multiple sub-paths this example uses moveto() to create two sub-paths within a single path.
CanvasRenderingContext2D.setLineDash() - Web APIs
html <canvas id="canvas"></canvas> javascript the drawdashedline() function created below makes the drawing of multiple dashed lines simple.
CanvasRenderingContext2D.stroke() - Web APIs
examples a simple stroked rectangle this example creates a rectangle using the rect() method, and then draws it to the canvas using stroke().
CanvasRenderingContext2D.strokeText() - Web APIs
this code creates a context 400 pixels wide and 150 pixels high.
Basic usage of canvas - Web APIs
the rendering context the <canvas> element creates a fixed-size drawing surface that exposes one or more rendering contexts, which are used to create and manipulate the content shown.
Finale - Web APIs
WebAPICanvas APITutorialFinale
web audio the web audio api provides a powerful and versatile system for controlling audio on the web, allowing developers to choose audio sources, add effects to audio, create audio visualizations, apply spatial effects (such as panning) and much more.
Canvas API - Web APIs
javascript infovis toolkit creates interactive data visualizations.
ChannelMergerNode() - Web APIs
the channelmergernode() constructor creates a new channelmergernode object instance.
ChannelSplitterNode.ChannelSplitterNode() - Web APIs
the channelsplitternode() constructor of the web audio api creates a new channelsplitternode object instance, representing a node that splits the input into a separate output for each of the source node's audio channels.
Clients.openWindow() - Web APIs
the openwindow() method of the clients interface creates a new top level browsing context and loads a given url.
Clients - Web APIs
WebAPIClients
examples the following example shows an existing chat window or creates a new one when the user clicks a notification.
Clipboard.read() - Web APIs
WebAPIClipboardread
unable to access it."); } else { const blob = data.items[i].gettype("image/png"); imgelem.src = url.createobjecturl(blob); } } }); } }); note: at this time, while firefox does implement read(), it does not recognize the "clipboard-read" permission, so attempting to use the permissions api to manage access to the api will not work.
ClipboardEvent() - Web APIs
the clipboardevent() constructor returns a newly created clipboardevent, representing an event providing information related to modification of the clipboard, that is cut, copy, and paste events.
ClipboardEvent - Web APIs
constructor clipboardevent() creates a clipboardevent event with the given parameters.
CloseEvent() - Web APIs
the closeevent() constructor creates a new closeevent.
CompositionEvent.CompositionEvent() - Web APIs
the compositionevent() constructor creates a new compositionevent object instance.
CompositionEvent - Web APIs
get="_top"><rect x="231" y="1" width="160" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="311" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">compositionevent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor compositionevent() creates a new compositionevent object instance.
Console API - Web APIs
the console api spec was created to define consistent behavior, and all modern browsers eventually settled on implementing this behavior — although some implementations still have their own additional proprietary functions.
ContentIndexEvent() - Web APIs
the contentindexevent() constructor creates a new contentindexevent object whose type and other options are configured as specified.
ContentIndexEvent - Web APIs
constructor contentindexevent() creates and returns a new contentindexevent object whose type and other options are configured as specified.
CountQueuingStrategy.CountQueuingStrategy() - Web APIs
the countqueuingstrategy() constructor creates and returns a countqueuingstrategy object instance.
CountQueuingStrategy - Web APIs
constructor countqueuingstrategy() creates a new countqueuingstrategy object instance.
CredentialsContainer - Web APIs
methods credentialscontainer.create()secure context returns a promise that resolves with a new credential instance based on the provided options, or null if no credential object can be created.
CustomElementRegistry.upgrade() - Web APIs
examples taken from the html spec: const el = document.createelement("spider-man"); class spiderman extends htmlelement {} customelements.define("spider-man", spiderman); console.assert(!(el instanceof spiderman)); // not yet upgraded customelements.upgrade(el); console.assert(el instanceof spiderman); // upgraded!
CustomEvent.detail - Web APIs
example // add an appropriate event listener obj.addeventlistener("cat", function(e) { process(e.detail) }); // create and dispatch the event let event = new customevent("cat", { detail: { hazcheeseburger: true } }); obj.dispatchevent(event); // will return an object contaning the hazcheeseburger property let mydetail = event.detail; specifications specification status comment domthe definition of 'detail' in that specification.
CustomEvent.initCustomEvent() - Web APIs
events initialized in this way must have been created with the document.createevent() method.
DOMException() - Web APIs
return value domexception a newly created domexception object.
DOMParser() - Web APIs
the domparser() constructor creates a new domparser object.
DOMPointInit.w - Web APIs
WebAPIDOMPointInitw
there are two methods which use dompointinit: the static function dompointreadonly.frompoint() takes an object that complies with dompointinit as its sole input parameter, to specify the coordinates and perspective value of the new point to be created.
DOMPointInit.y - Web APIs
WebAPIDOMPointInity
there are two methods which use dompointinit: the static function dompointreadonly.frompoint() takes an object that complies with dompointinit as its sole input parameter, to specify the coordinates and perspective value of the new point to be created.
DOMPointInit.z - Web APIs
WebAPIDOMPointInitz
there are two methods which use dompointinit: the static function dompointreadonly.frompoint() takes an object that complies with dompointinit as its sole input parameter, to specify the coordinates and perspective value of the new point to be created.
DOMPointReadOnly.toJSON() - Web APIs
example this example creates a dompoint object representing the top-left corner of the current window, in screen coordinates, then converts that to json.
DOMQuad - Web APIs
WebAPIDOMQuad
constructor domquad.domquad() creates a new domquad object.
DOMRectReadOnly.fromRect() - Web APIs
the fromrect() property of the domrectreadonly interface creates a new domrectreadonly object with a given location and dimensions.
DataTransfer() - Web APIs
the datatransfer constructor creates a new datatransfer object instance.
DataTransfer.dropEffect - Web APIs
when the datatransfer object is created, dropeffect is set to a string value.
DataTransfer.effectAllowed - Web APIs
the move operation is used to indicate that the data being dragged will be moved, and the link operation is used to indicate that some form of relationship or connection will be created between the source and drop locations.
DataTransfer - Web APIs
constructor datatransfer() creates and returns a new datatransfer object.
DedicatedWorkerGlobalScope: message event - Web APIs
bubbles no cancelable no interface messageevent event handler property onmessage examples this code creates a new worker and sends it a message using worker.postmessage(): const worker = new worker("static/scripts/worker.js"); worker.addeventlistener('message', (event) => { console.log(`received message from worker: ${event.data}`) }); the worker can listen for this message using addeventlistener(): // inside static/scripts/worker.js self.addeventlistener('message', (event) => { console.log(`received message from parent: ${event.data}`); }); ...
DedicatedWorkerGlobalScope.postMessage() - Web APIs
inside the handler a calculation is done from which a result message is created; this is then sent back to the main thread using postmessage(workerresult); onmessage = function(e) { console.log('message received from main script'); var workerresult = 'result: ' + (e.data[0] * e.data[1]); console.log('posting message back to main script'); postmessage(workerresult); } in the main script, onmessage would have to be called on a worker object, whereas inside the worke...
DelayNode() - Web APIs
the delaynode() constructor of the web audio api creates a new delaynode object with a delay-line; an audionode audio-processing module that causes a delay between the arrival of an input data, and its propagation to the output.
DeviceMotionEvent.DeviceMotionEvent() - Web APIs
the devicemotionevent constructor creates a new devicemotionevent.
DeviceMotionEvent - Web APIs
constructor devicemotionevent.devicemotionevent() creates a new devicemotionevent.
DeviceOrientationEvent.DeviceOrientationEvent() - Web APIs
the deviceorientationevent constructor creates a new deviceorientationevent.
DeviceOrientationEvent - Web APIs
constructor deviceorientationevent.deviceorientationevent() creates a new deviceorientationevent.
Document() - Web APIs
WebAPIDocumentDocument
the document constructor creates a new document object that is a web page loaded in the browser and serving as an entry point into the page's content.
Document.body - Web APIs
WebAPIDocumentbody
syntax const objref = document.body document.body = objref example // given this html: <body id="oldbodyelement"></body> alert(document.body.id); // "oldbodyelement" const anewbodyelement = document.createelement("body"); anewbodyelement.id = "newbodyelement"; document.body = anewbodyelement; alert(document.body.id); // "newbodyelement" notes document.body is the element that contains the content for the document.
Document.caretRangeFromPoint() - Web APIs
x, e.clienty); textnode = range.offsetnode; offset = range.offset; } else if (document.caretrangefrompoint) { range = document.caretrangefrompoint(e.clientx, e.clienty); textnode = range.startcontainer; offset = range.startoffset; } // only split text_nodes if (textnode && textnode.nodetype == 3) { let replacement = textnode.splittext(offset); let br = document.createelement('br'); textnode.parentnode.insertbefore(br, replacement); } } let paragraphs = document.getelementsbytagname("p"); for (let i = 0; i < paragraphs.length; i++) { paragraphs[i].addeventlistener('click', insertbreakatpoint, false); } result ...
Document.doctype - Web APIs
WebAPIDocumentdoctype
use domimplementation.createdocumenttype() to create a documenttype.
Document.getElementById() - Web APIs
when creating an element and assigning it an id, you have to insert the element into the document tree with node.insertbefore() or a similar method before you can access it with getelementbyid(): var element = document.createelement('div'); element.id = 'testqq'; var el = document.getelementbyid('testqq'); // el will be null!
Document.implementation - Web APIs
for example, the domimplementation interface includes a createdocumenttype method with which dtds can be created for one or more documents managed by the implementation.
Document.importNode() - Web APIs
the document object's importnode() method creates a copy of a node or documentfragment from another document, to be inserted into the current document later.
Document.links - Web APIs
WebAPIDocumentlinks
example var links = document.links; for(var i = 0; i < links.length; i++) { var linkhref = document.createtextnode(links[i].href); var linebreak = document.createelement("br"); document.body.appendchild(linkhref); document.body.appendchild(linebreak); } specifications specification status comment html living standardthe definition of 'document.links' in that specification.
Document.readyState - Web APIs
var span = document.createelement("span"); span.textcontent = "a <span> element."; document.body.appendchild(span); break; case "complete": // the page is fully loaded.
Document.registerElement() - Web APIs
the mytag variable holds a constructor that you can use to create a my-tag element in the document as follows: document.body.appendchild(new mytag()); this inserts an empty my-tag element that will be visible if you use the browser's developer tools.
Document.styleSheetSets - Web APIs
example given an <ul> (list) element with the id "sheetlist", you can populate it with the names of all the available style sheet sets with code like this: let list = document.getelementbyid('sheetlist'); let sheets = document.stylesheetsets; list.innerhtml = ''; for (let i = 0; i < sheets.length; i++) { let item = document.createelement('li'); item.innerhtml = sheets[i]; list.appendchild(item); } notes the list of available style sheet sets is constructed by enumerating all the style sheets available for the document, in the order in which they're listed in the document.stylesheets attribute, adding the title of each style sheet that has a title to the list.
Document.timeline - Web APIs
WebAPIDocumenttimeline
this timeline is a special instance of documenttimeline that is automatically created on page load.
Document: touchcancel event - Web APIs
the touchcancel event is fired when one or more touch points have been disrupted in an implementation-specific manner (for example, too many touch points are created).
Document: transitionrun event - Web APIs
the transitionrun event is fired when a css transition is first created, i.e.
Document: transitionstart event - Web APIs
the difference is transitionstart and transitionrun is that transitionrun fires when the transition is created (i.e.
Document.xmlVersion - Web APIs
to detect this, you can create an element with its name in lower case, then check to see if it gets converted into all upper case (in which case the document is in the non-xml html mode): if (document.createelement("foo").tagname == "foo") { /* document is not xml */ } specifications http://www.w3.org/tr/dom-level-3-cor...ument3-version this has been removed from dom core level 4wd ...
DocumentOrShadowRoot.caretPositionFromPoint() - Web APIs
nt(e.clientx, e.clienty); textnode = range.offsetnode; offset = range.offset; } else if (document.caretrangefrompoint) { range = document.caretrangefrompoint(e.clientx, e.clienty); textnode = range.startcontainer; offset = range.startoffset; } // only split text_nodes if (textnode.nodetype == 3) { var replacement = textnode.splittext(offset); var br = document.createelement('br'); textnode.parentnode.insertbefore(br, replacement); } } window.onload = function (){ var paragraphs = document.getelementsbytagname("p"); for (i=0 ; i < paragraphs.length; i++) { paragraphs[i].addeventlistener("click", insertbreakatpoint, false); } }; specifications specification status comment css object model (cssom) view modulethe definit...
DocumentOrShadowRoot.elementFromPoint() - Web APIs
example this example creates two buttons which let you set the current color of the paragraph element located under the coordinates (2, 2).
DocumentTimeline.DocumentTimeline() - Web APIs
the documenttimeline() constructor of the web animations api creates a new instance of the documenttimeline object associated with the active document of the current browsing context.
DocumentTimeline - Web APIs
constructor documenttimeline() creates a new documenttimeline object associated with the active document of the current browsing context.
Events and the DOM - Web APIs
when an event occurs, an event object is created and passed sequentially to the event listeners.
Example - Web APIs
var para = document.getelementsbytagname("p").item(0); para.firstchild.data = "this is the first paragraph."; // create a new text node for the second paragraph var newtext = document.createtextnode("this is the second paragraph."); // create a new element to be the second paragraph var newelement = document.createelement("p"); // put the text in the paragraph newelement.appendchild(newtext); // and put the paragraph on the end of the document by appending it to // the body (whic...
DynamicsCompressorNode() - Web APIs
the dynamicscompressornode() constructor creates a new dynamicscompressornode object which provides a compression effect, which lowers the volume of the loudest parts of the signal, in order to help prevent clipping and distortion.
DynamicsCompressorNode.reduction - Web APIs
example var audioctx = new audiocontext(); var compressor = audioctx.createdynamicscompressor(); var myreduction = compressor.reduction; specifications specification status comment web audio apithe definition of 'reduction' in that specification.
EXT_disjoint_timer_query.beginQueryEXT() - Web APIs
examples var ext = gl.getextension('ext_disjoint_timer_query'); var query = ext.createqueryext(); ext.beginqueryext(ext.time_elapsed_ext, query); // ...
EXT_disjoint_timer_query.deleteQueryEXT() - Web APIs
examples var ext = gl.getextension('ext_disjoint_timer_query'); var query = ext.createqueryext(); // ...
EXT_disjoint_timer_query.endQueryEXT() - Web APIs
examples var ext = gl.getextension('ext_disjoint_timer_query'); var query = ext.createqueryext(); ext.beginqueryext(ext.time_elapsed_ext, query); // ...
EXT_disjoint_timer_query.getQueryEXT() - Web APIs
examples var ext = gl.getextension('ext_disjoint_timer_query'); var startquery = ext.createqueryext(); ext.querycounterext(startquery, ext.timestamp_ext); var currentquery = ext.getqueryext(ext.timestamp_ext, ext.current_query_ext); specifications specification status comment ext_disjoint_timer_querythe definition of 'ext_disjoint_timer_query' in that specification.
EXT_disjoint_timer_query.getQueryObjectEXT() - Web APIs
examples var ext = gl.getextension('ext_disjoint_timer_query'); var query = ext.createqueryext(); ext.beginqueryext(ext.time_elapsed_ext, query); // ...
EXT_disjoint_timer_query.isQueryEXT() - Web APIs
examples var ext = gl.getextension('ext_disjoint_timer_query'); var query = ext.createqueryext(); // ...
EXT_disjoint_timer_query.queryCounterEXT() - Web APIs
examples var ext = gl.getextension('ext_disjoint_timer_query'); var startquery = ext.createqueryext(); var endquery = ext.createqueryext(); ext.querycounterext(startquery, ext.timestamp_ext); // ...
EXT_disjoint_timer_query - Web APIs
ext.createqueryext() creates a new webglquery.
EXT_float_blend - Web APIs
examples const gl = canvas.getcontext('webgl2'); // enable necessary extensions gl.getextension('ext_color_buffer_float'); gl.getextension('ext_float_blend'); const tex = gl.createtexture(); gl.bindtexture(gl.texture_2d, tex); // use floating point format gl.teximage2d(gl.texture_2d, 0, gl.rgba32f, 1, 1, 0, gl.rgba, gl.float, null); const fb = gl.createframebuffer(); gl.bindframebuffer(gl.framebuffer, fb); gl.framebuffertexture2d(gl.framebuffer, gl.color_attachment0, gl.texture_2d, tex, 0); // enable blending gl.enable(gl.blend); gl.drawarrays(gl.points, 0, 1); // won't...
EXT_sRGB - Web APIs
WebAPIEXT sRGB
examples var ext = gl.getextension('ext_srgb'); var texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); gl.teximage2d(gl.texture_2d, 0, ext.srgb_ext, 512, 512, 0, ext.srgb_ext, gl.unsigned_byte, image); specifications specification status comment ext_srgbthe definition of 'ext_srgb' in that specification.
EXT_texture_compression_bptc - Web APIs
examples var ext = gl.getextension('ext_texture_compression_bptc'); var texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); gl.compressedteximage2d(gl.texture_2d, 0, ext.compressed_rgba_bptc_unorm_ext, 128, 128, 0, texturedata); specifications specification status ext_texture_compression_bptc community approved ...
EXT_texture_compression_rgtc - Web APIs
examples var ext = gl.getextension('ext_texture_compression_rgtc'); var texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); gl.compressedteximage2d(gl.texture_2d, 0, ext.compressed_red_rgtc1_ext, 128, 128, 0, texturedata); specifications specification status ext_texture_compression_rgtc community approved ...
EXT_texture_filter_anisotropic - Web APIs
examples var texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); var ext = ( gl.getextension('ext_texture_filter_anisotropic') || gl.getextension('moz_ext_texture_filter_anisotropic') || gl.getextension('webkit_ext_texture_filter_anisotropic') ); if (ext){ var max = gl.getparameter(ext.max_texture_max_anisotropy_ext); gl.texparameterf(gl.texture_2d, ext.texture_max_anisotropy_ext, max); } specificati...
EffectTiming.fill - Web APIs
WebAPIEffectTimingfill
forwards makes the rabbit retain its last keyframe rather than reverting to its unanimated state: // create a set of keyframes to slide the rabbit down the hole--and keep him down with 'fill'!
Element.computedStyleMap() - Web APIs
'a'); // get the <dl> we'll be populating const styleslist = document.queryselector('#regurgitation'); // retrieve all computed styles with computedstylemap() const allcomputedstyles = myelement.computedstylemap(); // iterate thru the map of all the properties and values, adding a <dt> and <dd> for each for (const [prop, val] of allcomputedstyles) { // properties const cssproperty = document.createelement('dt'); cssproperty.appendchild(document.createtextnode(prop)); styleslist.appendchild(cssproperty); // values const cssvalue = document.createelement('dd'); cssvalue.appendchild(document.createtextnode(val)); styleslist.appendchild(cssvalue); } in browsers that support computedstylemap(), you'll see a list of all the css properties and values.
Element.getBoundingClientRect() - Web APIs
<div></div> div { width: 400px; height: 200px; padding: 20px; margin: 50px auto; background: purple; } let elem = document.queryselector('div'); let rect = elem.getboundingclientrect(); for (var key in rect) { if(typeof rect[key] !== 'function') { let para = document.createelement('p'); para.textcontent = `${ key } : ${ rect[key] }`; document.body.appendchild(para); } } notice how the width/height are equal to the equal to its width/height + padding.
Element.insertAdjacentElement() - Web APIs
example beforebtn.addeventlistener('click', function() { var tempdiv = document.createelement('div'); tempdiv.style.backgroundcolor = randomcolor(); if (activeelem) { activeelem.insertadjacentelement('beforebegin',tempdiv); } setlistener(tempdiv); }); afterbtn.addeventlistener('click', function() { var tempdiv = document.createelement('div'); tempdiv.style.backgroundcolor = randomcolor(); if (activeelem) { activeelem.insertadjacentelement('afterend',tempdiv);...
Element.insertAdjacentText() - Web APIs
note that the existing text node is not added to — further text nodes are created containing the new additions.
Element: mousedown event - Web APIs
when the page loads, constants mypics and context are created to store a reference to the canvas and the 2d context we will use to draw.
Element: mouseenter event - Web APIs
tlistener('mouseenter', e => { mousetarget.style.border = '5px dotted orange'; entereventcount++; addlistitem('this is mouseenter event ' + entereventcount + '.'); }); mousetarget.addeventlistener('mouseleave', e => { mousetarget.style.border = '1px solid #333'; leaveeventcount++; addlistitem('this is mouseleave event ' + leaveeventcount + '.'); }); function addlistitem(text) { // create a new text node using the supplied text var newtextnode = document.createtextnode(text); // create a new li element var newlistitem = document.createelement("li"); // add the text node to the li element newlistitem.appendchild(newtextnode); // add the newly created list item to list unorderedlist.appendchild(newlistitem); } result specifications specification sta...
Element: mouseleave event - Web APIs
tlistener('mouseenter', e => { mousetarget.style.border = '5px dotted orange'; entereventcount++; addlistitem('this is mouseenter event ' + entereventcount + '.'); }); mousetarget.addeventlistener('mouseleave', e => { mousetarget.style.border = '1px solid #333'; leaveeventcount++; addlistitem('this is mouseleave event ' + leaveeventcount + '.'); }); function addlistitem(text) { // create a new text node using the supplied text var newtextnode = document.createtextnode(text); // create a new li element var newlistitem = document.createelement("li"); // add the text node to the li element newlistitem.appendchild(newtextnode); // add the newly created list item to list unorderedlist.appendchild(newlistitem); } result specifications specification sta...
Element: mousemove event - Web APIs
when the page loads, constants mypics and context are created to store a reference to the canvas and the 2d context we will use to draw.
Element: mouseup event - Web APIs
when the page loads, constants mypics and context are created to store a reference to the canvas and the 2d context we will use to draw.
Element.name - Web APIs
WebAPIElementname
type="text" value="foo"> </form> <script type="text/javascript"> // get a reference to the first element in the form let formelement = document.forms['forma'].elements[0] // give it a name formelement.name = 'inputa' // show the value of the input alert(document.forms['forma'].elements['inputa'].value) </script> notes in internet explorer (ie), the name property of dom objects created using document.createelement() can't be set or modified.
Element.namespaceURI - Web APIs
you can create an element with the specified namespaceuri using the dom level 2 method document.createelementns.
Element: paste event - Web APIs
f1; } js const target = document.queryselector('div.target'); target.addeventlistener('paste', (event) => { let paste = (event.clipboarddata || window.clipboarddata).getdata('text'); paste = paste.touppercase(); const selection = window.getselection(); if (!selection.rangecount) return false; selection.deletefromdocument(); selection.getrangeat(0).insertnode(document.createtextnode(paste)); event.preventdefault(); }); result specifications specification status clipboard api and events working draft ...
Element.scrollHeight - Web APIs
"thank you." : "please, scroll and read the following text."; } onload = function () { var otoberead = document.getelementbyid("rules"); checkreading.noticebox = document.createelement("span"); document.registration.accept.checked = false; checkreading.noticebox.id = "notice"; otoberead.parentnode.insertbefore(checkreading.noticebox, otoberead); otoberead.parentnode.insertbefore(document.createelement("br"), otoberead); otoberead.onscroll = checkreading; checkreading.call(otoberead); } specifications specification status comment cs...
Element.shadowRoot - Web APIs
examples the following snippets are taken from our life-cycle-callbacks example (see it live also), which creates an element that displays a square of a size and color specified in the element's attributes.
Element.slot - Web APIs
WebAPIElementslot
examples in our simple-template example (see it live), we create a trivial custom element example called <my-paragraph> in which a shadow root is attached and then populated using the contents of a template that contains a slot named my-text.
Element.tagName - Web APIs
WebAPIElementtagName
example html <span id="born">when i was born...</span> javascript var span = document.getelementbyid("born"); console.log(span.tagname); in xhtml (or any other xml format), the original case will be maintained, so "span" would be output in case the original tag name was created lowercase.
Element: touchcancel event - Web APIs
the touchcancel event is fired when one or more touch points have been disrupted in an implementation-specific manner (for example, too many touch points are created).
ElementCSSInlineStyle - Web APIs
note: elementcssinlinestyle is a mixin and not an interface; you can't actually create an object of type elementcssinlinestyle.
ErrorEvent - Web APIs
constructor errorevent() creates an errorevent event with the given parameters.
Event.cancelable - Web APIs
WebAPIEventcancelable
custom events created by other javascript code control if they can be canceled when they are created.
Event.isTrusted - Web APIs
WebAPIEventisTrusted
the istrusted read-only property of the event interface is a boolean that is true when the event was generated by a user action, and false when the event was created or modified by a script or dispatched via eventtarget.dispatchevent().
Event.msConvertURL() - Web APIs
if (!filelist) { console.log("filelist is null."); return; } for (var i = 0; i < filelist.length; i++) { var file = filelist[i]; var url = url.createobjecturl(file); if (evt.converturl) { // use standard if available.
Event.preventDefault() - Web APIs
it's not an elegant function but does the job for the purposes of this example: var warningtimeout; var warningbox = document.createelement("div"); warningbox.classname = "warning"; function displaywarning(msg) { warningbox.innerhtml = msg; if (document.body.contains(warningbox)) { window.cleartimeout(warningtimeout); } else { // insert warningbox after mytextbox mytextbox.parentnode.insertbefore(warningbox, mytextbox.nextsibling); } warningtimeout = window.settimeout(function() { warningbox.pare...
Event.target - Web APIs
WebAPIEventtarget
// make a list const ul = document.createelement('ul'); document.body.appendchild(ul); const li1 = document.createelement('li'); const li2 = document.createelement('li'); ul.appendchild(li1); ul.appendchild(li2); function hide(evt) { // e.target refers to the clicked <li> element // this is different than e.currenttarget, which would refer to the parent <ul> in this context evt.target.style.visibility = 'hidden'; } // attach the...
EventSource.onmessage - Web APIs
syntax eventsource.onmessage = function examples evtsource.onmessage = function(e) { var newelement = document.createelement("li"); newelement.textcontent = "message: " + e.data; eventlist.appendchild(newelement); } note: you can find a full example on github — see simple sse demo using php.
EventTarget() - Web APIs
the eventtarget() constructor creates a new eventtarget object instance.
EventTarget - Web APIs
nttarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">eventtarget</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor eventtarget() creates a new eventtarget object instance.
ExtendableEvent() - Web APIs
the extendableevent() constructor creates a new extendableevent object.
ExtendableEvent - Web APIs
constructor extendableevent() creates a new extendableevent object.
ExtendableMessageEvent - Web APIs
constructor extendablemessageevent() creates a new extendablemessageevent object instance.
FederatedCredential - Web APIs
the federatedcredential constructor creates a new federatedcredential object.
FederatedCredential - Web APIs
constructor federatedcredential() creates a new federatedcredential object.
FetchEvent() - Web APIs
the fetchevent() constructor creates a new fetchevent object.
File.File() - Web APIs
WebAPIFileFile
the file() constructor creates a new file object instance.
File.webkitRelativePath - Web APIs
html content <input type="file" id="filepicker" name="filelist" webkitdirectory multiple /> <ul id="listing"></ul> javascript content document.getelementbyid("filepicker").addeventlistener("change", function(event) { let output = document.getelementbyid("listing"); let files = event.target.files; for (let i=0; i<files.length; i++) { let item = document.createelement("li"); item.innerhtml = files[i].webkitrelativepath; output.appendchild(item); }; }, false); result specifications specification status comment file and directory entries apithe definition of 'webkitrelativepath' in that specification.
File - Web APIs
WebAPIFile
in particular, filereader, url.createobjecturl(), createimagebitmap(), and xmlhttprequest.send() accept both blobs and files.
FileException - Web APIs
var fileentry = fs.root.getfile('log.txt', {create: true, exclusive:true}0; } catch (e) { onerrror(e); } the sample code was borrowed from html5rocks attribute attribute type description code unsigned short the most appropriate error code for the condition.
FileReader() - Web APIs
the filereader() constructor creates a new filereader.
FileReader.readAsBinaryString() - Web APIs
example var canvas = document.createelement('canvas'); var height = 200; var width = 200; canvas.width = width; canvas.height = height; var ctx = canvas.getcontext('2d'); ctx.strokestyle = '#090'; ctx.beginpath(); ctx.arc(width/2, height/2, width/2 - width/10, 0, math.pi*2); ctx.stroke(); canvas.toblob(function (blob) { var reader = new filereader(); reader.onload = function () { console.log(reader.result); } rea...
FileSystemEntry.fullPath - Web APIs
function gotfilesystem(fs) { let path = ""; fs.root.getfile("data.json", { create: true, exclusive: true }, function(entry) { path = fullpath; }, handleerror(error)); return path; } obviously, this is somewhat contrived, since we know that the file's full path is "/data.json", having just looked it up ourselves, but the concept holds up for scenarios in which you don't know it.
FileSystemEntry.getParent() - Web APIs
you can, however, create a simple helper function to adapt it, like this: function getparentpromise(entry) { return new promise((resolve, reject) => { entry.getparent(resolve, reject); }); } a similar approach can be taken elsewhere in the file and directory entries api.
FileSystemEntrySync - Web APIs
you can delete the file and recreate it, and it's all good.
FocusEvent() - Web APIs
the focusevent() constructor returns a newly created focusevent object with an optional eventtarget.
FocusEvent - Web APIs
usevent" target="_top"><rect x="231" y="1" width="100" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="281" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">focusevent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor focusevent() creates a focusevent event with the given parameters.
FontFace.FontFace() - Web APIs
WebAPIFontFaceFontFace
the fontface() constructor creates a new fontface object.
FontFaceSetLoadEvent.FontFaceSetLoadEvent() - Web APIs
the fontfacesetloadevent constructor creates a new fontfaceloadevent object which is fired whenever a fontfaceset loads.
FontFaceSetLoadEvent - Web APIs
constructor fontfacesetloadevent() creates a new fontfacesetloadevent object.
FormData.append() - Web APIs
WebAPIFormDataappend
example the following line creates an empty formdata object: var formdata = new formdata(); // currently empty you can add key/value pairs to this using formdata.append: formdata.append('username', 'chris'); formdata.append('userpic', myfileinput.files[0], 'chris.jpg'); as with regular form data, you can append multiple values with the same name.
FormData.delete() - Web APIs
WebAPIFormDatadelete
example the following line creates an empty formdata object and prepopulates it with key/value pairs from a form: var formdata = new formdata(myform); you can delete keys and their values using delete(): formdata.delete('username'); specifications specification status comment xmlhttprequestthe definition of 'delete()' in that specification.
FormData.entries() - Web APIs
WebAPIFormDataentries
example // create a test formdata object var formdata = new formdata(); formdata.append('key1', 'value1'); formdata.append('key2', 'value2'); // display the key/value pairs for(var pair of formdata.entries()) { console.log(pair[0]+ ', '+ pair[1]); } the result is: key1, value1 key2, value2 specifications specification status comment xmlhttprequestthe definition of 'entries() (as iterator<>)' in that specification.
FormData.get() - Web APIs
WebAPIFormDataget
example the following line creates an empty formdata object: var formdata = new formdata(); if we add two username values using formdata.append: formdata.append('username', 'chris'); formdata.append('username', 'bob'); the following get() function will only return the first username value appended: formdata.get('username'); // returns "chris" specifications specification status comment xmlhttpreques...
FormData.getAll() - Web APIs
WebAPIFormDatagetAll
example the following line creates an empty formdata object: var formdata = new formdata(); if we add two username values using formdata.append: formdata.append('username', 'chris'); formdata.append('username', 'bob'); the following getall() function will return both username values in an array: formdata.getall('username'); // returns ["chris", "bob"] specifications specification status comment xmlh...
FormData.has() - Web APIs
WebAPIFormDatahas
example the following line creates an empty formdata object: var formdata = new formdata(); the following snippet shows the results of testing for the existence of username in the formdata object, before and after appending a username value to it with formdata.append: formdata.has('username'); // returns false formdata.append('username', 'chris'); formdata.has('username'); // returns true specifications specification status comment xmlhttprequestthe definition...
FormData.keys() - Web APIs
WebAPIFormDatakeys
example // create a test formdata object var formdata = new formdata(); formdata.append('key1', 'value1'); formdata.append('key2', 'value2'); // display the keys for (var key of formdata.keys()) { console.log(key); } the result is: key1 key2 specifications specification status comment xmlhttprequestthe definition of 'keys() (as iterator<>)' in that specification.
FormData.set() - Web APIs
WebAPIFormDataset
example the following line creates an empty formdata object: var formdata = new formdata(); // currently empty you can set key/value pairs on this using formdata.set: formdata.set('username', 'chris'); formdata.set('userpic', myfileinput.files[0], 'chris.jpg'); if the sent value is different than string or blob it will be automatically converted to string: formdata.set('name', 72); formdata.get('name'); // "72" specificatio...
FormData.values() - Web APIs
WebAPIFormDatavalues
example // create a test formdata object var formdata = new formdata(); formdata.append('key1', 'value1'); formdata.append('key2', 'value2'); // display the values for (var value of formdata.values()) { console.log(value); } the result is: value1 value2 specifications specification status comment xmlhttprequestthe definition of 'values() (as iterator<>)' in that specification.
FormData - Web APIs
WebAPIFormData
constructor formdata() creates a new formdata object.
FormDataEvent() - Web APIs
the formdataevent() constructor creates a new formdataevent object instance.
FormDataEvent - Web APIs
constructor formdataevent() creates a new formdataevent object instance.
GamepadEvent() - Web APIs
the gamepadevent() constructor creates a new gamepadevent object.
GamepadHapticActuator.type - Web APIs
syntax var myactuatortype = gamepadhapticactuatorinstance.type; value an enum of type gamepadhapticactuatortype; currently available types are: vibration — vibration hardware, which creates a rumbling effect.
GeolocationCoordinates.longitude - Web APIs
javascript the javascript code below creates an event listener so that when the user clicks on a button, the location information is retrieved and displayed.
GeometryUtils - Web APIs
geometryutils is a raw interface and no object of this type can be created; it is implemented by text, element, csspseudoelement, and document objects.
GestureEvent - Web APIs
constructor gestureevent() creates a gestureevent object.
GlobalEventHandlers.onanimationiteration - Web APIs
example let's create an animation which automatically pauses at the end of each iteration, allowing the user to choose whether or not to start the next iteration.
GlobalEventHandlers.ontransitioncancel - Web APIs
html this simply creates a <div> which we'll style with css below to make into a box that resizes and changes color and such.
GlobalEventHandlers.ontransitionend - Web APIs
html this simply creates a <div> which we'll style with css below to make into a box that resizes and changes color and such.
GlobalEventHandlers - Web APIs
note: globaleventhandlers is a mixin and not an interface; you can't actually create an object of type globaleventhandlers.
Gyroscope.Gyroscope() - Web APIs
the gyroscope constructor creates a new gyroscope object which provides on each reading the angular velocity of the device along all three axes.
Gyroscope - Web APIs
WebAPIGyroscope
constructor gyroscope.gyroscope() creates a new gyroscope object.
HTMLAnchorElement.referrerPolicy - Web APIs
examples var elt = document.createelement("a"); var linktext = document.createtextnode("my link"); elt.appendchild(linktext); elt.href = "https://developer.mozilla.org/"; elt.referrerpolicy = "no-referrer"; var div = document.getelementbyid("divaround"); div.appendchild(elt); // when clicked, the link will not send a referrer header.
HTMLAreaElement.referrerPolicy - Web APIs
examples <img usemap="#maparound" width="100" height="100" src="/img/logo@2x.png" /> <map id="mymap" name="maparound" />> var elt = document.createelement("area"); elt.href = "/img2.png"; elt.shape = "rect"; elt.referrerpolicy = "no-referrer"; elt.coords = "0,0,100,100"; var map = document.getelementbyid("mymap"); map.appendchild(elt); // when clicked, the area's link will not send a referrer header.
HTMLCanvasElement.captureStream() - Web APIs
send it to another computer using an rtcpeerconnection // pc is an rtcpeerconnection created elsewhere pc.addstream(stream); specifications specification status comment media capture from dom elementsthe definition of 'htmlcanvaselement.capturestream()' in that specification.
HTMLCanvasElement.toDataURL() - Web APIs
addeventlistener('load', removecolors); function showcolorimg() { this.style.display = 'none'; this.nextsibling.style.display = 'inline'; } function showgrayimg() { this.previoussibling.style.display = 'inline'; this.style.display = 'none'; } function removecolors() { var aimages = document.getelementsbyclassname('grayscale'), nimgslen = aimages.length, ocanvas = document.createelement('canvas'), octx = ocanvas.getcontext('2d'); for (var nwidth, nheight, oimgdata, ograyimg, npixel, apix, npixlen, nimgid = 0; nimgid < nimgslen; nimgid++) { ocolorimg = aimages[nimgid]; nwidth = ocolorimg.offsetwidth; nheight = ocolorimg.offsetheight; ocanvas.width = nwidth; ocanvas.height = nheight; octx.drawimage(ocolorimg, 0, 0); oimgdata = octx.getima...
HTMLCanvasElement.transferControlToOffscreen() - Web APIs
examples var htmlcanvas = document.createelement('canvas'); var offscreen = htmlcanvas.transfercontroltooffscreen(); var gl = offscreen.getcontext('webgl'); // ...
accessKeyLabel - Web APIs
syntax label = element.accesskeylabel example javascript var node = document.getelementbyid('btn1'); if (node.accesskeylabel) { node.title += ' [' + node.accesskeylabel + ']'; } else { node.title += ' [' + node.accesskey + ']'; } node.onclick = function () { var p = document.createelement('p'); p.textcontent = 'clicked!'; node.parentnode.appendchild(p); }; html <button accesskey="h" title="caption" id="btn1">hover me</button> result specifications specification status comment html living standardthe definition of 'htmlelement.accesskeylabel' in that specification.
HTMLElement.contextMenu - Web APIs
the menu itself is created using the <menu> element.
HTMLElement.hidden - Web APIs
the welcome panel <div id="welcome" class="panel"> <h1>welcome to foobar.com!</h1> <p>by clicking "ok" you agree to be awesome every day!</p> <button class="button" id="okbutton">ok</button> </div> this html creates a panel (in a <div> block) that welcomes the user to a site and tells them what they're agreeing to by clicking the ok button.
HTMLElement.title - Web APIs
WebAPIHTMLElementtitle
syntax var str = element.title; element.title = str; example const link = document.createelement('a'); link.innertext = 'grapes'; link.href = 'https://en.wikipedia.org/wiki/grape'; link.title = 'wikipedia page on grapes'; specifications specification status comment html living standardthe definition of 'title' in that specification.
HTMLElement: transitionstart event - Web APIs
ion.addeventlistener('transitionrun', function() { message.textcontent = 'transitionrun fired'; }); transition.addeventlistener('transitionstart', function() { message.textcontent = 'transitionstart fired'; }); transition.addeventlistener('transitionend', function() { message.textcontent = 'transitionend fired'; }); the difference is that: transitionrun fires when the transition is created (i.e.
HTMLElement - Web APIs
transitionrun fired when a css transition is first created.
HTMLFormElement.method - Web APIs
syntax var string = form.method; form.method = string; example document.forms['myform'].method = 'post'; const formelement = document.createelement("form"); // create a form document.body.appendchild(formelement); console.log(formelement.method); // 'get' specifications specification status comment html living standardthe definition of 'htmlformelement: method' in that specification.
HTMLFormElement.name - Web APIs
internet explorer (ie) does not allow the name attribute of an element created using createelement() to be set or modified using the name property.
HTMLFormElement - Web APIs
examples creating a new form element, modifying its attributes, then submitting it: const f = document.createelement("form"); // create a form document.body.appendchild(f); // add it to the document body f.action = "/cgi-bin/some.cgi"; // add action and method attributes f.method = "post"; f.submit(); // call the form's submit() method extract information from a <form> element and set some of its attributes: <form name="forma" action="/cgi-bin/test" ...
HTMLHyperlinkElementUtils.host - Web APIs
syntax string = object.host; object.host = string; examples var anchor = document.createelement("a"); anchor.href = "https://developer.mozilla.org/htmlhyperlinkelementutils.host" anchor.host == "developer.mozilla.org" anchor.href = "https://developer.mozilla.org:443/htmlhyperlinkelementutils.host" anchor.host == "developer.mozilla.org" // the port number is not included because 443 is the scheme's default port anchor.href = "https://developer.mozilla.org:4097/htmlhyperlinkelementutils.host" anchor.host == "developer.mozilla.org:4097" specifications specification status comment html l...
HTMLIFrameElement.referrerPolicy - Web APIs
examples var iframe = document.createelement("iframe"); iframe.src = "/"; iframe.referrerpolicy = "unsafe-url"; var body = document.getelementsbytagname("body")[0]; body.appendchild(iframe); // fetch the image using the complete url as the referrer specifications specification status comment referrer policythe definition of 'referrerpolicy attribute' in that specification.
HTMLIFrameElement.src - Web APIs
syntax refstr = iframeelt.src; iframeelt.src= refstr; example var iframe = document.createelement("iframe"); iframe.src = "/"; var body = document.getelementsbytagname("body")[0]; body.appendchild(iframe); // fetch the image using the complete url as the referrer specifications specification status comment html living standardthe definition of 'htmliframeelement: src' in that specification.
srcdoc - Web APIs
examples var iframe = document.createelement("iframe"); iframe.srcdoc = `<!doctype html><p>hello world!</p>`; document.body.appendchild(iframe); specifications specification status comment html living standardthe definition of 'htmliframeelement: srcdoc' in that specification.
HTMLIFrameElement - Web APIs
htmliframeelement.frameborder is a domstring that indicates whether to create borders between frames.
HTMLImageElement.alt - Web APIs
html the html below creates a snippet of content from a site using the described icon.
HTMLImageElement.currentSrc - Web APIs
html <img src="/files/16797/clock-demo-400px.png" alt="clock" srcset="/files/16864/clock-demo-200px.png 200w, /files/16797/clock-demo-400px.png 400w" sizes="(max-width: 400px) 50%, 90%"> javascript var clockimage = document.queryselector("img"); let p = document.createelement("p"); if (!clockimage.currentsrc.endswith("200px.png")) { p.innertext = "using the 200px image."; } else { p.innertext = "using the 400px image!"; } document.body.appendchild(p); result specifications specification status comment html living standardthe definition of 'htmlimageelement.currentsrc' in that specification.
HTMLImageElement.loading - Web APIs
function addimagetolist(url) { const list = document.queryselector("div.photo-list"); let newitem = document.createelement("div"); newitem.classname = "photo-item"; let newimg = document.createelement("img"); newimg.loading = "lazy"; newimg.width = 320; newimg.height = 240; newimg.src = url; newitem.appendchild(newimg); list.appendchild(newitem); } specifications specification status comment html living standardthe definition of 'htmlimageelement.loading' in tha...
HTMLImageElement.sizes - Web APIs
example in this example, a blog-like layout is created, displaying some text and an image which for which three size points are specified, depending on the width of the window.
HTMLImageElement.srcset - Web APIs
let box = document.queryselector(".box"); let image = box.queryselector("img"); let newelem = document.createelement("p"); newelem.innerhtml = `image: <code>${image.currentsrc}</code>`; box.appendchild(newelem); result in the displayed output below, the selected url will correspond with whether your display results in selecting the 1x or the 2x version of the image.
HTMLInputElement.webkitEntries - Web APIs
example this example shows how to create a file selection <input> element and process the selected files.
HTMLInputElement.webkitdirectory - Web APIs
html content <input type="file" id="filepicker" name="filelist" webkitdirectory multiple /> <ul id="listing"></ul> javascript content document.getelementbyid("filepicker").addeventlistener("change", function(event) { let output = document.getelementbyid("listing"); let files = event.target.files; for (let i=0; i<files.length; i++) { let item = document.createelement("li"); item.innerhtml = files[i].webkitrelativepath; output.appendchild(item); }; }, false); result specifications specification status comment file and directory entries apithe definition of 'webkitdirectory' in that specification.
HTMLMediaElement: abort event - Web APIs
bubbles no cancelable no interface event event handler property onabort examples const video = document.queryselector('video'); const videosrc = 'https://path/to/video.webm'; video.addeventlistener('abort', () => { console.log(`abort loading: ${videosrc}`); }); const source = document.createelement('source'); source.setattribute('src', videosrc); source.setattribute('type', 'video/webm'); video.appendchild(source); specifications specification status html living standard living standard html5 recommendation ...
HTMLMediaElement.buffered - Web APIs
example var obj = document.createelement('video'); console.log(obj.buffered); // timeranges { length: 0 } specifications specification status comment html living standardthe definition of 'htmlmediaelement.buffered' in that specification.
HTMLMediaElement.canPlayType() - Web APIs
example var obj = document.createelement('video'); console.log(obj.canplaytype('video/mp4')); // "maybe" specifications specification status comment html living standardthe definition of 'canplaytype' in that specification.
HTMLMediaElement.controls - Web APIs
example var obj = document.createelement('video'); obj.controls = true; specifications specification status comment html living standardthe definition of 'htmlmediaelement.controls' in that specification.
HTMLMediaElement.currentSrc - Web APIs
example var obj = document.createelement('video'); console.log(obj.currentsrc); // "" specifications specification status comment html living standardthe definition of 'htmlmediaelement.currentsrc' in that specification.
HTMLMediaElement.currentTime - Web APIs
example var video = document.createelement('video'); console.log(video.currenttime); usage notes reduced time precision to offer protection against timing attacks and fingerprinting, browsers may round or otherwise adjust the value returned by currenttime.
HTMLMediaElement.defaultMuted - Web APIs
example var videoele = document.createelement('video'); videoele.defaultmuted = true; console.log(videoele.outerhtml); // <video muted=""></video> specifications specification status comment html living standardthe definition of 'htmlmediaelement.defaultmuted' in that specification.
HTMLMediaElement.defaultPlaybackRate - Web APIs
example var obj = document.createelement('video'); console.log(obj.defaultplaybackrate); // 1 specifications specification status comment html living standardthe definition of 'htmlmediaelement.defaultplaybackrate' in that specification.
HTMLMediaElement.disableRemotePlayback - Web APIs
(false means "not disabled", which means "enabled") example var obj = document.createelement('audio'); obj.disableremoteplayback = true; specifications specification status comment remote playback apithe definition of 'disableremoteplayback' in that specification.
HTMLMediaElement.duration - Web APIs
examples var obj = document.createelement('video'); console.log(obj.duration); // nan specifications specification status comment html living standardthe definition of 'htmlmediaelement.duration' in that specification.
HTMLMediaElement.ended - Web APIs
example var obj = document.createelement('video'); console.log(obj.ended); // false specifications specification status comment html living standardthe definition of 'htmlmediaelement.ended' in that specification.
HTMLMediaElement.error - Web APIs
var videoelement = document.createelement('video'); videoelement.onerror = function() { console.log("error " + videoelement.error.code + "; details: " + videoelement.error.message); } videoelement.src = "https://example.com/bogusvideo.mp4"; specifications specification status comment html living standardthe definition of 'htmlmediaelement.error' in that specification.
HTMLMediaElement: loadstart event - Web APIs
e}\n`; } video.addeventlistener('loadstart', handleevent); video.addeventlistener('progress', handleevent); video.addeventlistener('canplay', handleevent); video.addeventlistener('canplaythrough', handleevent); loadvideo.addeventlistener('click', () => { if (source) { document.location.reload(); } else { loadvideo.textcontent = "reset example"; source = document.createelement('source'); source.setattribute('src', 'https://interactive-examples.mdn.mozilla.net/media/examples/flower.webm'); source.setattribute('type', 'video/webm'); video.appendchild(source); } }); result specifications specification status html living standardthe definition of 'loadstart media event' in that specification.
HTMLMediaElement.loop - Web APIs
example var obj = document.createelement('video'); obj.loop = true; // true specifications specification status comment html living standardthe definition of 'htmlmediaelement.loop' in that specification.
HTMLMediaElement.muted - Web APIs
example var obj = document.createelement('video'); console.log(obj.muted); // false specifications specification status comment html living standardthe definition of 'htmlmediaelement.muted' in that specification.
HTMLMediaElement.paused - Web APIs
example var obj = document.createelement('video'); console.log(obj.paused); // true specifications specification status comment html living standardthe definition of 'htmlmediaelement.paused' in that specification.
HTMLMediaElement.playbackRate - Web APIs
(default: 1.0) example var obj = document.createelement('video'); console.log(obj.playbackrate); // expected output: 1 specifications specification status comment html living standardthe definition of 'htmlmediaelement.playbackrate' in that specification.
HTMLMediaElement: progress event - Web APIs
e}\n`; } video.addeventlistener('loadstart', handleevent); video.addeventlistener('progress', handleevent); video.addeventlistener('canplay', handleevent); video.addeventlistener('canplaythrough', handleevent); loadvideo.addeventlistener('click', () => { if (source) { document.location.reload(); } else { loadvideo.textcontent = "reset example"; source = document.createelement('source'); source.setattribute('src', 'https://interactive-examples.mdn.mozilla.net/media/examples/flower.webm'); source.setattribute('type', 'video/webm'); video.appendchild(source); } }); result specifications specification status html living standardthe definition of 'progress media event' in that specification.
HTMLMediaElement.setSinkId() - Web APIs
exceptions exception explanation domexception no permission to use the requested device examples const devices = await navigator.mediadevices.enumeratedevices(); const audiodevices = devices.filter(device => device.kind === 'audiooutput'); const audio = document.createelement('audio'); await audio.setsinkid(audiodevices[0].deviceid); console.log('audio is being played on ' + audio.sinkid); specifications specification status comment audio output devices apithe definition of 'sinkid' in that specification.
HTMLMediaElement.src - Web APIs
example var obj = document.createelement('video'); console.log(obj.src); // "" specifications specification status comment html living standardthe definition of 'htmlmediaelement.src' in that specification.
HTMLMediaElement.volume - Web APIs
example var obj = document.createelement('audio'); console.log(obj.volume); // 1 obj.volume = 0.75; specifications specification status comment html living standardthe definition of 'htmlmediaelement.volume' in that specification.
Option() - Web APIs
the option() constructor creates a new htmloptionelement.
HTMLOrForeignElement - Web APIs
note: htmlorforeignelement is a mixin and not an interface; you can't actually create an object of type htmlorforeignelement.
HTMLScriptElement.referrerPolicy - Web APIs
examples var scriptelem = document.createelement("script"); scriptelem.src = "/"; scriptelem.referrerpolicy = "unsafe-url"; document.body.appendchild(script); specifications specification status comment referrer policythe definition of 'referrerpolicy attribute' in that specification.
HTMLSelectElement.selectedOptions - Web APIs
html the html that creates the selection box and the <option> elements representing each of the food choices looks like this: <label for="foods">what do you want to eat?</label><br> <select id="foods" name="foods" size="7" multiple> <option value="1">burrito</option> <option value="2">cheeseburger</option> <option value="3">double bacon burger supreme</option> <option value="4">pepperoni pizza</option> <option ...
HTMLTableRowElement.rowIndex - Web APIs
> <tr><th>item</th> <th>price</th></tr> </thead> <tbody> <tr><td>bananas</td> <td>$2</td></tr> <tr><td>oranges</td> <td>$8</td></tr> <tr><td>top sirloin</td> <td>$20</td></tr> </tbody> <tfoot> <tr><td>total</td> <td>$30</td></tr> </tfoot> </table> javascript let rows = document.queryselectorall('tr'); rows.foreach((row) => { let z = document.createelement("td"); z.textcontent = `(row #${row.rowindex})`; row.appendchild(z); }); result ...
HTMLTextAreaElement - Web APIs
</textarea></p> </form> maximum length and number of lines example create a textarea with a maximum number of characters per line and a maximum number of lines: first, create a function that takes the text field and a key event as input and determines if any of the limits have been reached.
HTMLVideoElement.getVideoPlaybackQuality() - Web APIs
the htmlvideoelement method getvideoplaybackquality() creates and returns a videoplaybackquality object containing metrics including how many frames have been lost.
HTMLVideoElement.videoHeight - Web APIs
example this example creates a handler for the resize event that resizes the <video> element to match the intrinsic size of its contents.
HTMLVideoElement.videoWidth - Web APIs
example this example creates a handler for the resize event that resizes the <video> element to match the intrinsic size of its contents.
Headers.entries() - Web APIs
WebAPIHeadersentries
example // create a test headers object var myheaders = new headers(); myheaders.append('content-type', 'text/xml'); myheaders.append('vary', 'accept-language'); // display the key/value pairs for (var pair of myheaders.entries()) { console.log(pair[0]+ ': '+ pair[1]); } the result is: content-type: text/xml vary: accept-language ...
Headers.keys() - Web APIs
WebAPIHeaderskeys
example // create a test headers object var myheaders = new headers(); myheaders.append('content-type', 'text/xml'); myheaders.append('vary', 'accept-language'); // display the keys for(var key of myheaders.keys()) { console.log(key); } the result is: content-type vary ...
Headers.set() - Web APIs
WebAPIHeadersset
example creating an empty headers object is simple: var myheaders = new headers(); // currently empty you could add a header to this using headers.append, then set a new value for this header using set(): myheaders.append('content-type', 'image/jpeg'); myheaders.set('content-type', 'text/html'); if the specified header does not already exist, set() will create it and set its value to the specified value.
Headers.values() - Web APIs
WebAPIHeadersvalues
example // create a test headers object var myheaders = new headers(); myheaders.append('content-type', 'text/xml'); myheaders.append('vary', 'accept-language'); // display the values for (var value of myheaders.values()) { console.log(value); } the result is: text/xml accept-language ...
History.forward() - Web APIs
WebAPIHistoryforward
syntax history.forward() examples the following examples create a button that moves forward one step in the session history.
IDBCursor.request - Web APIs
WebAPIIDBCursorrequest
for example: function displaydata() { list.innerhtml = ''; var transaction = db.transaction(['rushalbumlist'], 'readonly'); var objectstore = transaction.objectstore('rushalbumlist'); var request = objectstore.opencursor(); request.onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listitem = document.createelement('li'); listitem.innerhtml = '<strong>' + cursor.value.albumtitle + '</strong>, ' + cursor.value.year; list.appendchild(listitem); console.log(cursor.request); cursor.continue(); } else { console.log('entries all displayed.'); } }; }; specification specification status comment indexed database api draftthe defin...
IDBDatabase.version - Web APIs
when a database is first created, this attribute is an empty string.
IDBDatabaseException - Web APIs
for example, an object, such as an object store or index, already exists and a request attempted to create a new one.
IDBEnvironment - Web APIs
example the following code creates a request for a database to be opened asychronously, after which the database is opened when the request's onsuccess handler is fired: var db; function opendb() { var dbopenrequest = window.indexeddb.open("todolist"); dbopenrequest.onsuccess = function(e) { db = dbopenrequest.result; }; } browser compatibility the compatibility table on this page is generated from structured data.
IDBFactory.open() - Web APIs
WebAPIIDBFactoryopen
if the version is not provided and the database does not exist, then it will be created with version 1.
IDBFactory - Web APIs
you open — that is, create and access — and delete a database with this object, and not directly with idbfactory.
IDBFactorySync - Web APIs
if there is already a database with the specified name, it uses that one; otherwise, it creates the database using the specified name and description.
IDBIndex.count() - Web APIs
WebAPIIDBIndexcount
ion(['contactslist'], 'readonly'); var objectstore = transaction.objectstore('contactslist'); var myindex = objectstore.index('lname'); var countrequest = myindex.count(); countrequest.onsuccess = function() { console.log(countrequest.result); } myindex.opencursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var tablerow = document.createelement('tr'); tablerow.innerhtml = '<td>' + cursor.value.id + '</td>' + '<td>' + cursor.value.lname + '</td>' + '<td>' + cursor.value.fname + '</td>' + '<td>' + cursor.value.jtitle + '</td>' + '<td>' + cursor.value.company + '</td>' + '<td>' + cursor.value...
IDBIndex.getKey() - Web APIs
WebAPIIDBIndexgetKey
tslist'], 'readonly'); var objectstore = transaction.objectstore('contactslist'); var myindex = objectstore.index('lname'); var getkeyrequest = myindex.getkey('bungle'); getkeyrequest.onsuccess = function() { console.log(getkeyrequest.result); } myindex.opencursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var tablerow = document.createelement('tr'); tablerow.innerhtml = '<td>' + cursor.value.id + '</td>' + '<td>' + cursor.value.lname + '</td>' + '<td>' + cursor.value.fname + '</td>' + '<td>' + cursor.value.jtitle + '</td>' + '<td>' + cursor.value.company + '</td>' + '<td>' + cursor.value...
IDBIndex.keyPath - Web APIs
WebAPIIDBIndexkeyPath
tion displaydatabyindex() { tableentry.innerhtml = ''; var transaction = db.transaction(['contactslist'], 'readonly'); var objectstore = transaction.objectstore('contactslist'); var myindex = objectstore.index('lname'); console.log(myindex.keypath); myindex.opencursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var tablerow = document.createelement('tr'); tablerow.innerhtml = '<td>' + cursor.value.id + '</td>' + '<td>' + cursor.value.lname + '</td>' + '<td>' + cursor.value.fname + '</td>' + '<td>' + cursor.value.jtitle + '</td>' + '<td>' + cursor.value.company + '</td>' + '<td>' + cursor.value...
IDBIndex.name - Web APIs
WebAPIIDBIndexname
unction displaydatabyindex() { tableentry.innerhtml = ''; var transaction = db.transaction(['contactslist'], 'readonly'); var objectstore = transaction.objectstore('contactslist'); var myindex = objectstore.index('lname'); console.log(myindex.name); myindex.opencursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var tablerow = document.createelement('tr'); tablerow.innerhtml = '<td>' + cursor.value.id + '</td>' + '<td>' + cursor.value.lname + '</td>' + '<td>' + cursor.value.fname + '</td>' + '<td>' + cursor.value.jtitle + '</td>' + '<td>' + cursor.value.company + '</td>' + '<td>' + cursor.value...
IDBIndex.objectStore - Web APIs
displaydatabyindex() { tableentry.innerhtml = ''; var transaction = db.transaction(['contactslist'], 'readonly'); var objectstore = transaction.objectstore('contactslist'); var myindex = objectstore.index('lname'); console.log(myindex.objectstore); myindex.opencursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var tablerow = document.createelement('tr'); tablerow.innerhtml = '<td>' + cursor.value.id + '</td>' + '<td>' + cursor.value.lname + '</td>' + '<td>' + cursor.value.fname + '</td>' + '<td>' + cursor.value.jtitle + '</td>' + '<td>' + cursor.value.company + '</td>' + '<td>' + cursor.value...
IDBKeyRange.lower - Web APIs
WebAPIIDBKeyRangelower
nction displaydata() { var keyrangevalue = idbkeyrange.bound("f", "w", true, true); console.log(keyrangevalue.lower); var transaction = db.transaction(['fthings'], 'readonly'); var objectstore = transaction.objectstore('fthings'); objectstore.opencursor(keyrangevalue).onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listitem = document.createelement('li'); listitem.innerhtml = '<strong>' + cursor.value.fthing + '</strong>, ' + cursor.value.frating; list.appendchild(listitem); cursor.continue(); } else { console.log('entries all displayed.'); } }; }; specification specification status comment indexed database api 2.0the definition of 'lower' in that specifi...
IDBKeyRange.lowerOpen - Web APIs
on displaydata() { var keyrangevalue = idbkeyrange.bound("f", "w", true, true); console.log(keyrangevalue.loweropen); var transaction = db.transaction(['fthings'], 'readonly'); var objectstore = transaction.objectstore('fthings'); objectstore.opencursor(keyrangevalue).onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listitem = document.createelement('li'); listitem.innerhtml = '<strong>' + cursor.value.fthing + '</strong>, ' + cursor.value.frating; list.appendchild(listitem); cursor.continue(); } else { console.log('entries all displayed.'); } }; }; specification specification status comment indexed database api 2.0the definition of 'loweropen' in that specif...
IDBKeyRange.upper - Web APIs
WebAPIIDBKeyRangeupper
nction displaydata() { var keyrangevalue = idbkeyrange.bound("f", "w", true, true); console.log(keyrangevalue.upper); var transaction = db.transaction(['fthings'], 'readonly'); var objectstore = transaction.objectstore('fthings'); objectstore.opencursor(keyrangevalue).onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listitem = document.createelement('li'); listitem.innerhtml = '<strong>' + cursor.value.fthing + '</strong>, ' + cursor.value.frating; list.appendchild(listitem); cursor.continue(); } else { console.log('entries all displayed.'); } }; }; specification specification status comment indexed database api 2.0the definition of 'upper' in that specifi...
IDBKeyRange.upperOpen - Web APIs
on displaydata() { var keyrangevalue = idbkeyrange.bound("f", "w", true, true); console.log(keyrangevalue.upperopen); var transaction = db.transaction(['fthings'], 'readonly'); var objectstore = transaction.objectstore('fthings'); objectstore.opencursor(keyrangevalue).onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listitem = document.createelement('li'); listitem.innerhtml = '<strong>' + cursor.value.fthing + '</strong>, ' + cursor.value.frating; list.appendchild(listitem); cursor.continue(); } else { console.log('entries all displayed.'); } }; }; specification specification status comment indexed database api 2.0the definition of 'upperopen' in that spe...
IDBMutableFile - Web APIs
note: this interface used to be called filehandle , but it was changed to this (bug 1006485.) as idbmutablefile objects are bound to a fake file system built on top of indexeddb, such an object is created using the idbdatabase.createmutablefile method.
IDBObjectStore.count() - Web APIs
example in this simple fragment we create a transaction, retrieve an object store, then count the number of records in the store using count() — when the success handler fires, we log the count value (an integer) to the console.
IDBObjectStore.delete() - Web APIs
r transaction = db.transaction(["todolist"], "readwrite"); // report on the success of the transaction completing, when everything is done transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error: ' + transaction.error + '</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // make a request to delete the specified record out of the object store var objectstorerequest = objectstore.delete("walk dog"); objectstorerequest.onsuccess = function(event) { // report the success of our request note.innerhtml += '<li>request successful.</li>'; }; }; specification ...
IDBObjectStore.getAll() - Web APIs
if a value is successfully found, then a structured clone of it is created and set as the result of the request object.
IDBObjectStore.getAllKeys() - Web APIs
if a value is successfully found, then a structured clone of it is created and set as the result of the request object.
IDBObjectStore.getKey() - Web APIs
if a key is successfully found, then a structured clone of it is created and set as the result of the request object.
IDBObjectStore.index() - Web APIs
po (view the example live.) function displaydatabyindex() { tableentry.innerhtml = ''; var transaction = db.transaction(['contactslist'], 'readonly'); var objectstore = transaction.objectstore('contactslist'); var myindex = objectstore.index('lname'); myindex.opencursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var tablerow = document.createelement('tr'); tablerow.innerhtml = '<td>' + cursor.value.id + '</td>' + '<td>' + cursor.value.lname + '</td>' + '<td>' + cursor.value.fname + '</td>' + '<td>' + cursor.value.jtitle + '</td>' + '<td>' + cursor.value.company + '</td>' + '<td>' + cursor.value...
IDBObjectStore.openCursor() - Web APIs
example in this simple fragment we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store: var transaction = db.transaction("name", "readonly"); var objectstore = transaction.objectstore("name"); var request = objectstore.opencursor(); request.onsuccess = function(event) { var cursor = event.target.result; if(cursor) { // cursor.value contains the current record b...
IDBObjectStore.openKeyCursor() - Web APIs
example in this simple fragment we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store: var transaction = db.transaction("name", "readonly"); var objectstore = transaction.objectstore("name"); var request = objectstore.openkeycursor(); request.onsuccess = function(event) { var cursor = event.target.result; if(cursor) { // cursor.key contains the key of the curr...
IDBRequest.error - Web APIs
WebAPIIDBRequesterror
db.transaction(['todolist'], "readwrite").objectstore('todolist'); // get the do-do list with the specified title var objectstoretitlerequest = objectstore.get(title); objectstoretitlerequest.onsuccess = function() { // grab the data object returned as the result var data = objectstoretitlerequest.result; // update the notified value in the object to "yes" data.notified = "yes"; // create another request that inserts the item // back into the database var updatetitlerequest = objectstore.put(data); // when this new request succeeds, run the displaydata() // function again to update the display updatetitlerequest.onsuccess = function() { displaydata(); }; }; objectstoretitlerequest.onerror = function() { // if an error occurs with the request, log what it is c...
IDBRequest.onerror - Web APIs
['todolist'], "readwrite").objectstore('todolist'); // get the to-do list object that has this title as it's title var objectstoretitlerequest = objectstore.get(title); objectstoretitlerequest.onsuccess = function() { // grab the data object returned as the result var data = objectstoretitlerequest.result; // update the notified value in the object to "yes" data.notified = "yes"; // create another request that inserts the item back // into the database var updatetitlerequest = objectstore.put(data); // when this new request succeeds, run the displaydata() // function again to update the display updatetitlerequest.onsuccess = function() { displaydata(); }; }; objectstoretitlerequest.onerror = function() { // if an error occurs with the request, log what it is c...
IDBRequest.onsuccess - Web APIs
['todolist'], "readwrite").objectstore('todolist'); // get the to-do list object that has this title as it's title var objectstoretitlerequest = objectstore.get(title); objectstoretitlerequest.onsuccess = function() { // grab the data object returned as the result var data = objectstoretitlerequest.result; // update the notified value in the object to "yes" data.notified = "yes"; // create another request that inserts the item back // into the database var updatetitlerequest = objectstore.put(data); // when this new request succeeds, run the displaydata() // function again to update the display updatetitlerequest.onsuccess = function() { displaydata(); }; }; specifications specification status comment indexed database api 2.0the definition...
IDBRequest.readyState - Web APIs
['todolist'], "readwrite").objectstore('todolist'); // get the to-do list object that has this title as it's title var objectstoretitlerequest = objectstore.get(title); objectstoretitlerequest.onsuccess = function() { // grab the data object returned as the result var data = objectstoretitlerequest.result; // update the notified value in the object to "yes" data.notified = "yes"; // create another request that inserts the item // back into the database var updatetitlerequest = objectstore.put(data); // log the source of this request console.log("the readystate of this request is " + updatetitlerequest.readystate); // when this new request succeeds, run the displaydata() // function again to update the display updatetitlerequest.onsuccess = function() { displayda...
IDBRequest.result - Web APIs
WebAPIIDBRequestresult
['todolist'], "readwrite").objectstore('todolist'); // get the to-do list object that has this title as it's title var objectstoretitlerequest = objectstore.get(title); objectstoretitlerequest.onsuccess = function() { // grab the data object returned as the result var data = objectstoretitlerequest.result; // update the notified value in the object to "yes" data.notified = "yes"; // create another request that inserts the item // back into the database var updatetitlerequest = objectstore.put(data); // when this new request succeeds, run the displaydata() // function again to update the display updatetitlerequest.onsuccess = function() { displaydata(); }; }; specifications specification status comment indexed database api 2.0the definition...
IDBRequest.source - Web APIs
WebAPIIDBRequestsource
(['todolist'], "readwrite").objectstore('todolist'); // get the to-do list object that has this title as its title var objectstoretitlerequest = objectstore.get(title); objectstoretitlerequest.onsuccess = function() { // grab the data object returned as the result var data = objectstoretitlerequest.result; // update the notified value in the object to "yes" data.notified = "yes"; // create another request that inserts the item // back into the database var updatetitlerequest = objectstore.put(data); // log the source of this request console.log("the source of this request is " + updatetitlerequest.source); // when this new request succeeds, run the displaydata() // function again to update the display updatetitlerequest.onsuccess = function() { displaydata(); }; }; ...
IDBTransaction.commit() - Web APIs
duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("myobjstore"); // add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of the request (this does not mean the item // has been stored successfully in the db - for that you need transaction.onsuccess) ...
IDBVersionChangeEvent.oldVersion - Web APIs
example var dbname = "sampledb"; var dbversion = 2; var request = indexeddb.open(dbname, dbversion); request.onupgradeneeded = function(e) { var db = request.result; if (e.oldversion < 1) { db.createobjectstore("store1"); } if (e.oldversion < 2) { db.deleteobjectstore("store1"); db.createobjectstore("store2"); } // etc.
IDBVersionChangeRequest.setVersion() - Web APIs
the new way is to define the version in the idbdatabase.open() method and create and delete object stores in the onupgradeneeded event handler associated with the returned request.
IIRFilterNode() - Web APIs
the iirfilternode() constructor of the web audio api creates a new iirfilternode object which an audionode processor which implements a general infinite impulse response filter.
ImageBitmap - Web APIs
it can be created from a variety of source objects using the createimagebitmap() factory method.
ImageCapture() constructor - Web APIs
the imagecapture() constructor creates a new imagecapture object.
ImageCapture.getPhotoCapabilities() - Web APIs
this example also shows how the imagecapture object is created using a mediastreamtrack retrieved from a device's mediastream.
ImageCapture.getPhotoSettings() - Web APIs
this example also shows how the imagecapture object is created using a mediastreamtrack retrieved from a device's mediastream.
ImageCapture.takePhoto() - Web APIs
var takephotobutton = document.queryselector('button#takephoto'); var canvas = document.queryselector('canvas'); takephotobutton.onclick = takephoto; function takephoto() { imagecapture.takephoto().then(function(blob) { console.log('took photo:', blob); img.classlist.remove('hidden'); img.src = url.createobjecturl(blob); }).catch(function(error) { console.log('takephoto() error: ', error); }); } specifications specification status comment mediastream image capturethe definition of 'takephoto()' in that specification.
ImageData.height - Web APIs
WebAPIImageDataheight
syntax imagedata.height example this example creates an imagedata object that is 200 pixels wide and 100 pixels tall.
ImageData.width - Web APIs
WebAPIImageDatawidth
syntax imagedata.width example this example creates an imagedata object that is 200 pixels wide and 100 pixels tall.
InputDeviceCapabilities - Web APIs
the inputdevicecapabilities() constructor creates a new inputdevicecapabilities object provides information about the physical device responsible for generating a touch event.
InputDeviceCapabilities - Web APIs
constructors inputdevicecapabilities.inputdevicecapabilities() creates an inputdevicecapabilities object.
InputEvent() - Web APIs
the inputevent() constructor creates a new inputevent.
InputEvent - Web APIs
utevent" target="_top"><rect x="231" y="1" width="100" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="281" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">inputevent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor inputevent() creates an inputevent object.
InstallEvent.InstallEvent() - Web APIs
the installevent() constructor creates a new installevent object.
InstallEvent - Web APIs
_top"><rect x="306" y="1" width="120" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="366" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">installevent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor installevent.installevent() creates a new installevent object.
IntersectionObserver.unobserve() - Web APIs
example this snippet simply shows an observer being created, an element being observed, and then being unobserved.
IntersectionObserverEntry.time - Web APIs
the intersectionobserverentry interface's read-only time property is a domhighrestimestamp that indicates the time at which the intersection change occurred relative to the time at which the document was created.
KeyboardEvent() - Web APIs
the keyboardevent() constructor creates a new keyboardevent.
KeyboardEvent: code values - Web APIs
so, following table is created from source code which maps from scancode to code value.
KeyboardEvent.code - Web APIs
press keys on the keyboard to see what the keyboardevent's key and code values are for each one.</p> <div id="output"> </div> css #output { font-family: arial, helvetica, sans-serif; border: 1px solid black; } javascript window.addeventlistener("keydown", function(event) { let str = "keyboardevent: key='" + event.key + "' | code='" + event.code + "'"; let el = document.createelement("span"); el.innerhtml = str + "<br/>"; document.getelementbyid("output").appendchild(el); }, true); try it out to ensure that keystrokes go to the sample, click in the output box below before pressing keys.
Key Values - Web APIs
appcommand_close gdk_key_close (0x1008ff56) qt::key_close (0x010000ce) keycode_media_close (128) "new" [1] creates a new document or message.
LargestContentfulPaint - Web APIs
examples the following example shows how to create a performanceobserver that listens for largest-contentful-paint entries and logs the lcp value to the console.
LinearAccelerationSensor.LinearAccelerationSensor() - Web APIs
the linearaccelerationsensor constructor creates a new linearaccelerationsensor object which provides on each reading the acceleration applied to the device along all three axes, but without the contribution of gravity.
LinearAccelerationSensor - Web APIs
constructor linearaccelerationsensor.linearaccelerationsensor() creates a new linearaccelerationsensor object.
LinkStyle - Web APIs
WebAPILinkStyle
linkstyle is a raw interface and no object of this type can be created; it is implemented by htmllinkelement and htmlstyleelement objects.
LocalFileSystemSync - Web APIs
calling window.requestfilesystemsync() for creates new storage for your web app.
Location: host - Web APIs
WebAPILocationhost
syntax string = object.host; object.host = string; examples var anchor = document.createelement("a"); anchor.href = "https://developer.mozilla.org/location.host" anchor.host == "developer.mozilla.org" anchor.href = "https://developer.mozilla.org:443/location.host" anchor.host == "developer.mozilla.org" // the port number is not included because 443 is the scheme's default port anchor.href = "https://developer.mozilla.org:4097/location.host" anchor.host == "developer.mozilla.org:4097" specifications specification status comment html living standardthe definition of 'host' in that spec...
Location - Web APIs
WebAPILocation
examples // create anchor element and use href property for the purpose of this example // a more correct alternative is to browse to the url and use document.location or window.location var url = document.createelement('a'); url.href = 'https://developer.mozilla.org:8080/search?q=url#search-results-close-container'; console.log(url.href); // https://developer.mozilla.org:8080/search?q=url#search-results-close...
LockManager.request() - Web APIs
options optional an object describing characteristics of the lock you want to create.
MIDIConnectionEvent - Web APIs
constructor midiconnectionevent.midiconnectionevent creates a new midiconnectionevent object.
MIDIMessageEvent - Web APIs
constructor midimessageevent.midimessageevent creates a new midimessageevent object instance.
MSGestureEvent - Web APIs
constructor msgestureevent() creates an msgestureevent object.
MSManipulationEvent - Web APIs
methods msmanipulationevent.initmsmanipulationevent(): used to create a manipulation event that can be called from javascript.
Magnetometer.Magnetometer() - Web APIs
the magnetometer constructor creates a new magnetometer object which returns information about the magnetic field as detected by a device’s primary magnetometer sensor.
Magnetometer - Web APIs
constructor magnetometer.magnetometer() creates a new magnetometer object.
MediaCapabilities.decodingInfo() - Web APIs
example //create media configuration to be tested const mediaconfig = { type : 'file', // or 'media-source' audio : { contenttype : "audio/ogg", // valid content type channels : 2, // audio channels used by the track bitrate : 132700, // number of bits used to encode 1s of audio samplerate : 5200 // number of audio samples making up that 1s.
MediaCapabilities.encodingInfo() - Web APIs
example //create media configuration to be tested const mediaconfig = { type : 'record', // or 'transmission' video : { contenttype : "video/webm;codecs=vp8.0", // valid content type width : 1920, // width of the video height : 1080, // height of the video bitrate : 120000, // number of bits used to encode 1s of video framerate : 48 // number of frames maki...
MediaConfiguration - Web APIs
example //create a video configuration to be tested const videodecoderconfig = { type : 'file', // 'record', 'transmission', or 'media-source' video : { contenttype : "video/webm;codecs=vp8", // valid content type width : 800, // width of the video height : 600, // height of the video bitrate : 10000, // number of bits used to encode 1s of video framerate : 30 // number of frames ...
MediaDecodingConfiguration - Web APIs
examples //create media configuration to be tested const mediaconfig = { type : 'file', // or 'media-source' video : { contenttype : "video/webm;codecs=vp8", // valid content type width : 800, // width of the video height : 600, // height of the video bitrate : 10000, // number of bits used to encode 1s of video framerate : 30 // number of frames making up t...
MediaDevices.getDisplayMedia() - Web APIs
example in the example below, a startcapture() method is created which initiates screen capture given a set of options specified by the displaymediaoptions parameter.
MediaDevices.getSupportedConstraints() - Web APIs
s are supported by your browser:</p> <ul id="constraintlist"> </ul> css body { font: 15px arial, sans-serif; } javascript let constraintlist = document.getelementbyid("constraintlist"); let supportedconstraints = navigator.mediadevices.getsupportedconstraints(); for (let constraint in supportedconstraints) { if (supportedconstraints.hasownproperty(constraint)) { let elem = document.createelement("li"); elem.innerhtml = "<code>" + constraint + "</code>"; constraintlist.appendchild(elem); } } result specifications specification status comment media capture and streamsthe definition of 'getsupportedconstraints()' in that specification.
MediaDevices.getUserMedia() - Web APIs
video.src = window.url.createobjecturl(stream); } video.onloadedmetadata = function(e) { video.play(); }; }) .catch(function(err) { console.log(err.name + ": " + err.message); }); frame rate lower frame-rates may be desirable in some cases, like webrtc transmissions with bandwidth restrictions.
MediaElementAudioSourceNode.mediaElement - Web APIs
this stream was specified when the node was first created, either using the mediaelementaudiosourcenode() constructor or the audiocontext.createmediaelementsource() method.
MediaEncodingConfiguration - Web APIs
examples //create media configuration to be tested const mediaconfig = { type : 'record', // or 'transmission' video : { contenttype : "video/webm;codecs=vp8", // valid content type width : 800, // width of the video height : 600, // height of the video bitrate : 10000, // number of bits used to encode 1s of video framerate : 30 // number of frames making up...
MediaKeyMessageEvent() - Web APIs
the mediakeymessageevent constructor creates a new mediakeymessageevent object which creates a new instance of mediakeymessageevent.
MediaKeyMessageEvent - Web APIs
p"><rect x="116" y="1" width="200" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="216" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">mediakeymessageevent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor mediakeymessageevent() creates a new instance of mediakeymessageevent.
MediaKeySystemAccess - Web APIs
methods mediakeysystemaccess.createmediakeys() returns a promise that resolves to a new mediakeys object.
MediaKeys - Web APIs
WebAPIMediaKeys
methods mediakeys.createsession() returns a new mediakeysession object, which represents a context for message exchange with a content decryption module (cdm).
MediaMetadata - Web APIs
constructor mediametadata.mediametadata() creates a new mediametadata object.
MediaQueryListEvent.MediaQueryListEvent() - Web APIs
the mediaquerylistevent constructor creates a new mediaquerylistevent instance.
MediaQueryListEvent - Web APIs
constructor mediaquerylistevent() creates a new mediaquerylistevent instance.
MediaRecorder.onstop - Web APIs
mediarecorder.onstop = 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); } ...
MediaRecorder.requestData() - Web APIs
raise a dataavailable event containing a blob of the currently captured data (the blob is available under the event's data attribute.) create a new blob and place subsequently captured data into it.
MediaRecorderErrorEvent - Web APIs
constructor mediastreamrecorderevent() creates and returns a new mediarecordererrorevent event object with the given parameters.
MediaSession.metadata - Web APIs
example the following example creates a new media session and assigns action handlers to it: if ('mediasession' in navigator){ navigator.mediasession.metadata = new mediametadata({ title: "podcast episode title", artist: "podcast host", album: "podcast name", artwork: [{src: "podcast.jpg"}] }); navigator.mediasession.setactionhandler('play', function() {}); navigator.mediasession.setactionhandler('pause', fu...
MediaSession - Web APIs
examples the following example creates a new media session and assigns action handlers to it: if ('mediasession' in navigator){ navigator.mediasession.metadata = new mediametadata({ title: "podcast episode title", artist: "podcast host", album: "podcast name", artwork: [{src: "podcast.jpg"}] }); navigator.mediasession.setactionhandler('play', function() {}); navigator.mediasession.setactionhandler('pause', fu...
MediaSource.MediaSource() - Web APIs
document.queryselector('video'); var asseturl = 'frag_bunny.mp4'; // need to be specific for blink regarding codecs // ./mp4info frag_bunny.mp4 | grep codec var mimecodec = 'video/mp4; codecs="avc1.42e01e, mp4a.40.2"'; if ('mediasource' in window && mediasource.istypesupported(mimecodec)) { var mediasource = new mediasource; //console.log(mediasource.readystate); // closed video.src = url.createobjecturl(mediasource); mediasource.addeventlistener('sourceopen', sourceopen); } else { console.error('unsupported mime type or codec: ', mimecodec); } ...
MediaSource.readyState - Web APIs
example the following snippet is from a simple example written by nick desaulniers (view the full demo live, or download the source for further investigation.) if ('mediasource' in window && mediasource.istypesupported(mimecodec)) { var mediasource = new mediasource; //console.log(mediasource.readystate); // closed video.src = url.createobjecturl(mediasource); mediasource.addeventlistener('sourceopen', sourceopen); } else { console.error('unsupported mime type or codec: ', mimecodec); } function sourceopen (_) { //console.log(this.readystate); // open var mediasource = this; var sourcebuffer = mediasource.addsourcebuffer(mimecodec); fetchab(asseturl, function (buf) { sourcebuffer.addeventlistener('updateend', fun...
MediaStream.clone() - Web APIs
WebAPIMediaStreamclone
the clone() method of the mediastream interface creates a duplicate of the mediastream.
MediaStream.onaddtrack - Web APIs
stream.onaddtrack = function(event) { let tracklist = document.getelementbyid("tracks"); let label = document.createelement("li"); label.innerhtml = event.track.kind + ": " + event.track.label; tracklist.appendchild(label); }; specifications specification status comment media capture and streamsthe definition of 'mediastream.onaddtrack' in that specification.
MediaStream.onremovetrack - Web APIs
stream.onremovetrack = function(event) { let tracklist = document.getelementbyid("tracks"); let label = document.createelement("li"); label.innerhtml = "removed: " + event.track.kind + ": " + event.track.label; tracklist.appendchild(label); }; specifications specification status comment media capture and streamsthe definition of 'mediastream.onremovetrack' in that specification.
MediaStreamAudioDestinationNode.MediaStreamAudioDestinationNode() - Web APIs
the mediastreamaudiodestinationnode() constructor of the web audio api creates a new mediastreamaudiodestinationnode object instance.
MediaStreamAudioDestinationNode.stream - Web APIs
syntax var audioctx = new audiocontext(); var destination = audioctx.createmediastreamdestination(); var mystream = destination.stream; value a mediastream.
MediaStreamAudioSourceNode.mediaStream - Web APIs
this stream was specified when the node was first created, either using the mediastreamaudiosourcenode() constructor or the audiocontext.createmediastreamsource() method.
MediaStreamAudioSourceOptions - Web APIs
it is not needed when using the audiocontext.createmediastreamsource() method.
MediaStreamEvent() - Web APIs
the mediastreamevent() constructor creates a new mediastreamevent.
MediaStreamTrack.clone() - Web APIs
the clone() method of the mediastreamtrack interface creates a duplicate of the mediastreamtrack.
MediaStreamTrack.enabled - Web APIs
"&#x25b6;&#xfe0f;" : "&#x23f8;&#xfe0f;"; myaudiotrack.enabled = newstate; } this creates a variable, newstate, which is the opposite of the current value of enabled, then uses that to select either the emoji character for the "play" icon or the character for the "pause" icon as the new innerhtml of the pause button's element.
MediaStreamTrack.onunmute - Web APIs
example this example creates an unmute event handler which changes the state of a visual indicator to display the emoji character representing a "speaker" icon.
MediaStreamTrackAudioSourceOptions - Web APIs
it isn't needed when using the audiocontext.createmediastreamtracksource() method.
MediaStreamTrackEvent() - Web APIs
the mediastreamtrackevent() constructor returns a newly created mediastreamtrackevent object, which represents an event announcing that a mediastreamtrack has been added to or removed from a mediastream.
MediaTrackConstraints.cursor - Web APIs
usage notes you can check the setting selected by the user agent after the display media has been created by getdisplaymedia() by calling getsettings() on the display media's video mediastreamtrack, then checking the value of the returned mediatracksettings object's cursor object.
MediaTrackConstraints.displaySurface - Web APIs
usage notes you can check the setting selected by the user agent after the display media has been created by getdisplaymedia() by calling getsettings() on the display media's video mediastreamtrack, then checking the value of the returned mediatracksettings object's displaysurface object.
MediaTrackConstraints.logicalSurface - Web APIs
usage notes you can check the setting selected by the user agent after the display media has been created by getdisplaymedia() by calling getsettings() on the display media's video mediastreamtrack, then checking the value of the returned mediatracksettings object's logicalsurface object.
Media Session API - Web APIs
it does this by providing metadata for display by the user agent of the media your web app is playing, and allows you to create event handlers, to define your own behaviors for a user-agent playback controls.
Transcoding assets for Media Source Extensions - Web APIs
if you wish to employ adaptive bitrate streaming, you'll have to create encodings at multiple resolutions.
Media Capture and Streams API (Media Stream) - Web APIs
a non-local mediastream may be representing to a media element, like <video> or <audio>, a stream originating over the network, and obtained via the webrtc rtcpeerconnection api, or a stream created using the web audio api mediastreamaudiosourcenode.
MerchantValidationEvent - Web APIs
constructor merchantvalidationevent() secure context creates a new merchantvalidationevent object describing a merchantvalidation event that will be sent to the payment handler to request that it validate the merchant.
MessageChannel.port1 - Web APIs
example in the following code block, you can see a new channel being created using the messagechannel() constructor.
MessageChannel.port2 - Web APIs
example in the following code block, you can see a new channel being created using the messagechannel.messagechannel constructor.
MessagePort: message event - Web APIs
bubbles no cancelable no interface messageevent event handler property onmessage examples suppose a script creates a messagechannel and sends one of the ports to a different browsing context, such as another <iframe>, using code like this: const channel = new messagechannel(); const myport = channel.port1; const targetframe = window.top.frames[1]; const targetorigin = 'https://example.org'; const messagecontrol = document.queryselector('#message'); const channelmessagebutton = document.queryselector('#channel-message'); channelmessagebutton.addeventlistener('click', () => { myport.postmessage(messagecontrol.value); }) targetframe.postmessage...
MessagePort: messageerror event - Web APIs
bubbles no cancelable no interface messageevent event handler property onmessageerror examples suppose a script creates a messagechannel and sends one of the ports to a different browsing context, such as another <iframe>, using code like this: const channel = new messagechannel(); const myport = channel.port1; const targetframe = window.top.frames[1]; const targetorigin = 'https://example.org'; const messagecontrol = document.queryselector('#message'); const channelmessagebutton = document.queryselector('#channel-message'); channelmessagebutton.addeventlistener('click', () => { myport.postmessage(messagecontrol.value); })...
MessagePort.onmessage - Web APIs
}; example in the following code block, you can see a new channel being created using the messagechannel.messagechannel constructor.
MessagePort.postMessage() - Web APIs
example in the following code block, you can see a new channel being created using the messagechannel.messagechannel constructor.
MessagePort - Web APIs
example in the following example, you can see a new channel being created using the messagechannel() constructor.
MimeTypeArray - Web APIs
var mimetypes = navigator.mimetype; var flashplugin = mimetypes['video/x-flv']; if (typeof flashplugin === "undefined") { var vid = document.createelement('video'); // use vid.canplaytype() to test for a supported mime type.
MouseEvent() - Web APIs
the mouseevent() constructor creates a new mouseevent.
MouseEvent.buttons - Web APIs
html <p>click anywhere with one or more mouse buttons.</p> <pre id="log">buttons: </pre> javascript let log = document.createtextnode('?'); // let log = new text('?'); function logbuttons(e) { log.data = `${e.buttons} (${e.type})`; // log.nodevalue= `${e.buttons} (${e.type})`; } document.addeventlistener('mouseup', logbuttons); document.addeventlistener('mousedown', logbuttons); // document.addeventlistener('mousemove', logbuttons); document.queryselector('#log').appendchild(log) result specifications ...
msPlayToPreferredSourceUri - Web APIs
example <video src="http://www.contoso.com/videos/video.mp4" msplaytopreferredsourceuri="http://www.contoso.com/catalogid=1234" /> var video = document.createelement('video'); document.body.appendchild(video); video.src = "http://www.contoso.com/videos/video.mp4"; video.msplaytopreferredsourceuri = "http://www.contoso.com/catalogid=1234"; see also microsoft playready content access and protection technology is a set of technologies that can be used to distribute audio/video content more securely over a network, and help prevent the unauthor...
MutationObserver.disconnect() - Web APIs
example this example creates an observer, then disconnects from it, leaving it available for possible reuse.
MutationObserver.observe() - Web APIs
// identify an element to observe const elementtoobserve = document.queryselector("#targetelementid"); // create a new instance of `mutationobserver` named `observer`, // passing it a callback function const observer = new mutationobserver(function() { console.log('callback that runs when observer is triggered'); }); // call `observe()` on that mutationobserver instance, // passing it the element to observe, and the options object observer.observe(elementtoobserve, {subtree: true, childlist: true}); s...
MutationObserverInit.attributeFilter - Web APIs
if this property exists on the options object when the mutationobserver() constructor is used to create a new mutationobserver, attribute monitoring is enabled regardless of whether or not the attributes property is true.
NDEFReadingEvent - Web APIs
constructor ndefreadingevent.ndefreadingevent() creates an ndefreadingevent event with the given parameters.
NDEFRecord.id - Web APIs
WebAPINDEFRecordid
this identifier is created by the generator of the record which is solely responsible for enforcing record identifier uniqueness.
NameList - Web APIs
WebAPINameList
note: although this interface was previously implemented in gecko, there was no way to actually create one.
Navigator.cookieEnabled - Web APIs
for example, chrome 80+ does not allow creating cookies with samesite=none attribute, unless they are created over https and with secure attribute.
Navigator.registerProtocolHandler() - Web APIs
to mms news nntp openpgp4fpr sip sms smsto ssh tel urn webcal wtai xmpp example if your site is burgers.example.com, you can register a protocol handler for it to handle web+burger: links, like so: navigator.registerprotocolhandler("web+burger", "https://burgers.example.com/?burger=%s", "burger handler"); this creates a handler that lets web+burger: links send the user to your site, inserting the accessed burger url into the %s placeholder.
Navigator.xr - Web APIs
WebAPINavigatorxr
at the same time, a new xr instance is also created and attached to the navigator instance as navigator.xr.
Online and offline events - Web APIs
updateonlinestatus); window.addeventlistener('offline', updateonlinestatus); }); a touch of css #status { position: fixed; width: 100%; font: bold 1em sans-serif; color: #fff; padding: 0.5em; } #log { padding: 2.5em 0.5em 0.5em; font: 1em sans-serif; } .online { background: green; } .offline { background: red; } and the corresponding htmlxxx when mochitests for this are created, point to those instead and update this example -nickolay <div id="status"></div> <div id="log"></div> <p>this is a test</p> here's the live result notes if the api isn't implemented in the browser, you can use other signals to detect if you are offline including using service workers and responses from xmlhttprequest.
Node.baseURI - Web APIs
WebAPINodebaseURI
details the base url of a document the base url of a document defaults to the document's address (as displayed by the browser and available in window.location), but it can be changed: when an html <base> tag is found in the document when the document is new (created dynamically) see the base urls section of the html living standard for details.
Node.firstChild - Web APIs
WebAPINodefirstChild
any whitespace will create a #text node, from a single space to multiple spaces, returns, tabs, and so on.
Node.getRootNode() - Web APIs
WebAPINodegetRootNode
lass="js-child"></div> </div> <div class="js-shadowhost"></div> <script> // works on chrome 54+,opera 41+ var parent = document.queryselector('.js-parent'), child = document.queryselector('.js-child'), shadowhost = document.queryselector('.js-shadowhost'); console.log(parent.getrootnode().nodename); // #document console.log(child.getrootnode().nodename); // #document // create a shadowroot var shadowroot = shadowhost.attachshadow({mode:'open'}); shadowroot.innerhtml = '<style>div{background:#2bb8aa;}</style>' + '<div class="js-shadowchild">content</div>'; var shadowchild = shadowroot.queryselector('.js-shadowchild'); // the default value of composed is false console.log(shadowchild.getrootnode() === shadowroot); // true console.log(shadowchild.getroo...
Node.isEqualNode() - Web APIs
WebAPINodeisEqualNode
example in this example, we create three <div> blocks.
Node.isSameNode() - Web APIs
WebAPINodeisSameNode
example in this example, we create three <div> blocks.
Node.namespaceURI - Web APIs
WebAPINodenamespaceURI
you can create an element with the specified namespaceuri using the dom level 2 method document.createelementns and attributes with the method element.setattributens.
Node.nodeType - Web APIs
WebAPINodenodeType
examples different types of nodes document.nodetype === node.document_node; // true document.doctype.nodetype === node.document_type_node; // true document.createdocumentfragment().nodetype === node.document_fragment_node; // true var p = document.createelement("p"); p.textcontent = "once upon a time…"; p.nodetype === node.element_node; // true p.firstchild.nodetype === node.text_node; // true comments this example checks if the first node inside the document element is a comment, and displays a message if not.
Node.normalize() - Web APIs
WebAPINodenormalize
syntax element.normalize(); example let wrapper = document.createelement("div"); wrapper.appendchild( document.createtextnode("part 1 ") ); wrapper.appendchild( document.createtextnode("part 2 ") ); // at this point, wrapper.childnodes.length === 2 // wrapper.childnodes[0].textcontent === "part 1 " // wrapper.childnodes[1].textcontent === "part 2 " wrapper.normalize(); // now, wrapper.childnodes.length === 1 // wrapper.childnodes[0].textcontent === "part 1 part 2 " specifications specification status comment domthe definition of 'node: normalize' in that...
Node.ownerDocument - Web APIs
syntax var document = element.ownerdocument; value document is the top-level document object in which all the child nodes are created.
Node.parentNode - Web APIs
WebAPINodeparentNode
it also returns null if the node has just been created and is not yet attached to the tree.
NodeFilter.acceptNode() - Web APIs
example var nodeiterator = document.createnodeiterator( // node to use as root document.getelementbyid('someid'), // only consider nodes that are text nodes (nodetype 3) nodefilter.show_text, // object containing the function to use for the acceptnode method // of the nodefilter { acceptnode: function(node) { // logic to determine whether to accept, reject or skip node // in this case, only accept nodes that ...
NodeFilter - Web APIs
example const nodeiterator = document.createnodeiterator( // node to use as root document.getelementbyid('someid'), // only consider nodes that are text nodes (nodetype 3) nodefilter.show_text, // object containing the function to use for the acceptnode method // of the nodefilter { acceptnode: function(node) { // logic to determine whether to accept, reject or skip node // in this case, only accept nodes that ...
NodeIterator.detach() - Web APIs
syntax nodeiterator.detach(); example var nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); nodeiterator.detach(); // detaches the iterator nodeiterator.nextnode(); // throws an invalid_state_err exception specifications specification status comment domthe definition of 'nodeiterator.detach' in that specification.
NodeIterator.expandEntityReferences - Web APIs
syntax expand = nodeiterator.expandentityreferences; example var nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); expand = nodeiterator.expandentityreferences; specifications specification status comment document object model (dom) level 2 traversal and range specificationthe definition of 'nodeiterator.expandentityreferences' in that spe...
NodeIterator.filter - Web APIs
syntax nodefilter = nodeiterator.filter; example const nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); nodefilter = nodeiterator.filter; specifications specification status comment domthe definition of 'nodeiterator.filter' in that specification.
NodeIterator.nextNode() - Web APIs
syntax node = nodeiterator.nextnode(); example var nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false // this optional argument is not used any more ); currentnode = nodeiterator.nextnode(); // returns the next node specifications specification status comment domthe definition of 'nodeiterator.nextnode' in that specification.
NodeIterator.pointerBeforeReferenceNode - Web APIs
syntax flag = nodeiterator.pointerbeforereferencenode; example var nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); flag = nodeiterator.pointerbeforereferencenode; specifications specification status comment domthe definition of 'nodeiterator.pointerbeforereferencenode' in that specification.
NodeIterator.previousNode() - Web APIs
syntax node = nodeiterator.previousnode(); example var nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false // this optional argument is not used any more ); currentnode = nodeiterator.nextnode(); // returns the next node previousnode = nodeiterator.previousnode(); // same result, since we backtracked to the previous node specifications specificatio...
NodeIterator.referenceNode - Web APIs
syntax node = nodeiterator.referencenode; example var nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); node = nodeiterator.referencenode; specifications specification status comment domthe definition of 'nodeiterator.referencenode' in that specification.
NodeIterator.root - Web APIs
WebAPINodeIteratorroot
syntax root = nodeiterator.root; example var nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); root = nodeiterator.root; // document.body in this case specifications specification status comment domthe definition of 'nodeiterator.root' in that specification.
NodeIterator.whatToShow - Web APIs
example var nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element + nodefilter.show_comment + nodefilter.show_text, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); if( (nodeiterator.whattoshow == nodefilter.show_all) || (nodeiterator.whattoshow % (nodefilter.show_comment*2)) >= nodefilter.show_comment) { // nodeiterator will show comments } specifications...
NodeList.entries() - Web APIs
WebAPINodeListentries
example var node = document.createelement("div"); var kid1 = document.createelement("p"); var kid2 = document.createtextnode("hey"); var kid3 = document.createelement("span"); node.appendchild(kid1); node.appendchild(kid2); node.appendchild(kid3); var list = node.childnodes; // using for..of for(var entry of list.entries()) { console.log(entry); } results in: array [ 0, <p> ] array [ 1, #text "hey" ] array [ 2, <span> ] ...
NodeList.prototype.forEach() - Web APIs
WebAPINodeListforEach
example let node = document.createelement("div"); let kid1 = document.createelement("p"); let kid2 = document.createtextnode("hey"); let kid3 = document.createelement("span"); node.appendchild(kid1); node.appendchild(kid2); node.appendchild(kid3); let list = node.childnodes; list.foreach( function(currentvalue, currentindex, listobj) { console.log(currentvalue + ', ' + currentindex + ', ' + this); }, 'mythisarg' ); t...
NodeList.keys() - Web APIs
WebAPINodeListkeys
example var node = document.createelement("div"); var kid1 = document.createelement("p"); var kid2 = document.createtextnode("hey"); var kid3 = document.createelement("span"); node.appendchild(kid1); node.appendchild(kid2); node.appendchild(kid3); var list = node.childnodes; // using for..of for(var key of list.keys()) { console.log(key); } the result is: 0 1 2 ...
NodeList.values() - Web APIs
WebAPINodeListvalues
example var node = document.createelement("div"); var kid1 = document.createelement("p"); var kid2 = document.createtextnode("hey"); var kid3 = document.createelement("span"); node.appendchild(kid1); node.appendchild(kid2); node.appendchild(kid3); var list = node.childnodes; // using for..of for(var value of list.values()) { console.log(value); } the result is: <p> #text "hey" <span> ...
NodeList - Web APIs
WebAPINodeList
for example, node.childnodes is live: const parent = document.getelementbyid('parent'); let child_nodes = parent.childnodes; console.log(child_nodes.length); // let's assume "2" parent.appendchild(document.createelement('div')); console.log(child_nodes.length); // outputs "3" static nodelists in other cases, the nodelist is static, where any changes in the dom does not affect the content of the collection.
NonDocumentTypeChildNode - Web APIs
nondocumenttypechildnode is a raw interface and no object of this type can be created; it is implemented by element, and characterdata objects.
Notification.close() - Web APIs
examples in the following snippet, we have a simple function that when called creates an options object and then a new notification.
Notification.data - Web APIs
WebAPINotificationdata
examples the following snippet fires a notification; a simple options object is created, then the notification is fired using the notification() constructor.
Notification.dir - Web APIs
WebAPINotificationdir
examples the following snippet fires a notification; a simple options object is created, then the notification is fired using the notification() constructor.
Notification.lang - Web APIs
WebAPINotificationlang
examples the following snippet fires a notification; a simple options object is created, then the notification is fired using the notification() constructor.
Notification.permission - Web APIs
function notifyme() { // let's check if the browser supports notifications if (!("notification" in window)) { console.log("this browser does not support desktop notification"); } // let's check whether notification permissions have alredy been granted else if (notification.permission === "granted") { // if it's okay let's create a notification var notification = new notification("hi there!"); } // otherwise, we need to ask the user for permission else if (notification.permission !== 'denied' || notification.permission === "default") { notification.requestpermission(function (permission) { // if the user accepts, let's create a notification if (permission === "granted") { var notificatio...
Notification.renotify - Web APIs
examples the following snippet is intended to fire a notification that renotifies the user after it has been replaced; a simple options object is created, and then the notification is fired using the notification() constructor.
Notification.requestPermission() - Web APIs
function notifyme() { // let's check if the browser supports notifications if (!("notification" in window)) { alert("this browser does not support desktop notification"); } // let's check whether notification permissions have already been granted else if (notification.permission === "granted") { // if it's okay let's create a notification var notification = new notification("hi there!"); } // otherwise, we need to ask the user for permission else if (notification.permission !== "denied") { notification.requestpermission().then(function (permission) { // if the user accepts, let's create a notification if (permission === "granted") { var notification = new notification("hi there!");...
Notification.requireInteraction - Web APIs
note: this can be set when the notification is first created by setting the requireinteraction option to true in the options object of the notification.notification() constructor.
Notification.silent - Web APIs
examples the following snippet is intended to fire a silent notification; a simple options object is created, and then the notification is fired using the notification() constructor.
Notification.vibrate - Web APIs
examples the following snippet is intended to create a notification that also triggers a device vibration; a simple options object is created, and then the notification is fired using the notification() constructor.
NotificationEvent.NotificationEvent() - Web APIs
the notificationevent() constructor creates a new notificationevent object.
NotificationEvent - Web APIs
constructor notificationevent() creates a new notificationevent object.
Using the Notifications API - Web APIs
for example, in the to-do-list example we use the following snippet to create a notification when required (found inside the createnotification() function): var img = '/to-do-notifications/img/icon-128.png'; var text = 'hey!
Notifications API - Web APIs
next, a new notification is created using the notification() constructor.
OES_texture_float - Web APIs
examples var ext = gl.getextension('oes_texture_float'); var texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); gl.teximage2d(gl.texture_2d, 0, gl.rgba, gl.rgba, gl.float, image); specifications specification status comment oes_texture_floatthe definition of 'oes_texture_float' in that specification.
OES_texture_float_linear - Web APIs
examples gl.getextension('oes_texture_float'); gl.getextension('oes_texture_float_linear'); var texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); gl.texparameterf(gl.texture_2d, gl.texture_mag_filter, gl.linear); gl.teximage2d(gl.texture_2d, 0, gl.rgba, gl.rgba, gl.float, image); specifications specification status comment oes_texture_float_linearthe definition of 'oes_texture_float_linear' in that specification.
OES_texture_half_float - Web APIs
examples var ext = gl.getextension('oes_texture_half_float'); var texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); gl.teximage2d(gl.texture_2d, 0, gl.rgba, gl.rgba, ext.half_float_oes, image); specifications specification status comment oes_texture_half_floatthe definition of 'oes_texture_half_float' in that specification.
OES_texture_half_float_linear - Web APIs
examples var halffloat = gl.getextension('oes_texture_half_float'); gl.getextension('oes_texture_half_float_linear'); var texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); gl.texparameterf(gl.texture_2d, gl.texture_mag_filter, gl.linear); gl.teximage2d(gl.texture_2d, 0, gl.rgba, gl.rgba, halffloat.half_float_oes, image); specifications specification status comment oes_texture_half_float_linearthe definition of 'oes_texture_half_float_linear' in that specification.
OES_vertex_array_object.bindVertexArrayOES() - Web APIs
examples var ext = gl.getextension('oes_vertex_array_object'); var vao = ext.createvertexarrayoes(); ext.bindvertexarrayoes(vao); // ...
OES_vertex_array_object.deleteVertexArrayOES() - Web APIs
examples var ext = gl.getextension('oes_vertex_array_object'); var vao = ext.createvertexarrayoes(); ext.bindvertexarrayoes(vao); // ...
OES_vertex_array_object.isVertexArrayOES() - Web APIs
examples var ext = gl.getextension('oes_vertex_array_object'); var vao = ext.createvertexarrayoes(); ext.bindvertexarrayoes(vao); // ...
OfflineAudioCompletionEvent - Web APIs
constructor offlineaudiocompletionevent.offlineaudiocompletionevent creates a new offlineaudiocompletionevent object instance.
OffscreenCanvas.convertToBlob() - Web APIs
the offscreencanvas.converttoblob() method creates a blob object representing the image contained in the canvas.
OffscreenCanvas() - Web APIs
examples this example creates a new offscreen canvas using the offscreencanvas() constructor.
OffscreenCanvas.convertToBlob() - Web APIs
the offscreencanvas.converttoblob()method creates a blob object representing the image contained in the canvas.
OffscreenCanvas.convertToBlob() - Web APIs
the offscreencanvas.converttoblob() method creates a blob object representing the image contained in the canvas.
OffscreenCanvas.transferToImageBitmap() - Web APIs
the offscreencanvas.transfertoimagebitmap() method creates an imagebitmap object from the most recently rendered image of the offscreencanvas.
OverconstrainedError.OverconstrainedError() - Web APIs
the overconstrainederror constructor creates a new overconstrainederror object which indicates that the set of desired capabilities for the current mediastreamtrack cannot currently be met.
OverconstrainedError - Web APIs
constructor overconstrainederror.overconstrainederror() creates a new overconstrainederror object.
Page Visibility API - Web APIs
the example, which pauses the video when you switch to another tab and plays again when you return to its tab, was created with the following code: // set the name of the hidden property and the change event for visibility var hidden, visibilitychange; if (typeof document.hidden !== "undefined") { // opera 12.10 and firefox 18 and later support hidden = "hidden"; visibilitychange = "visibilitychange"; } else if (typeof document.mshidden !== "undefined") { hidden = "mshidden"; visibilitychange = "msvisibilit...
PaintWorklet - Web APIs
create a paintworklet the following shows an example worklet module.
PannerNode.PannerNode() - Web APIs
the pannernode() constructor of the web audio api creates a new pannernode object instance.
PannerNode.orientationX - Web APIs
they range between -1 and 1 const x = math.cos(radians); const z = math.sin(radians); // we hard-code the y component to 0, as y is the axis of rotation return [x, 0, z]; }; now we can create our audiocontext, an oscillator and a pannernode: const context = new audiocontext(); const osc = new oscillatornode(context); osc.type = 'sawtooth'; const panner = new pannernode(context); panner.panningmodel = 'hrtf'; next, we set up the cone of our spatialised sound, determining the area in which it can be heard: // this value determines the size of the area in which the sound volume is c...
PannerNode.orientationY - Web APIs
they range between -1 and 1 const x = math.cos(radians); const z = math.sin(radians); // we hard-code the y component to 0, as y is the axis of rotation return [x, 0, z]; }; now we can create our audiocontext, an oscillator and a pannernode: const context = new audiocontext(); const osc = new oscillatornode(context); osc.type = 'sawtooth'; const panner = new pannernode(context); panner.panningmodel = 'hrtf'; next, we set up the cone of our spatialised sound, determining the area in which it can be heard: // this value determines the size of the area in which the sound volume is c...
PannerNode.orientationZ - Web APIs
they range between -1 and 1 const x = math.cos(radians); const z = math.sin(radians); // we hard-code the y component to 0, as y is the axis of rotation return [x, 0, z]; }; now we can create our audiocontext, an oscillator and a pannernode: const context = new audiocontext(); const osc = new oscillatornode(context); osc.type = 'sawtooth'; const panner = new pannernode(context); panner.panningmodel = 'hrtf'; next, we set up the cone of our spatialised sound, determining the area in which it can be heard: // this value determines the size of the area in which the sound volume is c...
PasswordCredential - Web APIs
constructor passwordcredential()secure context creates a new passwordcredential object.
PaymentAddress - Web APIs
examples in the following example, the paymentrequest() constructor is used to create a new payment request, which takes three objects as parameters — one containing details of the payment methods that can be used for the payment, one containing details of the actual order (such as items bought and shipping options), and an optional object containing further options.
PaymentMethodChangeEvent - Web APIs
constructor paymentmethodchangeevent() creates and returns a new paymentmethodchangeevent object, optionally initialized with values taken from a given paymentmethodchangeeventinit dictionary.
PaymentRequest.PaymentRequest() - Web APIs
the paymentrequest() constructor creates a new paymentrequest object which will be used to handle the process of generating, validating, and submitting a payment request.
PaymentRequest: shippingoptionchange event - Web APIs
you can also create an event handler for shippingoptionchange using its corresponding event handler property, onshippingoptionchange: paymentrequest.onshippingoptionchange = event => { const value = calculatenewtotal(paymentrequest.shippingoption); const total = { currency: "eur", label: "total due", value, }; event.updatewith({ total }); }; specifications specification status c...
PaymentRequest - Web APIs
constructor paymentrequest() secure context creates a new paymentrequest object.
PaymentRequestEvent() - Web APIs
the paymentrequestevent constructor creates a new paymentrequestevent object which is a constructor for a paymentrequestevent which is the object passed to a payment handler when a paymentrequest is made..
PaymentRequestEvent - Web APIs
constructor paymentrequestevent() creates a new paymentrequestevent object.
PaymentRequestUpdateEvent.PaymentRequestUpdateEvent() - Web APIs
the paymentrequestupdateevent constructor creates a new paymentrequestupdateevent object which enables a web page to update the details of a paymentrequest in response to a user action.
PaymentRequestUpdateEvent - Web APIs
constructor paymentrequestupdateevent() secure context creates a new paymentrequestupdateevent object.
PaymentResponse.retry() - Web APIs
see the example below for a thorough example, but the basic concept, in outline form, is: create a new paymentrequest (new paymentrequest()) display the payment request (paymentrequest.show() if show() resolves, the returned paymentresponse describes the requested payment and the options chosen by the user.
PaymentValidationErrors - Web APIs
when validation of the paymentresponse returned by the paymentrequest.show() or paymentresponse.retry() methods fails, your code creates a paymentvalidationerrors object to pass into retry() so that the user agent knows what needs to be fixed and what if any error messages to display to the user.
Payment Request API - Web APIs
to request a payment, a web page creates a paymentrequest object in response to a user action that initiates a payment, such as clicking a "purchase" button.
performance.clearResourceTimings() - Web APIs
example function load_resource() { var image = new image(); image.src = "https://developer.mozilla.org/static/img/opengraph-logo.png"; } function clear_performance_timings() { if (performance === undefined) { log("browser does not support web performance"); return; } // create a resource timing performance entry by loading an image load_resource(); var supported = typeof performance.clearresourcetimings == "function"; if (supported) { console.log("run: performance.clearresourcetimings()"); performance.clearresourcetimings(); } else { console.log("performance.clearresourcetimings() not supported"); return; } // getentries should now return z...
PerformanceEntry.duration - Web APIs
performance.mark not supported"); return; } // create some performance entries via the mark() method performance.mark("begin"); do_work(50000); performance.mark("end"); // use getentries() to iterate through the each entry var p = performance.getentries(); for (var i=0; i < p.length; i++) { log("entry[" + i + "]"); check_performanceentry(p[i]); } } function check_performanceentry(obj) { var properties = ["name", "entrytype",...
PerformanceEntry.toJSON() - Web APIs
performance.mark not supported"); return; } // create some performance entries via the mark() method performance.mark("begin"); do_work(50000); performance.mark("end"); // use getentries() to iterate through the each entry var p = performance.getentries(); for (var i=0; i < p.length; i++) { log("entry[" + i + "]"); check_performanceentry(p[i]); } } function check_performanceentry(obj) { var properties = ["name", "entrytype",...
PerformanceEventTiming - Web APIs
sendtoanalytics({fid}); } } // create a performanceobserver that calls `onfirstinputentry` for each entry.
PerformanceObserver() - Web APIs
the performanceobserver() constructor creates a new performanceobserver object with the given observer callback.
PerformanceObserver.observe() - Web APIs
examples this example creates and configures two performanceobservers; one watches for "mark" and "frame" events, and the other watches for "measure" events.
PerformanceObserver - Web APIs
constructor performanceobserver() creates and returns a new performanceobserver object.
PerformanceObserverEntryList.getEntries() - Web APIs
example function print_perf_entry(pe) { console.log("name: " + pe.name + "; entrytype: " + pe.entrytype + "; starttime: " + pe.starttime + "; duration: " + pe.duration); } // create observer for all performance event types var observe_all = new performanceobserver(function(list, obs) { var perfentries; // print all entries perfentries = list.getentries(); for (var i=0; i < perfentries.length; i++) { print_perf_entry(perfentries[i]); } // print entries named "begin" with type "mark" perfentries = list.getentriesbyname("begin", "mark"); for (var i=0; i < ...
PerformanceObserverEntryList.getEntriesByName() - Web APIs
example function print_perf_entry(pe) { console.log("name: " + pe.name + "; entrytype: " + pe.entrytype + "; starttime: " + pe.starttime + "; duration: " + pe.duration); } // create observer for all performance event types var observe_all = new performanceobserver(function(list, obs) { var perfentries; // print all entries perfentries = list.getentries(); for (var i=0; i < perfentries.length; i++) { print_perf_entry(perfentries[i]); } // print entries named "begin" with type "mark" perfentries = list.getentriesbyname("begin", "mark"); for (var i=0; i < ...
PerformanceObserverEntryList.getEntriesByType() - Web APIs
example function print_perf_entry(pe) { console.log("name: " + pe.name + "; entrytype: " + pe.entrytype + "; starttime: " + pe.starttime + "; duration: " + pe.duration); } // create observer for all performance event types var observe_all = new performanceobserver(function(list, obs) { var perfentries; // print all entries perfentries = list.getentries(); for (var i=0; i < perfentries.length; i++) { print_perf_entry(perfentries[i]); } // print entries named "begin" with type "mark" perfentries = list.getentriesbyname("begin", "mark"); for (var i=0; i < ...
PerformanceObserverEntryList - Web APIs
example // create observer for all performance event types // list is of type performanceobserveentrylist var observe_all = new performanceobserver(function(list, obs) { var perfentries = list.getentries(); for (var i = 0; i < perfentries.length; i++) { print_perf_entry(perfentries[i]); // do something with it } }) specifications specification status comment performan...
PerformanceResourceTiming - Web APIs
the interface's properties create a resource loading timeline with high-resolution timestamps for network events such as redirect start and end times, fetch start, dns lookup start and end times, response start and end times, etc..
PerformanceServerTiming - Web APIs
ng header, for example a node.js server like this: const http = require('http'); function requesthandler(request, response) { const headers = { 'server-timing': ` cache;desc="cache read";dur=23.2, db;dur=53, app;dur=47.2 `.replace(/\n/g, '') }; response.writehead(200, headers); response.write(''); return settimeout(_ => { response.end(); }, 1000) }; http.createserver(requesthandler).listen(3000).on('error', console.error); the performanceservertiming entries are now observable from javascript via the performanceresourcetiming.servertiming property: let entries = performance.getentriesbytype('resource'); console.log(entries[0].servertiming); // 0: performanceservertiming {name: "cache", duration: 23.2, description: "cache read"} // 1: performanceserver...
Using the Performance API - Web APIs
additionally, there must be a way to create a timestamp for a specific point in time; this is done with the now() method.
PhotoCapabilities - Web APIs
this example also shows how the imagecapture object is created using a mediastreamtrack retrieved from a device's mediastream.
PointerEvent.PointerEvent() - Web APIs
the pointerevent() constructor creates a new synthetic and untrusted pointerevent object instance.
PointerEvent.isPrimary - Web APIs
the isprimary read-only property of the pointerevent interface indicates whether or not the pointer device that created the event is the primary pointer.
PointerEvent - Web APIs
constructors pointerevent() creates a synthetic—and untrusted—pointerevent.
Using Pointer Events - Web APIs
create a canvas the touch-action property is set to none to prevent the browser from applying its default touch behavior to the application.
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.
ProgressEvent() - Web APIs
the progressevent() constructor returns a newly created progressevent, representing the current completion of a long process.
PromiseRejectionEvent - Web APIs
><rect x="116" y="1" width="210" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="221" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">promiserejectionevent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor promiserejectionevent() creates a promiserejectionevent event, given the type of event (unhandledrejection or rejectionhandled) and other details.
PublicKeyCredential.id - Web APIs
ublickey = { challenge: new uint8array(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { var id = newcredentialinfo.id; // do something with the id // send attestation response and client extensions // to the server to proceed with the registration // of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authe...
PublicKeyCredential.rawId - Web APIs
examples var options = { challenge: new uint8array(26) /* from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey: options }) .then(function (pubkeycredential) { var rawid = pubkeycredential.rawid; // do something with rawid }).catch(function (err) { // deal with any error }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the definition of 'rawid' in that specification.
PublicKeyCredentialCreationOptions.attestation - Web APIs
"indirect", challenge: new uint8array(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { // send attestation response and client extensions // to the server to proceed with the registration // of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the def...
PublicKeyCredentialCreationOptions.authenticatorSelection - Web APIs
ification: "required" }, challenge: new uint8array(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { // send attestation response and client extensions // to the server to proceed with the registration // of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the def...
PublicKeyCredentialCreationOptions.challenge - Web APIs
ublickey = { challenge: new uint8array(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { // send attestation response and client extensions // to the server to proceed with the registration // of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the def...
PublicKeyCredentialCreationOptions.extensions - Web APIs
false, exts: true }, challenge: new uint8array(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { // mybuffer will contain the result of any of the processing of the extensions var mybuffer = newcredentialinfo.getclientextensionresults(); // send attestation response and client extensions // to the server to proceed with the registration // of the credential }).catch(function (err) { console.error(err); }); s...
PublicKeyCredentialCreationOptions.timeout - Web APIs
challenge: new uint8array(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { // send attestation response and client extensions // to the server to proceed with the registration // of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the def...
PublicKeyCredentialRequestOptions.allowCredentials - Web APIs
syntax allowcredentials = publickeycredentialrequestoptions.allowcredentials value an array whose elements are objects with the following properties: type a string describing type of public-key credential to be created.
PublicKeyCredentialRequestOptions.challenge - Web APIs
note: when the credential is created with a navigator.credentials.create() call, the signature of the challenge is contained within authenticatorattestationresponse.attestationobject.
PublicKeyCredentialRequestOptions.extensions - Web APIs
note: an analogous option exists for the creation operation (navigators.credentials.create()), see publickeycredentialcreationoptions.extensions.
PublicKeyCredentialRequestOptions.rpId - Web APIs
note: an analogous option exists for the creation operation (navigators.credentials.create()), see the id property of publickeycredentialcreationoptions.rp.
PublicKeyCredentialRequestOptions.timeout - Web APIs
note: an analogous option exists for the creation operation (navigators.credentials.create()), see publickeycredentialcreationoptions.timeout.
PublicKeyCredentialRequestOptions.userVerification - Web APIs
note: an analogous option exists for the creation operation (navigators.credentials.create()), see the userverification property of publickeycredentialcreationoptions.authenticatorselection.
PushEvent.PushEvent() - Web APIs
the pushevent() constructor creates a new pushevent object.
PushEvent - Web APIs
WebAPIPushEvent
constructor pushevent.pushevent() creates a new pushevent object.
PushManager.subscribe() - Web APIs
a new push subscription is created if the current service worker does not have an existing subscription.
PushManager - Web APIs
a new push subscription is created if the current service worker does not have an existing subscription.
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.
PushSubscription - Web APIs
pushsubscription.options read only an object containing the options used to create the subscription.
Web Push API Notifications best practices - Web APIs
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.
RTCDataChannel.binaryType - Web APIs
var dc = peerconnection.createdatachannel("binary"); dc.binarytype = "arraybuffer"; dc.onmessage = function(event) { let bytearray = new uint8array(event.data); let hexstring = ""; bytearray.foreach(function(byte) { hexstring += byte.tostring(16) + " "; }); }; specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdatach...
RTCDataChannel.bufferedAmount - Web APIs
var dc = peerconnection.createdatachannel("file transfer"); /* ...
RTCDataChannel.bufferedAmountLowThreshold - Web APIs
var dc = peerconnection.createdatachannel("file transfer"); dc.bufferedamountlowthreshold = 65535; dc.onbufferedamountlow = function() { /* use send() to queue more data to be sent */ }; specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdatachannel.bufferedamountlowthreshold' in that specification.
RTCDataChannel.close() - Web APIs
example var pc = new rtcpeerconnection(); var dc = pc.createdatachannel("my channel"); dc.onmessage = function (event) { console.log("received: " + event.data); dc.close(); // we decided to close after the first received message }; dc.onopen = function () { console.log("datachannel open"); }; dc.onclose = function ( console.log("datachannel close"); }; // now negotiate the connection and so forth...
RTCDataChannel: close event - Web APIs
before any further data can be transferred using rtcdatachannel, a new data channel instance must be created.
RTCDataChannel.onbufferedamountlow - Web APIs
pc = new rtcpeerconnection(); dc = pc.createdatachannel("sendfile"); /* ...
RTCDataChannel.onerror - Web APIs
let pc = new rtcpeerconnection(); let dc = pc.createdatachannel("playercontrol"); dc.onerror = function(event) { myuilibrary.doalertbox({ 'network error', // alert title 'the error "' + event.message + '" occurred while handling player control network messages.', event.filename, event.lineno, event.colno }); } /* ...
RTCDataChannel.onopen - Web APIs
let dc = mypeerconnection.createdatachannel("message channel"); dc.onopen = function(event) { let messagebox = document.getelementbyid("messagebox"); let sendbutton = document.getelementbyid("sendbutton"); messagebox.disabled = false; messagebox.focus(); sendbutton.disabled = false; } specifications specification status comment webrtc 1.0: real-time communication between browsersthe def...
RTCDataChannelEvent - Web APIs
constructorrtcdatachannelevent() the rtcdatachannelevent() constructor creates a new rtcdatachannelevent.propertiesalso inherits properties from: eventchannel read only the read-only property rtcdatachannelevent.channel returns the rtcdatachannel associated with the event.methodsthis interface has no methods, but inherits methods from: event examples in this example, the datachannel event handler is set up to save the data channel reference and set up handlers for the ...
RTCError - Web APIs
WebAPIRTCError
constructor rtcerror() creates and returns a new rtcerror object initialized with the properties of the provided rtcerrorinit dictionary and, optionally, a string to use as the value of the error's message property.
RTCErrorEvent - Web APIs
constructor rtcerrorevent() creates and returns a new rtcerrorevent object.
RTCIceCandidate - Web APIs
constructor rtcicecandidate() creates an rtcicecandidate object to represent a single ice candidate, optionally configured based on an object based on the rtcicecandidateinit dictionary.
RTCIceCandidateInit - Web APIs
rtcicecandidateinit is used when using new rtcicecandidate() to create a new ice candidate object.
RTCIceGathererState - Web APIs
values "new" the rtcicetransport is newly created and has not yet started to gather ice candidates.
RTCIceServer.credential - Web APIs
}; var credential = iceserver.credential; iceserver.credential = newcredential; example this example creates a new rtcpeerconnection which uses a turn server at turnserver.example.org to negotiate connections.
RTCIceServer.credentialType - Web APIs
example this example creates a new rtcpeerconnection which will use a turn server at turnserver.example.org to negotiate connections.
RTCIceServer.url - Web APIs
WebAPIRTCIceServerurl
example this example creates a new rtcpeerconnection which will use a stun server at stunserver.example.org to negotiate connections.
RTCIceServer.username - Web APIs
}; var username = iceserver.username; iceserver.username = newusername; example this example creates a new rtcpeerconnection which will use a turn server at turnserver.example.org to negotiate connections.
RTCIceServer - Web APIs
me: "louis@mozilla.com", credential: "webrtcdemo" }, { urls: [ "stun:stun.example.com", "stun:stun-1.example.com" ] }] }; var pc = new rtcpeerconnection(configuration); once the configuration object has been created, it is passed into the rtcpeerconnection() constructor to use it as the configuration for the new peer connection.
RTCIceTransport.gatheringState - Web APIs
syntax gatherstate = rtcicetransport.gatheringstate; value a string from the rtcicegathererstate enumerated type whose value indicates the current state of the ice agent's candidate gathering process: "new" the rtcicetransport is newly created and has not yet started to gather ice candidates.
RTCIceTransport: gatheringstatechange event - Web APIs
examples this example creates a handler for gatheringstatechange events on each rtcrtpsender associated with a given rtcpeerconnection.
RTCIceTransport.ongatheringstatechange - Web APIs
its possible values are: "new" the rtcicetransport is newly created and has not yet started to gather ice candidates.
RTCIceTransport: selectedcandidatepairchange event - Web APIs
bubbles no cancelable no interface event event handler property onselectedcandidatepairchange examples this example creates an event handler for selectedcandidatepairchange that updates a display providing the user information about the progress of the ice negotiation for an rtcpeerconnection called pc.
RTCIceTransport: statechange event - Web APIs
bubbles no cancelable no interface event event handler property rtcicetransport.onstatechange examples given an rtcpeerconnection, pc, the following code creates an event handler that calls a function named handlefailure() if the ice transport enters a failure state.
RTCInboundRtpStreamStats.lastPacketReceivedTimestamp - Web APIs
note: this value differs from the timestamp, which represents the time at which the statistics object was created.
RTCOutboundRtpStreamStats.lastPacketSentTimestamp - Web APIs
note: this value differs from the timestamp, which represents the time at which the statistics object was created.
RTCPeerConnection.addTransceiver() - Web APIs
the rtcpeerconnection method addtransceiver() creates a new rtcrtptransceiver and adds it to the set of transceivers associated with the rtcpeerconnection.
RTCPeerConnection.canTrickleIceCandidates - Web APIs
pc.setremotedescription(remoteoffer) .then(_ => pc.createanswer()) .then(answer => pc.setlocaldescription(answer)) .then(_ => if (pc.cantrickleicecandidates) { return pc.localdescription; } return new promise(r => { pc.addeventlistener('icegatheringstatechange', e => { if (e.target.icegatheringstate === 'complete') { r(pc.localdescription); } }); }); }) .then(answer => sendanswertopeer(...
RTCPeerConnection: connectionstatechange event - Web APIs
nestatus("connecting..."); break; case "connected": setonlinestatus("online"); break; case "disconnected": setonlinestatus("disconnecting..."); break; case "closed": setonlinestatus("offline"); break; case "failed": setonlinestatus("error"); break; default: setonlinestatus("unknown"); break; } } you can also create a handler for connectionstatechange by using addeventlistener(): pc.addeventlistener("connectionstatechange", ev => { switch(pc.connectionstate) { /* ...
RTCPeerConnection.generateCertificate() - Web APIs
the generatecertificate() method of the rtcpeerconnection interface creates and stores an x.509 certificate and corresponding private key then returns an rtccertificate, providing access to it.
RTCPeerConnection.getConfiguration() - Web APIs
if it's determined that there are no certificates in place, rtcpeerconnection.generatecertificate() is called to create a new certificate; we provide a fulfillment handler which adds a new array containing the one newly-created certificate to the current configuration and passes it to setconfiguration() to add the certificate to the connection.
RTCPeerConnection.getStreamById() - Web APIs
example var stream = pc.getstreambyid(mytrackid); if (stream) { console.log("found stream: " + stream.id); } polyfill running the following code before any other code will create rtcpeerconnection.prototype.getstreambyid() if it's not natively available.
RTCPeerConnection: iceconnectionstatechange event - Web APIs
in this example, a handler for iceconnectionstatechange is set up to update a call state indicator by using the value of iceconnectionstate to create a string which corresponds to the name of a css class that we can assign to the status indicator to cause it to reflect the current state of the connection.
RTCPeerConnection.iceGatheringState - Web APIs
constant description "new" the peer connection was just created and hasn't done any networking yet.
RTCPeerConnection: icegatheringstatechange event - Web APIs
examples this example creates a handler for icegatheringstatechange events.
RTCPeerConnection: icecandidate event - Web APIs
examples this example creates a simple handler for the icecandidate event that uses a function called sendmessage() to create and send a reply to the remote peer through the signaling server.
RTCPeerConnection.onnegotiationneeded - Web APIs
pc.onnegotiationneeded = function() { pc.createoffer().then(function(offer) { return pc.setlocaldescription(offer); }) .then(function() { // send the offer to the remote peer through the signaling server }); }) .catch(reporterror); } first, it creates the offer by calling createoffer().
RTCPeerConnection.ontrack - Web APIs
the function receives as input the event object, of type rtctrackevent; this event is sent when a new incoming mediastreamtrack has been created and associated with an rtcrtpreceiver object which has been added to the set of receivers on connection.
RTCPeerConnection.sctp - Web APIs
example var pc = new rtcpeerconnection(); var channel = pc.createdatachannel("mydata"); channel.onopen = function(event) { channel.send('sending a message'); } channel.onmessage = function(event) { console.log(event.data); } // determine the largest message size that can be sent var sctp = pc.sctp; var maxmessagesize = sctp.maxmessagesize; specifications specification status comment webrtc 1.0: real-time communication betwee...
RTCPeerConnection: track event - Web APIs
examples this example shows code that creates a new rtcpeerconnection, then adds a new track event handler.
RTCPeerConnectionIceErrorEvent.address - Web APIs
examples this example creates a handler for icecandidateerror events which creates human readable messages describing the local network interface for the connection as well as the ice server that was being used to try to open the connection, then calls a function to display those as well as the event's errortext property's contents.
RTCRemoteOutboundRtpStreamStats.localId - Web APIs
let's create a utility function to help us look up the value of a key in the paired statistics object.
RTCRtpEncodingParameters - Web APIs
its value can only be set when the transceiver is first created.
RTCRtpSendParameters.encodings - Web APIs
its value can only be set when the transceiver is first created.
RTCRtpTransceiver.direction - Web APIs
effect on offers and answers the value of direction is used by rtcpeerconnection.createoffer() or rtcpeerconnection.createanswer() in order to generate the sdp generated by each of those methods.
RTCRtpTransceiver.setCodecPreferences() - Web APIs
when preparing to open an rtcpeerconnection, you can change the codec parameters from the user agent's default configuration by calling setcodecparameters() before calling either rtcpeerconnection.createoffer() or createanswer().
RTCSctpTransport - Web APIs
you don't create rtcsctptransport objects yourself; instead, you get access to the rtcsctptransport for a given rtcpeerconnection through its sctp property.
RTCSessionDescription - Web APIs
example signalingchannel.onmessage = function (evt) { if (!pc) start(false); var message = json.parse(evt.data); if (message.sdp) pc.setremotedescription(new rtcsessiondescription(message), function () { // if we received an offer, we need to answer if (pc.remotedescription.type == "offer") pc.createanswer(localdesccreated, logerror); }, logerror); else pc.addicecandidate(new rtcicecandidate(message.candidate), function () {}, logerror); }; specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcsessiondescription' in that specification.
Range.cloneContents() - Web APIs
syntax documentfragment = range.clonecontents(); example range = document.createrange(); range.selectnode(document.getelementsbytagname("div").item(0)); documentfragment = range.clonecontents(); document.body.appendchild(documentfragment); specifications specification status comment domthe definition of 'range.clonecontents()' in that specification.
Range.cloneRange() - Web APIs
WebAPIRangecloneRange
syntax clone = range.clonerange(); example range = document.createrange(); range.selectnode(document.getelementsbytagname("div").item(0)); clone = range.clonerange(); specifications specification status comment domthe definition of 'range.clonerange()' in that specification.
Range.collapse() - Web APIs
WebAPIRangecollapse
example var range = document.createrange(); referencenode = document.getelementsbytagname("div").item(0); range.selectnode(referencenode); range.collapse(true); specifications specification status comment domthe definition of 'range.collapse()' in that specification.
Range.collapsed - Web APIs
WebAPIRangecollapsed
syntax iscollapsed = range.collapsed; example let range = document.createrange(); range.setstart(startnode, startoffset); range.setend(endnode, endoffset); iscollapsed = range.collapsed; specifications specification status comment domthe definition of 'range.collapsed' in that specification.
Range.compareBoundaryPoints() - Web APIs
example var range, sourcerange, compare; range = document.createrange(); range.selectnode(document.getelementsbytagname("div")[0]); sourcerange = document.createrange(); sourcerange.selectnode(document.getelementsbytagname("div")[1]); compare = range.compareboundarypoints(range.start_to_end, sourcerange); specifications specification status comment domthe definition of 'range.compareboundarypoints()' in that specification.
Range.comparePoint() - Web APIs
example range = document.createrange(); range.selectnode(document.getelementsbytagname('div').item(0)); returnvalue = range.comparepoint(document.getelementsbytagname('p').item(0), 1); specification specification status comment domthe definition of 'range.comparepoint()' in that specification.
Range.deleteContents() - Web APIs
syntax range.deletecontents() example range = document.createrange(); range.selectnode(document.getelementsbytagname("div").item(0)); range.deletecontents(); specifications specification status comment domthe definition of 'range.deletecontents()' in that specification.
Range.detach() - Web APIs
WebAPIRangedetach
syntax range.detach(); example var range = document.createrange(); range.selectnode(document.getelementsbytagname("div").item(0)); range.detach(); specifications specification status comment domthe definition of 'range.detach()' in that specification.
Range.endContainer - Web APIs
syntax endrangenode = range.endcontainer; example var range = document.createrange(); range.setstart(startnode,startoffset); range.setend(endnode,endoffset); endrangenode = range.endcontainer; specifications specification status comment domthe definition of 'range.endcontainer' in that specification.
Range.endOffset - Web APIs
WebAPIRangeendOffset
syntax endrangeoffset = range.endoffset; example var range = document.createrange(); range.setstart(startnode,startoffset); range.setend(endnode,endoffset); endrangeoffset = range.endoffset; specifications specification status comment domthe definition of 'range.endoffset' in that specification.
Range.extractContents() - Web APIs
syntax documentfragment = range.extractcontents(); example basic example var range = document.createrange(); range.selectnode(document.getelementsbytagname("div").item(0)); var documentfragment = range.extractcontents(); document.body.appendchild(documentfragment); moving items between containers this example lets you move items between two containers.
Range.getBoundingClientRect() - Web APIs
the bounding client rectangle contains everything selected in the range.</p> css #highlight { background: yellow; position: absolute; z-index: -1; } p { width: 200px; } javascript const range = document.createrange(); range.setstartbefore(document.getelementsbytagname('b').item(0), 0); range.setendafter(document.getelementsbytagname('b').item(1), 0); const clientrect = range.getboundingclientrect(); const highlight = document.getelementbyid('highlight'); highlight.style.left = `${clientrect.x}px`; highlight.style.top = `${clientrect.y}px`; highlight.style.width = `${clientrect.width}px`; highlight.sty...
Range.insertNode() - Web APIs
WebAPIRangeinsertNode
example range = document.createrange(); newnode = document.createelement("p"); newnode.appendchild(document.createtextnode("new node inserted here")); range.selectnode(document.getelementsbytagname("div").item(0)); range.insertnode(newnode); specifications specification status comment domthe definition of 'range.insertnode()' in that specification.
Range.intersectsNode() - Web APIs
example var range = document.createrange(); range.selectnode(document.getelementsbytagname("div").item(0)); var bool = range.intersectsnode(document.getelementsbytagname("p").item(0)); specification specification status comment domthe definition of 'range.intersectnode()' in that specification.
Range.isPointInRange() - Web APIs
example range = document.createrange(); range.selectnode(document.getelementsbytagname("div").item(0)); bool = range.ispointinrange(document.getelementsbytagname("p").item(0),1); specification specification status comment domthe definition of 'range.ispointinrange()' in that specification.
Range.selectNode() - Web APIs
WebAPIRangeselectNode
example let range = document.createrange(); let referencenode = document.getelementsbytagname('div').item(0); range.selectnode(referencenode); specifications specification status comment domthe definition of 'range.selectnode()' in that specification.
Range.setEnd() - Web APIs
WebAPIRangesetEnd
example const range = document.createrange(); const endnode = document.getelementsbytagname('p').item(3); const endoffset = endnode.childnodes.length; range.setend(endnode, endoffset); setend() is commonly used in conjunction with setstart() to fully configure a range.
Range.setEndAfter() - Web APIs
WebAPIRangesetEndAfter
example var range = document.createrange(); var referencenode = document.getelementsbytagname('div').item(0); range.setendafter(referencenode); specifications specification status comment domthe definition of 'range.setendafter()' in that specification.
Range.setEndBefore() - Web APIs
example var range = document.createrange(); var referencenode = document.getelementsbytagname("div").item(0); range.setendbefore(referencenode); specifications specification status comment domthe definition of 'range.setendbefore()' in that specification.
Range.setStartAfter() - Web APIs
example var range = document.createrange(); var referencenode = document.getelementsbytagname("div").item(0); range.setstartafter(referencenode); specifications specification status comment domthe definition of 'range.setstartafter()' in that specification.
Range.setStartBefore() - Web APIs
example var range = document.createrange(); var referencenode = document.getelementsbytagname("div").item(0); range.setstartbefore(referencenode); specifications specification status comment domthe definition of 'range.setstartbefore()' in that specification.
Range.startContainer - Web APIs
syntax startrangenode = range.startcontainer; example range = document.createrange(); range.setstart(startnode,startoffset); range.setend(endnode,endoffset); startrangenode = range.startcontainer; specifications specification status comment domthe definition of 'range.endcontainer' in that specification.
Range.startOffset - Web APIs
WebAPIRangestartOffset
syntax startrangeoffset = range.startoffset; example var range = document.createrange(); range.setstart(startnode,startoffset); range.setend(endnode,endoffset); var startrangeoffset = range.startoffset; specifications specification status comment domthe definition of 'range.startoffset' in that specification.
Range.surroundContents() - Web APIs
example html <span class="header-text">put this in a headline</span> javascript const range = document.createrange(); const newparent = document.createelement('h1'); range.selectnode(document.queryselector('.header-text')); range.surroundcontents(newparent); result specifications specification status comment domthe definition of 'range.surroundcontents()' in that specification.
Range.toString() - Web APIs
WebAPIRangetoString
look at the output below.</p> <p id="log"></p> javascript const range = document.createrange(); range.setstartbefore(document.getelementsbytagname('b').item(0), 0); range.setendafter(document.getelementsbytagname('b').item(1), 0); document.getelementbyid('log').textcontent = range.tostring(); result specifications specification status comment domthe definition of 'range.tostring()' in that specification.
ReadableByteStreamController - Web APIs
readablebytestreamcontroller instances are created automatically during readablestream construction.
ReadableStreamBYOBReader.ReadableStreamBYOBReader() - Web APIs
the readablestreambyobreader() constructor creates and returns a readablestreambyobreader object instance.
ReadableStreamBYOBReader - Web APIs
constructor readablestreambyobreader() creates and returns a readablestreambyobreader object instance.
ReadableStreamBYOBRequest - Web APIs
readablestreambyobrequest instance is created automatically by readablebytestreamcontroller as needed.
ReadableStreamDefaultReader.closed - Web APIs
examples in this snippet, a previously-created reader is queried to see if the stream has been closed.
RelativeOrientationSensor.RelativeOrientationSensor() - Web APIs
the relativeorientationsensor constructor creates a new relativeorientationsensor object which describes the device's physical orientation.
RelativeOrientationSensor - Web APIs
constructor relativeorientationsensor.relativeorientationsensor() creates a new relativeorientationsensor object.
ReportingObserverOptions - Web APIs
buffered a boolean that defines whether the reports that were generated before the observer was able to be created should be observable (true) or not (false).
Request.context - Web APIs
WebAPIRequestcontext
example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request context in a variable: var myrequest = new request('flowers.jpg'); var mycontext = myrequest.context; // returns the empty string by default ...
Request.credentials - Web APIs
example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request credentials in a variable: var myrequest = new request('flowers.jpg'); var mycred = myrequest.credentials; // returns "same-origin" by default specifications specification status comment fetchthe definition of 'credentials' in that specifi...
Request.destination - Web APIs
example in the following snippet, we create a new request using the request() constructor (for an image file in the same directory as the script), then save the request's destination: var myrequest = new request('flowers.jpg'); var mydestination = myrequest.destination; // returns the empty string by default specifications specification status comment fetchthe definition of 'destination' in that specification.
Request.headers - Web APIs
WebAPIRequestheaders
example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request headers in a variable: var myrequest = new request('flowers.jpg'); var myheaders = myrequest.headers; // headers {} to add a header to the headers object we use headers.append; we then create a new request along with a 2nd init parameter, passing headers in as an init option: var myheaders = new headers(); myheaders.append('content-type', 'image/jpeg'); var myinit = { method: 'get', headers: myheaders, mode: 'cors', cache: 'defau...
Request.integrity - Web APIs
WebAPIRequestintegrity
example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request integrity value in a variable: var myrequest = new request('flowers.jpg'); var myintegrity = myrequest.integrity; specifications specification status comment fetchthe definition of 'integrity' in that specification.
Request.method - Web APIs
WebAPIRequestmethod
example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the method of the request in a variable: var myrequest = new request('flowers.jpg'); var mymethod = myrequest.method; // get specifications specification status comment fetchthe definition of 'method' in that specification.
Request.referrer - Web APIs
WebAPIRequestreferrer
example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request referrer in a variable: var myrequest = new request('flowers.jpg'); var myreferrer = myrequest.referrer; // returns "about:client" by default specifications specification status comment fetchthe definition of 'referrer' in that specification.
Request.referrerPolicy - Web APIs
example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request referrer policy in a variable: var myrequest = new request('flowers.jpg'); var myreferrer = myrequest.referrerpolicy; // returns "" by default specifications specification status comment fetchthe definition of 'referrerpolicy' in that spec...
Request.url - Web APIs
WebAPIRequesturl
example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the url of the request in a variable: var myrequest = new request('flowers.jpg'); var myurl = myrequest.url; // "http://mdn.github.io/fetch-examples/fetch-request/flowers.jpg" specifications specification status comment fetchthe definition of 'url' in that specification.
ResizeObserver() - Web APIs
the resizeobserver constructor creates a new resizeobserver object, which can be used to report changes to the content or border box of an element or the bounding box of an svgelement.
Resize Observer API - Web APIs
usage is simple, and pretty much the same as other observers, such as performance observer or intersection observer — you create a new resizeobserver object using the resizeobserver() constructor, then use resizeobserver.observe() to make it look for changes to a specific element's size.
Using the Resource Timing API - Web APIs
the interface's properties create a resource loading timeline with high-resolution timestamps for network events such as redirect start and end times, fetch start, dns lookup start and end times, response start and end times, etc.
Resource Timing API - Web APIs
the interface's properties create a resource loading timeline with high-resolution timestamps for network events such as redirect start and end times, dns lookup start and end times, request start, response start and end times, etc.
SVGAngle - Web APIs
WebAPISVGAngle
every svgangle object operates in one of two modes: reflect the base value of a reflected animatable attribute (being exposed through the baseval member of an svganimatedangle), be detached, which is the case for svgangle objects created with svgsvgelement.createsvgangle().
SVGAnimatedString - Web APIs
you need to create svg attribute before doing anything else, everything should be declared inside this.
Screen.availHeight - Web APIs
let palettewindow = window.open("panels.html", "panels", "left=0, top=0, width=200"); the panels window's html, in panels.html, has javascript code of its own, which is executed as soon as the window is created.
Using the Screen Capture API - Web APIs
unction stopcapture(evt) { let tracks = videoelem.srcobject.gettracks(); tracks.foreach(track => track.stop()); videoelem.srcobject = null; } dumping configuration information for informational purposes, the startcapture() method shown above calls a method named dumpoptions(), which outputs the current track settings as well as the constraints that were placed upon the stream when it was created.
Screen Capture API - Web APIs
similar to getusermedia(), this method creates a promise that resolves with a mediastream containing the display area selected by the user, in a format that matches the specified options.
SecurityPolicyViolationEvent.SecurityPolicyViolationEvent() - Web APIs
the securitypolicyviolationevent constructor creates a new securitypolicyviolationevent object instance.
SecurityPolicyViolationEvent - Web APIs
constructor securitypolicyviolationevent() creates a new securitypolicyviolationevent object instance.
Selection.addRange() - Web APIs
/strong>.</p> <button>select strong words</button> javascript let button = document.queryselector('button'); button.addeventlistener('click', function () { let selection = window.getselection(); let strongs = document.getelementsbytagname('strong'); if (selection.rangecount > 0) { selection.removeallranges(); } for (let i = 0; i < strongs.length; i++) { let range = document.createrange(); range.selectnode(strongs[i]); selection.addrange(range); } }); result specifications specification status comment selection apithe definition of 'selection.addrange()' in that specification.
SensorErrorEvent.SensorErrorEvent() - Web APIs
the sensorerrorevent constructor creates a new sensorerrorevent object which provides information about errors thrown by any of the interfaces based on sensor.
SensorErrorEvent - Web APIs
constructor sensorerrorevent.sensorerrorevent() creates a new sensorerrorevent object.
ServiceWorkerContainer.register() - Web APIs
the register() method of the serviceworkercontainer interface creates or updates a serviceworkerregistration for the given scripturl.
ServiceWorkerContainer - Web APIs
methods serviceworkercontainer.register() creates or updates a serviceworkerregistration for the given scripturl.
ServiceWorkerMessageEvent - Web APIs
constructor serviceworkermessageevent.serviceworkermessageevent() creates a new serviceworkermessageevent object instance.
Slottable: assignedSlot - Web APIs
examples in our simple-template example (see it live), we create a trivial custom element example called <my-paragraph> in which a shadow root is attached and then populated using the contents of a template that contains a slot named my-text.
SourceBuffer.mode - Web APIs
WebAPISourceBuffermode
the mode value is initially set when the sourcebuffer is created using mediasource.addsourcebuffer().
SourceBuffer - Web APIs
cument.queryselector('video'); var asseturl = 'frag_bunny.mp4'; // need to be specific for blink regarding codecs // ./mp4info frag_bunny.mp4 | grep codec var mimecodec = 'video/mp4; codecs="avc1.42e01e, mp4a.40.2"'; if ('mediasource' in window && mediasource.istypesupported(mimecodec)) { var mediasource = new mediasource(); //console.log(mediasource.readystate); // closed video.src = url.createobjecturl(mediasource); mediasource.addeventlistener('sourceopen', sourceopen); } else { console.error('unsupported mime type or codec: ', mimecodec); } function sourceopen (_) { //console.log(this.readystate); // open var mediasource = this; var sourcebuffer = mediasource.addsourcebuffer(mimecodec); fetchab(asseturl, function (buf) { sourcebuffer.addeventlistener('updateend', fun...
SpeechGrammar.SpeechGrammar() - Web APIs
the speechgrammar constructor of the speechgrammar interface creates a new speechgrammar object instance.
SpeechGrammar - Web APIs
constructor speechgrammar.speechgrammar() creates a new speechgrammar object.
SpeechGrammarList.item() - Web APIs
| red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; var myfirstgrammar = speechrecognitionlist[0]; // var should contain the speechgrammar object created in line 4.
SpeechRecognition() - Web APIs
the speechrecognition() constructor creates a new speechrecognition object instance.
SpeechSynthesis.getVoices() - Web APIs
example javascript function populatevoicelist() { if(typeof speechsynthesis === 'undefined') { return; } var voices = speechsynthesis.getvoices(); for(var i = 0; i < voices.length; i++) { var option = document.createelement('option'); option.textcontent = voices[i].name + ' (' + voices[i].lang + ')'; if(voices[i].default) { option.textcontent += ' -- default'; } option.setattribute('data-lang', voices[i].lang); option.setattribute('data-name', voices[i].name); document.getelementbyid("voiceselect").appendchild(option); } } populatevoicelist(); if (typeof speechsynthesis !== ...
SpeechSynthesis.onvoiceschanged - Web APIs
var voices = []; function populatevoicelist() { voices = synth.getvoices(); for(i = 0; i < voices.length ; i++) { var option = document.createelement('option'); option.textcontent = voices[i].name + ' (' + voices[i].lang + ')'; if(voices[i].default) { option.textcontent += ' -- default'; } option.setattribute('data-lang', voices[i].lang); option.setattribute('data-name', voices[i].name); voiceselect.appendchild(option); } } populatevoicelist(); if (speechsynthesis.onvoiceschanged !== undefined) { spe...
SpeechSynthesis.speak() - Web APIs
when a form containing the text we want to speak is submitted, we (amongst other things) create a new utterance containing this text, then speak it by passing it into speak() as a parameter.
SpeechSynthesisVoice.default - Web APIs
examples for(i = 0; i < voices.length ; i++) { var option = document.createelement('option'); option.textcontent = voices[i].name + ' (' + voices[i].lang + ')'; if(voices[i].default) { option.textcontent += ' -- default'; } option.setattribute('data-lang', voices[i].lang); option.setattribute('data-name', voices[i].name); voiceselect.appendchild(option); } specifications specification status comment web speech apithe definition...
SpeechSynthesisVoice.lang - Web APIs
examples for(i = 0; i < voices.length ; i++) { var option = document.createelement('option'); option.textcontent = voices[i].name + ' (' + voices[i].lang + ')'; if(voices[i].default) { option.textcontent += ' -- default'; } option.setattribute('data-lang', voices[i].lang); option.setattribute('data-name', voices[i].name); voiceselect.appendchild(option); } specifications specification status comment web speech apithe definition of 'lang' in that specification.
SpeechSynthesisVoice.localService - Web APIs
examples for(i = 0; i < voices.length ; i++) { var option = document.createelement('option'); option.textcontent = voices[i].name + ' (' + voices[i].lang + ')'; if(voices[i].default) { option.textcontent += ' -- default'; } console.log(voices[i].localservice); option.setattribute('data-lang', voices[i].lang); option.setattribute('data-name', voices[i].name); voiceselect.appendchild(option); } specifications specification status comme...
SpeechSynthesisVoice.name - Web APIs
examples for(i = 0; i < voices.length ; i++) { var option = document.createelement('option'); option.textcontent = voices[i].name + ' (' + voices[i].lang + ')'; if(voices[i].default) { option.textcontent += ' -- default'; } option.setattribute('data-lang', voices[i].lang); option.setattribute('data-name', voices[i].name); voiceselect.appendchild(option); } specifications specification status comment web speech apithe definition of 'name' in that specification.
SpeechSynthesisVoice.voiceURI - Web APIs
examples for(i = 0; i < voices.length ; i++) { var option = document.createelement('option'); option.textcontent = voices[i].name + ' (' + voices[i].lang + ')'; if(voices[i].default) { option.textcontent += ' -- default'; } console.log(voices[i].voiceuri); // on mac, this returns urns, for example 'urn:moz-tts:osx:com.apple.speech.synthesis.voice.daniel' option.setattribute('data-lang', voices[i].lang); option.setattribute('data-name', voices[i].name...
SpeechSynthesisVoice - Web APIs
function populatevoicelist() { voices = synth.getvoices(); for(i = 0; i < voices.length ; i++) { var option = document.createelement('option'); option.textcontent = voices[i].name + ' (' + voices[i].lang + ')'; if(voices[i].default) { option.textcontent += ' -- default'; } option.setattribute('data-lang', voices[i].lang); option.setattribute('data-name', voices[i].name); voiceselect.appendchild(option); } } populatevoicelist(); if (speechsynthesis.onvoiceschanged !== undefined) { spe...
StaticRange.StaticRange() - Web APIs
the staticrange() constructor creates a new staticrange object representing a span of content within the dom.
StaticRange - Web APIs
range" target="_top"><rect x="171" y="1" width="110" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="226" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">staticrange</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor staticrange() creates a new staticrange object given the staticrangeinit dictionary specifying the default values for its properties.
StereoPannerNode.StereoPannerNode() - Web APIs
the stereopannernode() constructor of the web audio api creates a new stereopannernode object which is an audionode that represents a simple stereo panner node that can be used to pan an audio stream left or right.
Storage.clear() - Web APIs
WebAPIStorageclear
examples the following function creates three data entries in local storage, and then deletes them by using clear().
Storage.removeItem() - Web APIs
example the following function creates three data items inside local storage, then removes the image data item.
StylePropertyMapReadOnly - Web APIs
selector('p'); // get the <dl> we'll be populating const styleslist = document.queryselector('#output'); // retrieve all computed styles with computedstylemap() const stylepropertymap = myelement.computedstylemap(); // iterate thru the map of all the properties and values, adding a <dt> and <dd> for each for (const [prop, val] of stylepropertymap) { // properties const cssproperty = document.createelement('dt'); cssproperty.appendchild(document.createtextnode(prop)); styleslist.appendchild(cssproperty); // values const cssvalue = document.createelement('dd'); cssvalue.appendchild(document.createtextnode(val)); styleslist.appendchild(cssvalue); } specifications specification status comment css typed om level 1the definition of 'stylepropertymapreadonly' in ...
SubmitEvent - Web APIs
constructor submitevent() creates and returns a new submitevent object whose type and other options are configured as specified.
SubtleCrypto.digest() - Web APIs
hint: if you are looking here for how to create an keyed-hash message authentication code (hmac), you need to use the subtlecrypto.sign() instead.
SyncEvent.SyncEvent() - Web APIs
the syncevent() constructor creates a new syncevent object.
SyncEvent - Web APIs
WebAPISyncEvent
" target="_top"><rect x="306" y="1" width="90" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="351" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">syncevent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor syncevent.syncevent() creates a new syncevent object.
SyncManager - Web APIs
methods syncmanager.register create a new sync registration and return a promise.
Text.replaceWholeText() - Web APIs
the returned node is the current node unless the current node is read only, in which case the returned node is a newly created text node of the same type which has been inserted at the location of the replacement.
Text - Web APIs
WebAPIText
over time, more text nodes may be created as the document's content changes.
TextDecoder() - Web APIs
the textdecoder() constructor returns a newly created textdecoder object for the encoding specified in parameter.
TextMetrics.actualBoundingBoxAscent - Web APIs
examples const canvas = document.createelement('canvas'); const ctx = canvas.getcontext('2d'); const text = ctx.measuretext('foo'); // returns textmetrics object text.actualboundingboxascent; // 8; specifications specification html living standardthe definition of 'textmetrics.actualboundingboxascent' in that specification.
TextMetrics.actualBoundingBoxDescent - Web APIs
examples const canvas = document.createelement('canvas'); const ctx = canvas.getcontext('2d'); const text = ctx.measuretext('foo'); // returns textmetrics object text.actualboundingboxdescent; // 0; specifications specification html living standardthe definition of 'textmetrics.actualboundingboxdescent' in that specification.
TextMetrics.actualBoundingBoxLeft - Web APIs
examples const canvas = document.createelement('canvas'); const ctx = canvas.getcontext('2d'); const text = ctx.measuretext('foo'); // returns textmetrics object text.actualboundingboxleft; // 0; specifications specification html living standardthe definition of 'textmetrics.actualboundingboxleft' in that specification.
TextMetrics.actualBoundingBoxRight - Web APIs
examples const canvas = document.createelement('canvas'); const ctx = canvas.getcontext('2d'); const text = ctx.measuretext('foo'); // returns textmetrics object text.actualboundingboxright; // 15.633333333333333; specifications specification html living standardthe definition of 'textmetrics.actualboundingboxright' in that specification.
TextMetrics.alphabeticBaseline - Web APIs
examples const canvas = document.createelement('canvas'); const ctx = canvas.getcontext('2d'); const text = ctx.measuretext('foo'); // returns textmetrics object text.alphabeticbaseline; // -0; specifications specification html living standardthe definition of 'textmetrics.alphabeticbaseline' in that specification.
TextMetrics.emHeightAscent - Web APIs
examples const canvas = document.createelement('canvas'); const ctx = canvas.getcontext('2d'); const text = ctx.measuretext('foo'); // returns textmetrics object text.emheightascent; // 7.59765625; specifications specification html living standardthe definition of 'textmetrics.emheightascent' in that specification.
TextMetrics.emHeightDescent - Web APIs
examples const canvas = document.createelement('canvas'); const ctx = canvas.getcontext('2d'); const text = ctx.measuretext('foo'); // returns textmetrics object text.emheightdescent; // -2.40234375; specifications specification html living standardthe definition of 'textmetrics.emheightdescent' in that specification.
TextMetrics.fontBoundingBoxAscent - Web APIs
examples const canvas = document.createelement('canvas'); const ctx = canvas.getcontext('2d'); const text = ctx.measuretext('foo'); // returns textmetrics object text.fontboundingboxascent; // 10; specifications specification html living standardthe definition of 'textmetrics.fontboundingboxascent' in that specification.
TextMetrics.fontBoundingBoxDescent - Web APIs
examples const canvas = document.createelement('canvas'); const ctx = canvas.getcontext('2d'); const text = ctx.measuretext('foo'); // returns textmetrics object text.fontboundingboxdescent; // 3; specifications specification html living standardthe definition of 'textmetrics.fontboundingboxdescent' in that specification.
TextMetrics.hangingBaseline - Web APIs
examples const canvas = document.createelement('canvas'); const ctx = canvas.getcontext('2d'); const text = ctx.measuretext('foo'); // returns textmetrics object text.hangingbaseline; // 6.078125; specifications specification html living standardthe definition of 'textmetrics.hangingbaseline' in that specification.
TextMetrics.ideographicBaseline - Web APIs
examples const canvas = document.createelement('canvas'); const ctx = canvas.getcontext('2d'); const text = ctx.measuretext('foo'); // returns textmetrics object text.ideographicbaseline; // -1.201171875; specifications specification html living standardthe definition of 'textmetrics.ideographicbaseline' in that specification.
TimeEvent - Web APIs
WebAPITimeEvent
methods inittimeevent(domstring typearg, abstractview viewarg, long detailarg) the inittimeevent method is used to initialize the value of a timeevent created through the documentevent interface.
Touch() - Web APIs
WebAPITouchTouch
the touch() constructor creates a new touch object.
Touch - Web APIs
WebAPITouch
constructor touch() creates a touch object.
TouchEvent() - Web APIs
the touchevent() constructor creates a new touchevent.
TouchEvent.altKey - Web APIs
WebAPITouchEventaltKey
summary a boolean value indicating whether or not the alt (alternate) key is enabled when the touch event is created.
TouchEvent.ctrlKey - Web APIs
summary a boolean value indicating whether the control (control) key is enabled when the touch event is created.
TouchEvent.metaKey - Web APIs
summary a boolean value indicating whether or not the meta key is enabled when the touch event is created.
TouchEvent.shiftKey - Web APIs
summary a boolean value indicating whether or not the shift key is enabled when the touch event is created.
TouchEvent - Web APIs
chevent" target="_top"><rect x="231" y="1" width="100" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="281" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">touchevent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor touchevent() creates a touchevent object.
Supporting both TouchEvent and MouseEvent - Web APIs
the touch interfaces enable applications to create enhanced user experiences on touch enabled devices.
TrackEvent - Web APIs
constructor trackevent() creates and initializes a new trackevent object with the event type specified, as well as optional additional properties.
TransformStream - Web APIs
constructor transformstream() creates and returns a transform stream object from the given handlers.
TransitionEvent() - Web APIs
the transitionevent() constructor returns a newly created transitionevent, representing an event in relation with an transition.
TreeWalker.currentNode - Web APIs
syntax node = treewalker.currentnode; treewalker.currentnode = node; example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); root = treewalker.currentnode; // the root element as it is the first element!
TreeWalker.expandEntityReferences - Web APIs
syntax expand = treewalker.expandentityreferences; example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); expand = treewalker.expandentityreferences; specifications document object model (dom) level 2 traversal and range specificationthe definition of 'treewalker.expandentityreferences' in that specification.
TreeWalker.filter - Web APIs
WebAPITreeWalkerfilter
syntax nodefilter = treewalker.filter; example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); nodefilter = treewalker.filter; // document.body in this case specifications specification status comment domthe definition of 'treewalker.filter' in that specification.
TreeWalker.firstChild() - Web APIs
syntax node = treewalker.firstchild; example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); var node = treewalker.firstchild(); // returns the first child of the root element, or null if none specifications specification status comment domthe definition of 'treewalker.firstchild' in that specification.
TreeWalker.lastChild() - Web APIs
syntax node = treewalker.lastchild(); example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); var node = treewalker.lastchild(); // returns the last visible child of the root element specifications specification status comment domthe definition of 'treewalker.lastchild' in that specification.
TreeWalker.nextNode() - Web APIs
syntax node = treewalker.nextnode(); example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); var node = treewalker.nextnode(); // returns the first child of root, as it is the next node in document order specifications specification status comment domthe definition of 'treewalker.nextnode' in that specification.
TreeWalker.nextSibling() - Web APIs
syntax node = treewalker.nextsibling(); example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); treewalker.firstchild(); var node = treewalker.nextsibling(); // returns null if the first child of the root element has no sibling specifications specification status comment domthe definition of 'treewalker.nextsibling' in that specification.
TreeWalker.parentNode() - Web APIs
syntax node = treewalker.parentnode(); example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); var node = treewalker.parentnode(); // returns null as there is no parent specifications specification status comment domthe definition of 'treewalker.parentnode' in that specification.
TreeWalker.previousNode() - Web APIs
syntax node = treewalker.previousnode(); example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); var node = treewalker.previousnode(); // returns null as there is no parent specifications specification status comment domthe definition of 'treewalker.previousnode' in that specification.
TreeWalker.previousSibling() - Web APIs
syntax node = treewalker.previoussibling(); example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); var node = treewalker.previoussibling(); // returns null as there is no previous sibiling specifications specification status comment domthe definition of 'treewalker.previoussibling' in that specification.
TreeWalker.root - Web APIs
WebAPITreeWalkerroot
syntax root = treewalker.root; example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); root = treewalker.root; // document.body in this case specifications specification status comment domthe definition of 'treewalker.root' in that specification.
TreeWalker.whatToShow - Web APIs
syntax nodetypes = treewalker.whattoshow; example var treewalker = document.createtreewalker( document.body, nodefilter.show_element + nodefilter.show_comment + nodefilter.show_text, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); if( (treewalker.whattoshow == nodefilter.show_all) || (treewalker.whattoshow % (nodefilter.show_comment*2)) >= nodefilter.show_comment) { // treewalker will show comments } specifications ...
UIEvent() - Web APIs
WebAPIUIEventUIEvent
the uievent() constructor creates a new uievent.
URL() - Web APIs
WebAPIURLURL
the url() constructor returns a newly created url object representing the url defined by the parameters.
URLSearchParams.entries() - Web APIs
examples // create a test urlsearchparams object var searchparams = new urlsearchparams("key1=value1&key2=value2"); // display the key/value pairs for(var pair of searchparams.entries()) { console.log(pair[0]+ ', '+ pair[1]); } the result is: key1, value1 key2, value2 specifications specification status comment urlthe definition of 'entries() (see "iterable")' in that specification.
URLSearchParams.forEach() - Web APIs
examples // create a test urlsearchparams object var searchparams = new urlsearchparams("key1=value1&key2=value2"); // log the values searchparams.foreach(function(value, key) { console.log(value, key); }); the result is: value1 key1 value2 key2 specifications specification status comment urlthe definition of 'foreach() (see "iterable")' in that specification.
URLSearchParams.keys() - Web APIs
examples // create a test urlsearchparams object var searchparams = new urlsearchparams("key1=value1&key2=value2"); // display the keys for(var key of searchparams.keys()) { console.log(key); } the result is: key1 key2 specifications specification status comment urlthe definition of 'keys() (see "iterable")' in that specification.
URLSearchParams.sort() - Web APIs
examples // create a test urlsearchparams object var searchparams = new urlsearchparams("c=4&a=2&b=3&a=1"); // sort the key/value pairs searchparams.sort(); // display the sorted query string console.log(searchparams.tostring()); the result is: a=2&a=1&b=3&c=4 specifications specification status comment urlthe definition of 'sort()' in that specification.
URLSearchParams.toString() - Web APIs
params.append('foo', 4); console.log(params.tostring()); //prints 'foo=1&bar=2&foo=4' // note: params can also be directly created let url = new url('https://example.com?foo=1&bar=2'); let params = url.searchparams; // or even simpler let params = new urlsearchparams('foo=1&bar=2'); specifications specification status comment urlthe definition of 'tostring() (see "stringifier")' in that specification.
URLSearchParams.values() - Web APIs
examples // create a test urlsearchparams object var searchparams = new urlsearchparams("key1=value1&key2=value2"); // display the values for(var value of searchparams.values()) { console.log(value); } the result is: value1 value2 specifications specification status comment urlthe definition of 'values() (see "iterable")' in that specification.
USBAlternateInterface - Web APIs
constructor usbalternateinterface.usbalternateinterface creates a new usbalternateinterface object which will be populated with information about the alternate interface of the provided usbinterface with the given alternate setting number.
USBConfiguration.USBConfiguration() - Web APIs
the usbconfiguration() constructor creates a new usbconfiguration object which contains information about the configuration on the provided usbdevice with the given configuration value.
USBConfiguration - Web APIs
constructor usbconfiguration.usbconfiguration() creates a new usbconfiguration object which contains information about the configuration on the provided usbdevice with the given configuration value.
USBEndpoint - Web APIs
constructor usbendpoint.usbendpoint creates a new usbendpoint object which will be populated with information about the endpoint on the provided usbaltenateinterface with the given endpoint number and transfer direction.
USBInTransferResult - Web APIs
constructor usbintransferresult.usbintransferresult() creates a new usbintransferresult object with the provided status and data fields.
USBInterface - Web APIs
constructor usbinterface.usbinterface creates a new usbinterface object which will be populated with information about the interface on the provided usbconfiguration with the given interface number.
USBIsochronousInTransferPacket - Web APIs
constructor usbisochronousintransferpacket.usbisochronousintransferpacket() creates a new usbisochronousintransferpacket object with the provided status and data fields.
USBIsochronousInTransferResult - Web APIs
constructor usbisochronousintransferresult.usbisochronousintransferresult() creates a new usbisochronousintransferresult object with the provided packets and data fields.
USBIsochronousOutTransferPacket - Web APIs
constructor usbisochronousouttransferpacket.usbisochronousouttransferpacket() creates a new usbisochronousouttransferpacket object with the provided status and byteswritten fields.
USBIsochronousOutTransferResult - Web APIs
constructor usbisochronousouttransferresult.usbisochronousouttransferresult() creates a new usbisochronousouttransferresult object with the provided packet field.
USBOutTransferResult - Web APIs
constructor usbouttransferresult.usbouttransferresult() creates a new usbouttransferresult object with the provided status and byteswritten fields.
VTTCue - Web APIs
WebAPIVTTCue
constructor vttcue(starttime, endtime, text) returns a newly created vttcue object that covers the given time range and has the given text.
VTTRegion - Web APIs
WebAPIVTTRegion
constructor vttregion() returns a newly created vttregion object.
Vibration API - Web APIs
continued vibrations some basic setinterval and clearinterval action will allow you to create persistent vibration: var vibrateinterval; // starts vibration at passed in level function startvibrate(duration) { navigator.vibrate(duration); } // stops vibration function stopvibrate() { // clear interval and stop persistent vibrating if(vibrateinterval) clearinterval(vibrateinterval); navigator.vibrate(0); } // start persistent vibration at given duration and interval // ...
VideoConfiguration - Web APIs
examples // create media configuration to be tested const mediaconfig = { type : 'file', // see mediadecodingconfiguration and mediaencodingconfiguration video : { contenttype : "video/webm;codecs=vp8", // valid content type width : 800, // width of the video height : 600, // height of the video bitrate : 10000, // number of bits used to encode 1s of video fra...
VideoTrack.sourceBuffer - Web APIs
the read-only videotrack property sourcebuffer returns the sourcebuffer that created the track, or null if the track was not created by a sourcebuffer or the sourcebuffer has been removed from the mediasource.sourcebuffers attribute of its parent media source.
WEBGL_compressed_texture_astc - Web APIs
compressed_srgb8_alpha8_astc_12x10_khr 12x10 1.07 floor((width + 11) / 12) * floor((height + 9) / 10) * 16 35776 ext.compressed_rgba_astc_12x12_khr ext.compressed_srgb8_alpha8_astc_12x12_khr 12x12 0.89 floor((width + 11) / 12) * floor((height + 11) / 12) * 16 29584 examples var ext = gl.getextension('webgl_compressed_texture_astc'); var texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); gl.compressedteximage2d(gl.texture_2d, 0, ext.compressed_rgba_astc_12x12_khr, 512, 512, 0, texturedata); specifications specification status comment webgl_compressed_texture_astcthe definition of 'webgl_compressed_texture_astc' in that specification.
WEBGL_compressed_texture_atc - Web APIs
examples var ext = gl.getextension('webgl_compressed_texture_atc'); var texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); gl.compressedteximage2d(gl.texture_2d, 0, ext.compressed_rgb_atc_webgl, 512, 512, 0, texturedata); specifications specification status comment webgl_compressed_texture_atcthe definition of 'webgl_compressed_texture_atc' in that specification.
WEBGL_compressed_texture_etc - Web APIs
examples var ext = gl.getextension('webgl_compressed_texture_etc'); var texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); gl.compressedteximage2d(gl.texture_2d, 0, ext.compressed_rgba8_etc2_eac, 512, 512, 0, texturedata); specifications specification status comment webgl_compressed_texture_etcthe definition of 'webgl_compressed_texture_etc' in that specification.
WEBGL_compressed_texture_etc1 - Web APIs
examples var ext = gl.getextension('webgl_compressed_texture_etc1'); var texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); gl.compressedteximage2d(gl.texture_2d, 0, ext.compressed_rgb_etc1_webgl, 512, 512, 0, texturedata); specifications specification status comment webgl_compressed_texture_etc1the definition of 'webgl_compressed_texture_etc1' in that specification.
WEBGL_compressed_texture_pvrtc - Web APIs
examples var ext = gl.getextension('webgl_compressed_texture_pvrtc'); var texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); gl.compressedteximage2d(gl.texture_2d, 0, ext.compressed_rgb_pvrtc_4bppv1_img, 512, 512, 0, texturedata); specifications specification status comment webgl_compressed_texture_pvrtcthe definition of 'webgl_compressed_texture_pvrtc' in that specification.
WEBGL_compressed_texture_s3tc - Web APIs
examples var ext = ( gl.getextension('webgl_compressed_texture_s3tc') || gl.getextension('moz_webgl_compressed_texture_s3tc') || gl.getextension('webkit_webgl_compressed_texture_s3tc') ); var texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); gl.compressedteximage2d(gl.texture_2d, 0, ext.compressed_rgba_s3tc_dxt5_ext, 512, 512, 0, texturedata); gl.texparameteri(gl.texture_2d, gl.texture_mag_filter, gl.linear); gl.texparameteri(gl.texture_2d, gl.texture_min_filter, gl.linear); specifications specification status comment webgl_compressed_texture_s3tcthe defini...
WEBGL_compressed_texture_s3tc_srgb - Web APIs
examples var ext = gl.getextension('webgl_compressed_texture_s3tc_srgb'); var texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); gl.compressedteximage2d(gl.texture_2d, 0, ext.compressed_srgb_s3tc_dxt1_ext, 512, 512, 0, texturedata); gl.texparameteri(gl.texture_2d, gl.texture_mag_filter, gl.linear); gl.texparameteri(gl.texture_2d, gl.texture_min_filter, gl.linear); specifications specification status comment webgl_compressed_texture_s3tc_srgbthe d...
WEBGL_debug_shaders.getTranslatedShaderSource() - Web APIs
examples var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var shader = gl.createshader(gl.fragment_shader); gl.shadersource(shader, 'void main() { gl_fragcolor = vec4(gl_fragcoord.x, 0.0, 0.0, 1.0); }'); gl.compileshader(shader); var src = gl.getextension('webgl_debug_shaders').gettranslatedshadersource(shader); console.log(src); // "void main(){ // (gl_fragcolor = vec4(gl_fragcoord.x, 0.0, 0.0, 1.0)); // }" specifications specification status comment ...
WEBGL_draw_buffers - Web APIs
examples enabling the extension: var ext = gl.getextension('webgl_draw_buffers'); binding multiple textures (to a tx[] array) to different framebuffer color attachments: var fb = gl.createframebuffer(); gl.bindframebuffer(gl.framebuffer, fb); gl.framebuffertexture2d(gl.framebuffer, ext.color_attachment0_webgl, gl.texture_2d, tx[0], 0); gl.framebuffertexture2d(gl.framebuffer, ext.color_attachment1_webgl, gl.texture_2d, tx[1], 0); gl.framebuffertexture2d(gl.framebuffer, ext.color_attachment2_webgl, gl.texture_2d, tx[2], 0); gl.framebuffertexture2d(gl.framebuffer, ext.color_attachment...
WaveShaperNode.WaveShaperNode() - Web APIs
the waveshapernode() constructor of the web audio api creates a new waveshapernode object which is an audionode that represents a non-linear distorter.
WebGL2RenderingContext.beginQuery() - Web APIs
examples var query = gl.createquery(); gl.beginquery(gl.any_samples_passed, query); // ...
WebGL2RenderingContext.beginTransformFeedback() - Web APIs
examples var transformfeedback = gl.createtransformfeedback(); gl.bindtransformfeedback(gl.transform_feedback, transformfeedback); gl.begintransformfeedback(gl.triangles); gl.drawarrays(gl.triangles, 0, 3); specifications specification status comment webgl 2.0the definition of 'begintransformfeedback' in that specification.
WebGL2RenderingContext.bindSampler() - Web APIs
examples var sampler = gl.createsampler(); gl.bindsampler(0, sampler); specifications specification status comment webgl 2.0the definition of 'bindsampler' in that specification.
WebGL2RenderingContext.bindTransformFeedback() - Web APIs
examples var transformfeedback = gl.createtransformfeedback(); gl.bindtransformfeedback(gl.transform_feedback, transformfeedback); specifications specification status comment webgl 2.0the definition of 'bindtransformfeedback' in that specification.
WebGL2RenderingContext.bindVertexArray() - Web APIs
examples var vao = gl.createvertexarray(); gl.bindvertexarray(vao); // ...
WebGL2RenderingContext.copyBufferSubData() - Web APIs
examples var srcbuffer = gl.createbuffer(); var dstbuffer = gl.createbuffer(); var data = new float32array(vertices); var length = vertices.length * 4; gl.bindbuffer(gl.array_buffer, srcbuffer); gl.bufferdata(gl.array_buffer, data, gl.static_draw); gl.bindbuffer(gl.copy_read_buffer, srcbuffer); gl.bindbuffer(gl.array_buffer, dstbuffer); gl.bufferdata(gl.array_buffer, new float32array(length), gl.static_draw); gl.copybuffersubd...
WebGL2RenderingContext.deleteQuery() - Web APIs
var query = gl.createquery(); // ...
WebGL2RenderingContext.deleteSampler() - Web APIs
var sampler = gl.createsampler(); // ...
WebGL2RenderingContext.deleteTransformFeedback() - Web APIs
var transformfeedback = gl.createtransformfeedback(); // ...
WebGL2RenderingContext.deleteVertexArray() - Web APIs
examples var vao = gl.createvertexarray(); gl.bindvertexarray(vao); // ...
WebGL2RenderingContext.endQuery() - Web APIs
examples var query = gl.createquery(); gl.beginquery(gl.any_samples_passed, query); // ...
WebGL2RenderingContext.endTransformFeedback() - Web APIs
examples var transformfeedback = gl.createtransformfeedback(); gl.bindtransformfeedback(gl.transform_feedback, transformfeedback); gl.begintransformfeedback(gl.triangles); gl.drawarrays(gl.triangles, 0, 3); gl.endtransformfeedback(); specifications specification status comment webgl 2.0the definition of 'endtransformfeedback' in that specification.
WebGL2RenderingContext.fenceSync() - Web APIs
the webgl2renderingcontext.fencesync() method of the webgl 2 api creates a new webglsync object and inserts it into the gl command stream.
WebGL2RenderingContext.getBufferSubData() - Web APIs
examples var buffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, buffer); gl.bufferdata(gl.array_buffer, new float32array(vertices), gl.static_draw); var arrbuffer = new arraybuffer(vertices.length * float32array.bytes_per_element); gl.getbuffersubdata(gl.array_buffer, 0, arrbuffer); specifications specification status comment webgl 2.0the definition of 'getbuffersubdata' in that specification...
WebGL2RenderingContext.getQueryParameter() - Web APIs
examples var query = gl.createquery(); gl.beginquery(gl.any_samples_passed, query); var result = gl.getqueryparameter(query, gl.query_result); specifications specification status comment webgl 2.0the definition of 'getqueryparameter' in that specification.
WebGL2RenderingContext.getSamplerParameter() - Web APIs
examples var sampler = gl.createsampler(); gl.getsamplerparameter(sampler, gl.texture_compare_func); specifications specification status comment webgl 2.0the definition of 'getsamplerparameter' in that specification.
WebGL2RenderingContext.getSyncParameter() - Web APIs
gl.sync_flags: returns a glenum indicating the flags with which the sync object was created (always 0 as no flags are supported).
WebGL2RenderingContext.isQuery() - Web APIs
var query = gl.createquery(); // ...
WebGL2RenderingContext.isSampler() - Web APIs
var sampler = gl.createsampler(); // ...
WebGL2RenderingContext.isTransformFeedback() - Web APIs
var transformfeedback = gl.createtransformfeedback(); // ...
WebGL2RenderingContext.isVertexArray() - Web APIs
examples var vao = gl.createvertexarray(); gl.bindvertexarray(vao); // ...
WebGL2RenderingContext.pauseTransformFeedback() - Web APIs
examples var transformfeedback = gl.createtransformfeedback(); gl.bindtransformfeedback(gl.transform_feedback, transformfeedback); gl.begintransformfeedback(gl.triangles); gl.pausetransformfeedback(); //...
WebGL2RenderingContext.renderbufferStorageMultisample() - Web APIs
the webgl2renderingcontext.renderbufferstoragemultisample() method of the webgl 2 api returns creates and initializes a renderbuffer object's data store and allows specifying a number of samples to be used.
WebGL2RenderingContext.resumeTransformFeedback() - Web APIs
examples var transformfeedback = gl.createtransformfeedback(); gl.bindtransformfeedback(gl.transform_feedback, transformfeedback); gl.begintransformfeedback(gl.triangles); gl.pausetransformfeedback(); //...
WebGL2RenderingContext.samplerParameter[if]() - Web APIs
examples var sampler = gl.createsampler(); gl.samplerparameteri(sampler, gl.texture_mag_filter, gl.nearest); specifications the compatibility table in this page is generated from structured data.
WebGL2RenderingContext.transformFeedbackVaryings() - Web APIs
examples var transformfeedback = gl.createtransformfeedback(); gl.bindtransformfeedback(gl.transform_feedback, transformfeedback); var transformfeedbackoutputs = ['gl_position', 'anotheroutput']; gl.transformfeedbackvaryings(shaderprog, transformfeedbackoutputs, gl.interleaved_attribs); gl.linkprogram(shaderprog); specifications specification status comment webgl 2.0the definition o...
WebGLBuffer - Web APIs
when working with webglbuffer objects, the following methods of the webglrenderingcontext are useful: webglrenderingcontext.bindbuffer() webglrenderingcontext.createbuffer() webglrenderingcontext.deletebuffer() webglrenderingcontext.isbuffer() examples creating a buffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var buffer = gl.createbuffer(); specifications specification status comment webgl 1.0the definition of 'webglbuffer' in that specification.
WebGLFramebuffer - Web APIs
when working with webglframebuffer objects, the following methods of the webglrenderingcontext are useful: webglrenderingcontext.bindframebuffer() webglrenderingcontext.createframebuffer() webglrenderingcontext.deleteframebuffer() webglrenderingcontext.isframebuffer() examples creating a frame buffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var buffer = gl.createframebuffer(); specifications specification status comment webgl 1.0the definition of 'webglframebuffer' in that specification.
WebGLRenderbuffer - Web APIs
when working with webglrenderbuffer objects, the following methods of the webglrenderingcontext are useful: webglrenderingcontext.bindrenderbuffer() webglrenderingcontext.createrenderbuffer() webglrenderingcontext.deleterenderbuffer() webglrenderingcontext.isrenderbuffer() examples creating a render buffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var buffer = gl.createrenderbuffer(); specifications specification status comment webgl 1.0the definition of 'webglrenderbuffer' in that specification.
WebGLRenderingContext.attachShader() - Web APIs
var program = gl.createprogram(); // attach pre-existing shaders gl.attachshader(program, vertexshader); gl.attachshader(program, fragmentshader); gl.linkprogram(program); if ( !gl.getprogramparameter( program, gl.link_status) ) { var info = gl.getprograminfolog(program); throw 'could not compile webgl program.
WebGLRenderingContext.bindBuffer() - Web APIs
examples binding a buffer to a target var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var buffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, buffer); getting current bindings to check the current buffer bindings, query the array_buffer_binding and element_array_buffer_binding constants.
WebGLRenderingContext.bindFramebuffer() - Web APIs
examples binding a frame buffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var framebuffer = gl.createframebuffer(); gl.bindframebuffer(gl.framebuffer, framebuffer); getting current bindings to check the current frame buffer binding, query the framebuffer_binding constant.
WebGLRenderingContext.bindRenderbuffer() - Web APIs
examples binding a renderbuffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var renderbuffer = gl.createrenderbuffer(); gl.bindrenderbuffer(gl.renderbuffer, renderbuffer); getting current bindings to check the current renderbuffer binding, query the renderbuffer_binding constant.
WebGLRenderingContext.bindTexture() - Web APIs
examples binding a texture var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); getting current bindings to check the current texture binding, query the gl.texture_binding_2d or gl.texture_binding_cube_map constants.
WebGLRenderingContext.bufferSubData() - Web APIs
examples using buffersubdata var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var buffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, buffer); gl.bufferdata(gl.array_buffer, 1024, gl.static_draw); gl.buffersubdata(gl.array_buffer, 512, data); specifications specification status comment webgl 1.0the definition of 'buffersubdata' in that specification.
WebGLRenderingContext.checkFramebufferStatus() - Web APIs
examples var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var framebuffer = gl.createframebuffer(); // ...
WebGLRenderingContext.commit() - Web APIs
syntax void webglrenderingcontext.commit() examples var htmlcanvas = document.createelement('canvas'); var offscreen = htmlcanvas.transfercontroltooffscreen(); var gl = offscreen.getcontext('webgl'); // ...
WebGLRenderingContext.compileShader() - Web APIs
examples var shader = gl.createshader(gl.vertex_shader); gl.shadersource(shader, shadersource); gl.compileshader(shader); specifications specification status comment webgl 1.0the definition of 'compileshader' in that specification.
WebGLRenderingContext.compressedTexImage[23]D() - Web APIs
examples var ext = ( gl.getextension('webgl_compressed_texture_s3tc') || gl.getextension('moz_webgl_compressed_texture_s3tc') || gl.getextension('webkit_webgl_compressed_texture_s3tc') ); var texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); gl.compressedteximage2d(gl.texture_2d, 0, ext.compressed_rgba_s3tc_dxt5_ext, 512, 512, 0, texturedata); gl.texparameteri(gl.texture_2d, gl.texture_mag_filter, gl.linear); gl.texparameteri(gl.texture_2d, gl.texture_min_filter, gl.linear); specifications specification status comment webgl 1.0the definition of 'compressedte...
WebGLRenderingContext.deleteBuffer() - Web APIs
examples deleting a buffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var buffer = gl.createbuffer(); // ...
WebGLRenderingContext.deleteFramebuffer() - Web APIs
examples deleting a frame buffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var framebuffer = gl.createframebuffer(); // ...
WebGLRenderingContext.deleteProgram() - Web APIs
examples deleting a program var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var program = gl.createprogram(); // ...
WebGLRenderingContext.deleteRenderbuffer() - Web APIs
examples deleting a renderbuffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var renderbuffer = gl.createrenderbuffer(); // ...
WebGLRenderingContext.deleteTexture() - Web APIs
examples deleting a texture var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var texture = gl.createtexture(); // ...
WebGLRenderingContext.enableVertexAttribArray() - Web APIs
others are assigned by the webgl layer when you create the attributes.
WebGLRenderingContext.getActiveUniform() - Web APIs
gl.sampler_3d gl.sampler_cube gl.sampler_2d_shadow gl.sampler_2d_array gl.sampler_2d_array_shadow gl.sampler_cube_shadow gl.int_sampler_2d gl.int_sampler_3d gl.int_sampler_cube gl.int_sampler_2d_array gl.unsigned_int_sampler_2d gl.unsigned_int_sampler_3d gl.unsigned_int_sampler_cube gl.unsigned_int_sampler_2d_array when gl.linkprogram is called, webgl creates a list of active uniforms.
WebGLRenderingContext.getAttachedShaders() - Web APIs
examples var program = gl.createprogram(); // attach pre-existing shaders gl.attachshader(program, vertexshader); gl.attachshader(program, fragmentshader); gl.linkprogram(program); gl.getattachedshaders(program); specifications specification status comment webgl 1.0the definition of 'getattachedshaders' in that specification.
WebGLRenderingContext.getShaderInfoLog() - Web APIs
when a webglshader object is initially created, its information log will be a string of length 0.
WebGLRenderingContext.getShaderSource() - Web APIs
examples var shader = gl.createshader(gl.vertex_shader); gl.shadersource(shader, originalsource); var source = gl.getshadersource(shader); specifications specification status comment webgl 1.0the definition of 'getshadersource' in that specification.
WebGLRenderingContext.isBuffer() - Web APIs
examples creating a buffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var buffer = gl.createbuffer(); gl.isbuffer(buffer); specifications specification status comment webgl 1.0the definition of 'isbuffer' in that specification.
WebGLRenderingContext.isFramebuffer() - Web APIs
examples checking a frame buffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var framebuffer = gl.createframebuffer(); gl.isframebuffer(framebuffer); specifications specification status comment webgl 1.0the definition of 'isframebuffer' in that specification.
WebGLRenderingContext.isProgram() - Web APIs
examples checking a program var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var program = gl.createprogram(); // ...
WebGLRenderingContext.isRenderbuffer() - Web APIs
examples checking a renderbuffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var renderbuffer = gl.createrenderbuffer(); gl.isrenderbuffer(renderbuffer); specifications specification status comment webgl 1.0the definition of 'isrenderbuffer' in that specification.
WebGLRenderingContext.isShader() - Web APIs
examples checking a shader var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var shader = gl.createshader(gl.vertex_shader); // ...
WebGLRenderingContext.isTexture() - Web APIs
examples checking a texture var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var texture = gl.createtexture(); gl.istexture(texture); specifications specification status comment webgl 1.0the definition of 'istexture' in that specification.
WebGLRenderingContext.linkProgram() - Web APIs
examples var program = gl.createprogram(); // attach pre-existing shaders gl.attachshader(program, vertexshader); gl.attachshader(program, fragmentshader); gl.linkprogram(program); if ( !gl.getprogramparameter( program, gl.link_status) ) { var info = gl.getprograminfolog(program); throw new error('could not compile webgl program.
WebGLRenderingContext.pixelStorei() - Web APIs
var tex = gl.createtexture(); gl.bindtexture(gl.texture_2d, tex); gl.pixelstorei(gl.pack_alignment, 4); to check the values for packing and unpacking of pixel data, you can query the same pixel storage parameters with webglrenderingcontext.getparameter().
WebGLRenderingContext.polygonOffset() - Web APIs
units a glfloat which sets the multiplier by which an implementation-specific value is multiplied with to create a constant depth offset.
WebGLRenderingContext.renderbufferStorage() - Web APIs
the webglrenderingcontext.renderbufferstorage() method of the webgl api creates and initializes a renderbuffer object's data store.
WebGLRenderingContext.shaderSource() - Web APIs
examples var shader = gl.createshader(gl.vertex_shader); gl.shadersource(shader, originalsource); var source = gl.getshadersource(shader); specifications specification status comment webgl 1.0the definition of 'shadersource' in that specification.
WebGLRenderingContext.useProgram() - Web APIs
examples var program = gl.createprogram(); // attach pre-existing shaders gl.attachshader(program, vertexshader); gl.attachshader(program, fragmentshader); gl.linkprogram(program); gl.useprogram(program); specifications specification status comment webgl 1.0the definition of 'useprogram' in that specification.
WebGLRenderingContext.validateProgram() - Web APIs
examples var program = gl.createprogram(); // attach pre-existing shaders gl.attachshader(program, vertexshader); gl.attachshader(program, fragmentshader); gl.linkprogram(program); gl.validateprogram(program); if ( !gl.getprogramparameter( program, gl.link_status) ) { var info = gl.getprograminfolog(program); throw 'could not compile webgl program.
WebGLRenderingContext.vertexAttrib[1234]f[v]() - Web APIs
for example, if you have a shader which has a color vertex attribute, but you want to draw everything in a single color, you can use vertexattrib to achieve that without creating a buffer filled with only one value or having to create a separate shader which uses a uniform for the color.
WebGLRenderingContext.viewport() - Web APIs
examples when you first create a webgl context, the size of the viewport will match the size of the canvas.
WebGLTexture - Web APIs
when working with webgltexture objects, the following methods of the webglrenderingcontext are useful: webglrenderingcontext.bindtexture() webglrenderingcontext.createtexture() webglrenderingcontext.deletetexture() webglrenderingcontext.istexture() examples creating a texture var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var texture = gl.createtexture(); specifications specification status comment webgl 1.0the definition of 'webgltexture' in that specification.
Raining rectangles - Web APIs
// increment score and create a new rectangle.
Simple color animation - Web APIs
« previousnext » a very basic color animation created using webgl, performed by clearing the drawing buffer with a different random color every second.
Data in WebGL - Web APIs
WebAPIWebGL APIData
s = [ vec4( 0.0, 0.0, 0.0, 1.0 ), // black vec4( 1.0, 0.0, 0.0, 1.0 ), // red vec4( 1.0, 1.0, 0.0, 1.0 ), // yellow vec4( 0.0, 1.0, 0.0, 1.0 ), // green vec4( 0.0, 0.0, 0.0, 1.0 ), // black vec4( 1.0, 0.0, 0.0, 1.0 ), // red vec4( 1.0, 1.0, 0.0, 1.0 ), // yellow vec4( 0.0, 1.0, 0.0, 1.0 ), // green ]; var cbuffer = gl.createbuffer(); //continued //create buffer to store colors and reference it to "vcolor" which is in glsl gl.bindbuffer( gl.array_buffer, cbuffer ); gl.bufferdata( gl.array_buffer, flatten(vertexcolors), gl.static_draw ); var vcolor = gl.getattriblocation( program, "vcolor" ); gl.vertexattribpointer( vcolor, 4, gl.float, false, 0, 0 ); gl.enablevertexattribarray( vcolor ); /...
Animating objects with WebGL - Web APIs
you'll need to include it if you create your own project based on this code.
WebRTC coding guide - Web APIs
how do you create a web application that uses two-way video or data streams without having to do all the hard work of compressing frames, building streams, and so forth by yourself?
WebRTC Statistics API - Web APIs
in this example, a new rtcpeerconnection is created, and then setinterval() is used to set the function getconnectionstats() to be called every second.
WebSocket: error event - Web APIs
bubbles no cancelable no interface event event handler property onerror examples // create websocket connection const socket = new websocket('ws://localhost:8080'); // listen for possible errors socket.addeventlistener('error', function (event) { console.log('websocket error: ', event); }); specifications specification status html living standardthe definition of 'websocket error' in that specification.
WebSocket: message event - Web APIs
bubbles no cancelable no interface messageevent event handler property onmessage examples // create websocket connection.
WebSocket: open event - Web APIs
bubbles no cancelable no interface event event handler property onopen examples // create websocket connection.
WebSocket.readyState - Web APIs
syntax var readystate = awebsocket.readystate; value one of the following unsigned short values: value state description 0 connecting socket has been created.
WebXR application life cycle - Web APIs
if your scene is complex, you should consider creating a worker—or using one that you've previously created for this purpose—to perform the computations needed for each frame to be rendered.
WebXR permissions and security - Web APIs
inline presentation when you request an xrsession with the mode set to inline, and any features are required or requested, the browser will only allow the session to be created if the call to requestsession() was made by code which is executing expressly due to user intent.
Tools for analyzing Web Audio usage - Web APIs
while working on your web audio api code, you may find that you need tools to analyze the graph of nodes you create or to otherwise debug your work.
Web Speech API - Web APIs
generally you'll use the interface's constructor to create a new speechrecognition object, which has a number of event handlers available for detecting when speech is input through the device's microphone.
WheelEvent() - Web APIs
the wheelevent() constructor returns a newly created wheelevent object.
WheelEvent - Web APIs
elevent" target="_top"><rect x="371" y="1" width="100" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="421" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">wheelevent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor wheelevent() creates a wheelevent object.
Window.alert() - Web APIs
WebAPIWindowalert
for this reason, you should not overuse any function that creates a dialog box (or modal window).
Window: beforeunload event - Web APIs
to combat unwanted pop-ups, browsers may not display prompts created in beforeunload event handlers unless the page has been interacted with, or may even not display them at all.
Window.close() - Web APIs
WebAPIWindowclose
re a reference to the opened window var openedwindow; function openwindow() { openedwindow = window.open('moreinfo.htm'); } function closeopenedwindow() { openedwindow.close(); } closing the current window in the past, when you called the window object's close() method directly, rather than calling close() on a window instance, the browser closed the frontmost window, whether your script created that window or not.
Window.confirm() - Web APIs
WebAPIWindowconfirm
for this reason, you should not overuse any function that creates a dialog box (or modal window).
Window.dialogArguments - Web APIs
this lets you determine what parameters were specified when the modal dialog was created.
Window.localStorage - Web APIs
(data in a localstorage object created in a "private browsing" or "incognito" session is cleared when the last "private" tab is closed.) data stored in either localstorage is specific to the protocol of the page.
Window.mozPaintCount - Web APIs
the window.mozpaintcount value is a long long, and starts at zero when the document is first created, incrementing by one each time the document is painted.
Window.openDialog() - Web APIs
WebAPIWindowopenDialog
the optional parameters, if present, are bundled up in a javascript array object and added to the newly created window as a property named window.arguments.
Window.opener - Web APIs
WebAPIWindowopener
if this window was not opened by being linked to or created by another, returns null.
Window.pageYOffset - Web APIs
integer euismod lectus a ipsum pellentesque lacinia.</p> `; document.getelementbyid("frame").contentdocument .body.innerhtml = contenthtml; in this example, an <iframe> is created and filled with content, then a specific element within the document is scrolled into view in the frame.
Window.prompt() - Web APIs
WebAPIWindowprompt
for this reason, you should not overuse any function that creates a dialog box (or modal window).
Window.requestFileSystem() - Web APIs
errorcallback optional an optional parameter specifying a function which is called if an error occurs while attempting to obtain the file system, or if the user denies permission to create or access the file system.
Window.showModalDialog() - Web APIs
the window.showmodaldialog() created and displayed a modal dialog box containing a specified html document.
Window: transitionrun event - Web APIs
the transitionrun event is fired when a css transition is first created, i.e.
Window.window - Web APIs
WebAPIWindowwindow
for example, if we refer to "this.window.location.href", a javascript module could define a property called "window" inside of a class it defined (since no global "window" variable exists for it by default) which could be created after passing in a window object to the module class' constructor.
WindowEventHandlers.onbeforeprint - Web APIs
}; polyfill safari does not implement these events, but you can create an equivalent result to the beforeprint event with window.matchmedia('print').
WindowEventHandlers.onbeforeunload - Web APIs
note: to combat unwanted pop-ups, some browsers don't display prompts created in beforeunload event handlers unless the page has been interacted with.
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.
WindowEventHandlers - Web APIs
note: windoweventhandlers is a mixin and not an interface; you can't actually create an object of type windoweventhandlers.
WindowOrWorkerGlobalScope.btoa() - Web APIs
the windoworworkerglobalscope.btoa() method creates a base64-encoded ascii string from a binary string (i.e., a string object in which each character in the string is treated as a byte of binary data).
WindowOrWorkerGlobalScope.indexedDB - Web APIs
example the following code creates a request for a database to be opened asychronously, after which the database is opened when the request's onsuccess handler is fired: var db; function opendb() { var dbopenrequest = window.indexeddb.open('todolist'); dbopenrequest.onsuccess = function(e) { db = dbopenrequest.result; } } specifications specification status comment indexed database api draftthe definition of 'indexeddb' in that specification.
WindowOrWorkerGlobalScope.queueMicrotask() - Web APIs
it creates a microtask by using a promise that resolves immediately.
WindowOrWorkerGlobalScope.setInterval() - Web APIs
return value the returned intervalid is a numeric, non-zero value which identifies the timer created by the call to setinterval(); this value can be passed to windoworworkerglobalscope.clearinterval() to cancel the timeout.
WindowOrWorkerGlobalScope.setTimeout() - Web APIs
return value the returned timeoutid is a positive integer value which identifies the timer created by the call to settimeout(); this value can be passed to cleartimeout() to cancel the timeout.
Worker: message event - Web APIs
bubbles no cancelable no interface messageevent event handler property onmessage examples this code creates a new worker and listens to messages from it using addeventlistener(): const worker = new worker("static/scripts/worker.js"); worker.addeventlistener('message', (event) => { console.log(`received message from worker: ${event.data}`) }); alternatively, it could listen using the onmessage event handler property: const worker = new worker("static/scripts/worker.js"); worker.onmessage = (event) => { console.log(`received message from ...
Worker: messageerror event - Web APIs
bubbles no cancelable no interface messageevent event handler property onmessageerror examples create a worker, and listen for message and messageerror events using addeventlistener(): // inside main.js const worker = new worker("static/scripts/worker.js"); worker.addeventlistener("message", (event) => { console.error(`received message from worker: ${event}`); }); worker.addeventlistener("messageerror", (event) => { console.error(`error receiving message from worker: ${event}`); }); the same, but using the onmessageerror event handler property: // inside main.js const worker = new worker("static/scripts/worker.js"); wo...
Worker.prototype.postMessage() - Web APIs
); function handlemessagefromworker(msg) { console.log('incoming message from worker, msg:', msg); switch (msg.data.atopic) { case 'do_sendmainarrbuff': sendmainarrbuff(msg.data.abuf) break; default: throw 'no atopic on incoming message to chromeworker'; } } myworker.addeventlistener('message', handlemessagefromworker); // ok lets create the buffer and send it var arrbuf = new arraybuffer(8); console.info('arrbuf.bytelength pre transfer:', arrbuf.bytelength); myworker.postmessage( { atopic: 'do_sendworkerarrbuff', abuf: arrbuf // the array buffer that we passed to the transferrable section 3 lines below }, [ arrbuf // the array buffer we created 9 lines above ] ); console.info('arrbuf.byt...
Worklet.addModule() - Web APIs
WebAPIWorkletaddModule
klet example const audioctx = new audiocontext(); const audioworklet = audioctx.audioworklet; await audioworklet.addmodule('modules/bypassfilter.js', { credentials: 'omit', }); paintworklet example css.paintworklet.addmodule('https://mdn.github.io/houdini-examples/csspaint/intro/worklets/hilite.js'); once a paintworklet is included, the css paint() function can be used to include the image created by the worklet: @supports (background-image: paint(id)) { h1 { background-image: paint(hollowhighlights, filled, 3px); } } specifications specification status comment worklets level 1the definition of 'addmodule()' in that specification.
Worklet - Web APIs
WebAPIWorklet
the worklet interface abstracts properties and methods common to all kind of worklets, and cannot be created directly.
WritableStreamDefaultController - Web APIs
writablestreamdefaultcontroller instances are created automatically during writablestream construction.
XMLDocument.async - Web APIs
WebAPIXMLDocumentasync
(it has been possible to load documents synchronously since 1.4 alpha.) example function loadxmldata(e) { alert(new xmlserializer().serializetostring(e.target)); // gives querydata.xml contents as string } var xmldoc = document.implementation.createdocument("", "test", null); xmldoc.async = false; xmldoc.onload = loadxmldata; xmldoc.load('querydata.xml'); ...
Synchronous and asynchronous requests - Web APIs
line 3 creates an event handler function object and assigns it to the request's onload attribute.
Using XMLHttpRequest in IE6 - Web APIs
in all modern browsers, you can create a new xmlhttprequest object using the following code: var request = new xmlhttprequest() however, if you need to also support internet explorer 6 and older, you need to extend your code like this: if (window.xmlhttprequest) { //firefox, opera, ie7, and other browsers will use the native object var request = new xmlhttprequest(); } else { //ie 5 and 6 will use the activex control var request = new activexobject("microsoft.xmlhttp"); } see also using xmlhttprequest ...
init() - Web APIs
this may be null, but if it is, the request cannot create a document.
XMLHttpRequest() - Web APIs
the xmlhttprequest() constructor creates a new xmlhttprequest.
XMLHttpRequest.channel - Web APIs
this is null if the channel hasn't been created yet.
XMLHttpRequest.getResponseHeader() - Web APIs
example in this example, a request is created and sent, and a readystatechange handler is established to look for the readystate to indicate that the headers have been received; when that is the case, the value of the content-type header is fetched.
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.
XMLHttpRequest.open() - Web APIs
the xmlhttprequest method open() initializes a newly-created request, or re-initializes an existing one.
XMLHttpRequest.response - Web APIs
json the response is a javascript object created by parsing the contents of received data as json.
XMLHttpRequest.responseType - Web APIs
json the response is a javascript object created by parsing the contents of received data as json.
XMLHttpRequest.sendAsBinary() - Web APIs
you can create the binary string using the filereader method readasbinarystring().
XMLHttpRequestResponseType - Web APIs
json the response is a javascript object created by parsing the contents of received data as json.
XPathExpression.evaluate() - Web APIs
html <div>xpath example</div> <div>number of &lt;div&gt;s: <output></output></div> javascript var xpath = "//div"; var evaluator = new xpathevaluator(); var expression = evaluator.createexpression("//div"); var result = expression.evaluate(document, xpathresult.ordered_node_snapshot_type); document.queryselector("output").textcontent = result.snapshotlength; result specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathexpression.evaluate()' in that specification.
XRBoundedReferenceSpace.boundsGeometry - Web APIs
if you need to create a multi-room space, or a space which is very large or needs to have varying floor levels, you should instead use an unbounded xrreferencespace and enforce the bounds on your own, as appropriate.
XREnvironmentBlendMode - Web APIs
alpha-blend used by headsets or goggles which use cameras to capture the real world and display it digitally on the screen or screens used to render the content for the user to see, this offers a way to create an ar presentation using a vr device.
XRFrame - Web APIs
WebAPIXRFrame
in addition to providing a reference to the xrsession for which this frame is to be rendered, the getviewerpose() method is provided to obtain the xrviewerpose describing the viewer's position and orientation in space, and getpose() can be used to create an xrpose describing the relative position of one xrspace relative to another.
XRInputSourceEvent() - Web APIs
the xrinputsourceevent() constructor creates and returns a new xrinputsourceevent object describing an event (state change) which has occurred on a webxr user input device represented by an xrinputsource.
XRInputSourceEvent - Web APIs
constructor xrinputsourceevent() creates and returns a new xrinputsourceevent object whose properties match those provided in the eventinitdict dictionary provided.
XRInputSourceEventInit - Web APIs
the xrinputsourceeventinit dictionary is used when calling the xrinputsourceevent() constructor to provide configuration options for the newly-created xrinputsourceevent object to take on.
XRInputSourcesChangeEvent.added - Web APIs
examples the example below creates a handler for the inputsourceschange event that processes the lists of added and removed from the webxr system.
XRInputSourcesChangeEvent.removed - Web APIs
examples the example below creates a handler for the inputsourceschange event that processes the lists of added and removed from the webxr system.
XRInputSourcesChangeEvent - Web APIs
constructor xrinputsourceschangeevent() creates and returns a new xrinputsourceschangeevent object configured as indicated by the given xrinputsourceschangeeventinit object.
XRPermissionDescriptor.optionalFeatures - Web APIs
xrboundedreferencespace local a tracking space whose native origin is located near the viewer's position at the time the session was created.
XRPermissionDescriptor.requiredFeatures - Web APIs
xrboundedreferencespace local a tracking space whose native origin is located near the viewer's position at the time the session was created.
XRPermissionStatus.granted - Web APIs
xrboundedreferencespace local a tracking space whose native origin is located near the viewer's position at the time the session was created.
XRPose - Web APIs
WebAPIXRPose
if any component of the transform is computed or created artificially (such as by using mouse or keyboard controls to move through space), this value is instead true, indicating that the transform is in part emulated in software.
XRReferenceSpace: reset event - Web APIs
instead of allowing this to happen, you can integrate the emulatedposition into the teleportation offset calculated prior to calling getoffsetreferencespace() to create a new reference space whose updated effective origin is adjusted by the distance the viewer's position jumped since the previous frame.
XRReferenceSpaceEvent() - Web APIs
the xrreferencespaceevent() constructor is used to create a new xrreferencespaceevent object, which represents an event regarding the state of a webxr reference space object, xrreferencespace.
XRReferenceSpaceEventInit.referenceSpace - Web APIs
examples this simple snippet calls the constructor to create a new reference space event of type reset.
XRReferenceSpaceEventInit.transform - Web APIs
examples this simple snippet calls the constructor to create a new reference space event of type reset.
XRReferenceSpaceType - Web APIs
xrboundedreferencespace local a tracking space whose native origin is located near the viewer's position at the time the session was created.
XRRenderState.baseLayer - Web APIs
that context is passed into new xrwebgllayer() to create an xrwebgllayer which uses the contents of the webgl context gl as the source of the world's image during presentation.
XRRigidTransform.inverse - Web APIs
let modelviewmatrix = mat4.create(); for (let view of pose.view) { let viewport = gllayer.getviewport(view); gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height); /* ...
XRRigidTransform.orientation - Web APIs
examples to create a reference space which is oriented to look straight up, positioned 2 meters off of ground level: xrreferencespace = refspace.getoffsetreferencespace( new xrrigidtransform({y: -2}, {x: 0.0, y: 1.0, z: 0.0, w: 1.0}); ); the unit quaternion specified here is [0.0, 1.0, 0.0, 1.0] to indicate that the object should be facing directly along the y axis.
XRSession.environmentBlendMode - Web APIs
alpha-blend used by headsets or goggles which use cameras to capture the real world and display it digitally on the screen or screens used to render the content for the user to see, this offers a way to create an ar presentation using a vr device.
XRSession.requestAnimationFrame() - Web APIs
this example demonstrates a design pattern that ensures seamless transition between non-immersive animations created via window.requestanimationframe and immersive xr animations.
XRSession.requestReferenceSpace() - Web APIs
xrboundedreferencespace local a tracking space whose native origin is located near the viewer's position at the time the session was created.
XRSession: visibilitychange event - Web APIs
you can also create the event handler by assigning it to the xrsession's onvisibilitychange event handler property, like this: xrsession.onvisibilitychange = (e) => { /* event handled here */ }; specifications specification status comment webxr device apithe definition of 'visibilitychange event' in that specification.
XRSession - Web APIs
WebAPIXRSession
requestreferencespace() requests that a new xrreferencespace of the specified type be created.
XRSessionEventInit - Web APIs
you're unlikely to need to create these events yourself, however, as they're created by the xr system.
XRSpace - Web APIs
WebAPIXRSpace
note: the xrspace interface is never used directly; instead, all spaces are created using one of the interfaces based on xrspace.
XRView.projectionMatrix - Web APIs
the projection matrix for each eye's view is used to ensure that the correct area of the scene is presented to each eye in order to create a believable 3d scene without introducing discomfort for the user.
XRWebGLLayer - Web APIs
constructor new xrwebgllayer() creates and returns a new xrwebgllayer object for use by the specified xrsession, using a particular webglrenderingcontext or webgl2renderingcontext as the destination context.
XRWebGLLayerInit.alpha - Web APIs
example in this example, a new xrwebgllayer is created for a webxr session, xrsession, without an alpha channel.
XRWebGLLayerInit.antialias - Web APIs
usage notes the state of anti-aliasing for the context after being created can be read from the xrwebgllayer property antialias.
XSLT Basic Example - Web APIs
an xslt stylesheet starts with the xsl:stylesheet element, which contains all the templates used to create the final output.
ARIA Screen Reader Implementors Guide - Accessibility
optionally, create a second, additional queue if the user configures a second hardware channel: if there are two channels for presentation (e.g.
Using the aria-invalid attribute - Accessibility
atealert(amsg); } else { elem.setattribute("aria-invalid", "false"); updatealert(); } } the snippet below shows the alert functions, which add (or remove) the error message: function updatealert(msg) { var oldalert = document.getelementbyid("alert"); if (oldalert) { document.body.removechild(oldalert); } if (msg) { var newalert = document.createelement("div"); newalert.setattribute("role", "alert"); newalert.setattribute("id", "alert"); var content = document.createtextnode(msg); newalert.appendchild(content); document.body.appendchild(newalert); } } note that the alert has the aria role attribute set to "alert." working examples: alert role example (uses the aria-invalid attribute) notes ...
Using the aria-valuemax attribute - Accessibility
value string representation of a number possible effects on user agents and assistive technology if the aria-valuemax is indeterminate, or if aria-valuemin is not less than or equal to the value of aria-valuemax, this creates an error condition that will be handled by the assistive technology.
Using the aria-valuemin attribute - Accessibility
value string representation of a number possible effects on user agents and assistive technology if aria-valuemin is not less than or equal to the value of aria-valuemax, this creates an error condition that will be handled by the assistive technology.
Using the group role - Accessibility
the group role is used to identify a set of user interface objects which, in contrast with a region, are not intended to be included in a table of contents or a page summary (such as the structures that are dynamically created by a script or assistive technologies); a group should not be considered a major perceivable section on a page.
ARIA: alert role - Accessibility
lots of alerts at once or unnecessary alerts willl create a bad user experience.
ARIA: application role - Accessibility
in a slides application, for example, a widget could be created that uses the arrow keys to position elements on the slide, and uses audio feedback via an aria live region to communicate the position and overlap status with other objects.
ARIA: Comment role - Accessibility
using too many landmark roles can create "noise" in screen readers, making it difficult to understand the overall layout of the page.
ARIA: Complementary role - Accessibility
using too many landmark roles can create "noise" in screen readers, making it difficult to understand the overall layout of the page.
ARIA: figure role - Accessibility
instead of using aria to create a figure, consider using the native, semantic html <figure> element.
ARIA: gridcell role - Accessibility
examples the following example creates a table-style grouping of information: <h3 id="table-title">jovian gas giant planets</h3> <div role="grid" aria-describedby="table-title"> <div role="rowgroup"> <div role="row"> <div role="columnheader">name</div> <div role="columnheader">diameter (km)</div> <div role="columnheader">length of day (hours)</div> <div role="columnheader">distance from sun (10<sup>6</s...
ARIA: Mark role - Accessibility
using too many landmark roles can create "noise" in screen readers, making it difficult to understand the overall layout of the page.
ARIA: Navigation Role - Accessibility
using too many landmark roles can create "noise" in screen readers, making it difficult to understand the overall layout of the page.
ARIA: Region role - Accessibility
using too many landmark roles can create "noise" in screen readers, making it difficult to understand the overall layout of the page.
ARIA: rowgroup role - Accessibility
to create an aria table header, table footer or table body, add role="rowgroup" to the element.
ARIA: Suggestion role - Accessibility
using too many landmark roles can create "noise" in screen readers, making it difficult to understand the overall layout of the page.
ARIA: tab role - Accessibility
example this example combines the role tab with tablist and elements with tabpanel to create an interactive group of tabbed content.
ARIA: checkbox role - Accessibility
f the aria-checked attribute and the appearance of the checkbox so it appears checked or unchecked to the sighted user onkeypress handle the case where the user presses the space key to change the state of the checkbox by changing the value of the aria-checked attribute and the appearance of the checkbox so it appears checked or unchecked to the sighted user examples the following example creates a simple checkbox element using css and javascript to handle the checked or unchecked status of the element.
ARIA: listbox role - Accessibility
description the listbox role is used to identify an element that creates a list from which a user may select one or more static items, similar to the html <select> element.
WAI-ARIA Roles - Accessibility
this role can be used in combination with the aria-pressed attribute to create toggle buttons.aria: cell rolethe cell value of the aria role attribute identifies an element as being a cell in a tabular container that does not contain column or row header information.
widgets - Accessibility
this page was auto-generated because a user created a sub-page to this page.
ARIA - Accessibility
progressbar.setattribute("role", "progressbar"); progressbar.setattribute("aria-valuemin", 0); progressbar.setattribute("aria-valuemax", 100); // create a function that can be called at any time to update // the value of the progress bar.
Accessibility and Spacial Patterns - Accessibility
stripes and patterns are typical of the kinds of images that create problems, and stripes have been studied most closely.
An overview of accessible web applications and widgets - Accessibility
see also live regions keyboard navigation often times developers overlook support for the keyboard when they create custom widgets.
Architecture - Accessibility
the implementation simply doesn't create atkobjects for a whitespace or text leaf nsiaccessibles.
Cognitive accessibility - Accessibility
adaptability guideline 1.3 states "content should be adaptable." create content that can be presented in different ways without losing information or structure.
Keyboard-navigable JavaScript widgets - Accessibility
tips use element.focus() to set focus do not use createevent(), initevent() and dispatchevent() to send focus to an element.
Web accessibility for seizures and physical reactions - Accessibility
attern analyzer iso iec 61966-2-2:2003(en) multimedia systems and equipment — colour measurement and management — part 2-2: colour management — extended rgb colour space — scrgb photosensitive epilepsy analysis tool along with the harding tool, is generaly recognized to be one of the two "gold standards" for analyzing flashes trace research and development center using peat to create seizureless web animations w3c css color module level 3 personalization semantics explainer 1.0.
Operable - Accessibility
most of these mechanisms can be created using simple html features, for example see search field, creating a navigation menu, styling links as buttons.
Text labels and names - Accessibility
or, you can create an association between a <label> and a form element by specifying the form element's id value as the value of the label's for attribute.
Understandable - Accessibility
the html5 <audio> element can be used to create a control that allows the reader to play back an audio file containing the correct pronounciation, and it also makes sense to include a textual pronounciation guide after difficult words, in the same way that you find in dictionary entries.
Accessibility
accessible multimedia another category of content that can create accessibility problems is multimedia — video, audio, and image content need to be given proper textual alternatives so they can be understood by assistive technologies and their users.
-moz-user-focus - CSS: Cascading Style Sheets
instead, xbl creates an anonymous html <input> element inside the textbox, and that element is what receives focus.
-webkit-overflow-scrolling - CSS: Cascading Style Sheets
also creates a new stacking context.
:-moz-ui-invalid - CSS: Cascading Style Sheets
by default, gecko applies a style that creates a red "glow" (using the box-shadow property) around items, which have this pseudo-class applied.
::first-letter (:first-letter) - CSS: Cascading Style Sheets
ext-shadow, text-transform, letter-spacing, word-spacing (when appropriate), line-height, text-decoration-color, text-decoration-line, text-decoration-style, box-shadow, float, vertical-align (only if float is none) css properties syntax /* css3 syntax */ ::first-letter /* css2 syntax */ :first-letter examples simple drop cap in this example we will use the ::first-letter pseudo-element to create a simple drop cap effect on the first letter of the paragraph coming right after the <h2>.
::slotted() - CSS: Cascading Style Sheets
WebCSS::slotted
</ul> </div> </template> a custom element — <person-details> — is defined like so: customelements.define('person-details', class extends htmlelement { constructor() { super(); let template = document.getelementbyid('person-template'); let templatecontent = template.content; const shadowroot = this.attachshadow({mode: 'open'}); let style = document.createelement('style'); style.textcontent = 'div { padding: 10px; border: 1px solid gray; width: 200px; margin: 10px; }' + 'h2 { margin: 0 0 10px; }' + 'ul { margin: 0; }' + 'p { margin: 10px 0; }' + '::slotted(*) { color: gray; font-family: sans-serif; } '; shadowroot.appendchild(sty...
:defined - CSS: Cascading Style Sheets
WebCSS:defined
in this demo we define a very simple trivial custom element: customelements.define('simple-custom', class extends htmlelement { constructor() { super(); let divelem = document.createelement('div'); divelem.textcontent = this.getattribute('text'); let shadowroot = this.attachshadow({mode: 'open'}) .appendchild(divelem); } }) then insert a copy of this element into the document, along with a standard <p>: <simple-custom text="custom element example text"></simple-custom> <p>standard paragraph example text</p> in the css we first include the following ...
:empty - CSS: Cascading Style Sheets
WebCSS:empty
all interactive content must have an accessible name, which is created by providing a text value for the interactive control's parent element (anchors, buttons, etc.).
:host() - CSS: Cascading Style Sheets
WebCSS:host()
in this example we have a simple custom element — <context-span> — that you can wrap around text: <h1>host selectors <a href="#"><context-span>example</context-span></a></h1> inside the element's constructor, we create style and span elements, fill the span with the content of the custom element, and fill the style element with some css rules: let style = document.createelement('style'); let span = document.createelement('span'); span.textcontent = this.textcontent; const shadowroot = this.attachshadow({mode: 'open'}); shadowroot.appendchild(style); shadowroot.appendchild(span); style.textcontent = 'span:hov...
:host-context() - CSS: Cascading Style Sheets
in this example we have a simple custom element — <context-span> — that you can wrap around text: <h1>host selectors <a href="#"><context-span>example</context-span></a></h1> inside the element's constructor, we create style and span elements, fill the span with the content of the custom element, and fill the style element with some css rules: let style = document.createelement('style'); let span = document.createelement('span'); span.textcontent = this.textcontent; const shadowroot = this.attachshadow({mode: 'open'}); shadowroot.appendchild(style); shadowroot.appendchild(span); style.textcontent = 'span:hov...
:host - CSS: Cascading Style Sheets
WebCSS:host
in this example we have a simple custom element — <context-span> — that you can wrap around text: <h1>host selectors <a href="#"><context-span>example</context-span></a></h1> inside the element's constructor, we create style and span elements, fill the span with the content of the custom element, and fill the style element with some css rules: let style = document.createelement('style'); let span = document.createelement('span'); span.textcontent = this.textcontent; const shadowroot = this.attachshadow({mode: 'open'}); shadowroot.appendchild(style); shadowroot.appendchild(span); style.textcontent = 'span:hov...
:target - CSS: Cascading Style Sheets
WebCSS:target
isn't that delightful?</p> css p:target { background-color: gold; } /* add a pseudo-element inside the target element */ p:target::before { font: 70% sans-serif; content: "►"; color: limegreen; margin-right: .25em; } /* style italic elements within the target element */ p:target i { color: red; } result pure-css lightbox you can use the :target pseudo-class to create a lightbox without using any javascript.
fallback - CSS: Cascading Style Sheets
the fallback descriptor can be used to specify a counter style to fall back to if the current counter style cannot create a marker representation for a particular counter value.
font-style - CSS: Cascading Style Sheets
these fonts are specially created by font designers and are not artificially sloped.
unicode-range - CSS: Cascading Style Sheets
formal definition related at-rule@font-faceinitial valueu+0-10ffffcomputed valueas specified formal syntax <unicode-range># examples using a different font for a single character in this example we create a simple html containing a single <div> element, including an ampersand, that we want to style with a different font.
@keyframes - CSS: Cascading Style Sheets
to use keyframes, create a @keyframes rule with a name that is then used by the animation-name property to match an animation to its keyframe declaration.
any-pointer - CSS: Cascading Style Sheets
examples this example creates a small checkbox for users with at least one fine pointer and a large checkbox for users with at least one coarse pointer.
aspect-ratio - CSS: Cascading Style Sheets
examples the example below is contained in an <iframe>, which creates its own viewport.
pointer - CSS: Cascading Style Sheets
WebCSS@mediapointer
examples this example creates a small checkbox for users with fine primary pointers and a large checkbox for users with coarse primary pointers.
prefers-color-scheme - CSS: Cascading Style Sheets
alternately, users can create the numeric preference ui.systemusesdarktheme to override the default behavior and return light (value: 0), dark (value: 1), or no-preference (value: 2).
@media - CSS: Cascading Style Sheets
WebCSS@media
note: in javascript, the rules created using @media can be accessed with the cssmediarule css object model interface.
Alternative style sheets - CSS: Cascading Style Sheets
it defines how these are determined, and lets the html specification define the html-specific behaviors by requiring it to define when to create a css style sheet.
Coordinate systems - CSS: Cascading Style Sheets
this simple example creates a set of nested boxes.
CSS Animations - CSS: Cascading Style Sheets
using css animations step-by-step tutorial about how to create animations using css.
CSS Box Alignment - CSS: Cascading Style Sheets
the module aims to create a consistent method of alignment across all of css.
Mastering margin collapsing - CSS: Cascading Style Sheets
no content separating parent and descendants if there is no border, padding, inline part, block formatting context created, or clearance to separate the margin-top of a block from the margin-top of one or more of its descendant blocks; or no border, padding, inline content, height, min-height, or max-height to separate the margin-bottom of a block from the margin-bottom of one or more of its descendant blocks, then those margins collapse.
CSS Color - CSS: Cascading Style Sheets
WebCSSCSS Color
tools color picker tool this tool makes it easy to create, adjust, and experiment with custom colors.
Handling Overflow in Multicol - CSS: Cascading Style Sheets
my multicol container has a height and there is more text than space to create columns, therefore we get columns created outside of the container.
Spanning and Balancing Columns - CSS: Cascading Style Sheets
additionally, if a spanning element appears later in the content it can cause unexpected or unwanted behaviour when there is not enough content to create columns after the spanner.
Using multi-column layouts - CSS: Cascading Style Sheets
therefore it's relatively easy to create a layout that will display in a single column in those browsers and use multiple columns in supporting browsers.
Ordering Flex Items - CSS: Cascading Style Sheets
the card also has a date; the finished design we want to create is something like this.
CSS Flexible Box Layout - CSS: Cascading Style Sheets
mastering wrapping of flex items how to create flex containers with multiple lines and control the display of the items in those lines.
In Flow and Out of Flow - CSS: Cascading Style Sheets
taking an item out of flow all elements are in-flow apart from: floated items items with position: absolute (including position: fixed which acts in the same way) the root element (html) out of flow items create a new block formatting context (bfc) and therefore everything inside them can be seen as a mini layout, separate from the rest of the page.
Variable fonts guide - CSS: Cascading Style Sheets
there is a new attribute, font-optical-sizing, created to support variable fonts in css.
CSS Grid Layout - CSS: Cascading Style Sheets
basic example the example below shows a three-column track grid with new rows created at a minimum of 100 pixels and a maximum of auto.
CSS Images - CSS: Cascading Style Sheets
on image-rendering image-resolution object-fit object-position functions linear-gradient() radial-gradient() repeating-linear-gradient() repeating-radial-gradient() conic-gradient() repeating-conic-gradient() url() element() image() cross-fade() data types <gradient> <image> guides using css gradients presents a specific type of css images, gradients, and how to create and use these.
Logical properties for floating and positioning - CSS: Cascading Style Sheets
new properties have been created in the logical properties specification for when you want the positioning to relate to the flow of text in your writing mode.
Logical properties for margins, borders and padding - CSS: Cascading Style Sheets
in the example below i have created two boxes and added different sized margins to each edge.
Using z-index - CSS: Cascading Style Sheets
if you want to create a custom stacking order, you can use the z-index property on a positioned element.
Stacking with floated blocks - CSS: Cascading Style Sheets
this is due to a peculiar part of the specification: applying a opacity value creates a new stacking context (see what no one told you about z-index).
CSS Shapes - CSS: Cascading Style Sheets
this creates a circle shape, and the content wrapping the float now wraps around that shape.
Using CSS transforms - CSS: Cascading Style Sheets
html the html below creates four copies of the same box, with the perspective set at different values.
CSS values and units - CSS: Cascading Style Sheets
for example, the value of grid-area can be a <custom-ident>, so if we had a grid area named content we would use it without quotes: .item { grid-area: content; } in comparison, a data type that is a <string>, such as a string value of the content property, must be quoted: .item::after { content: "this is my content."; } while you can generally create any name you want, including using emojis, the identifier can't be none, unset, initial, or inherit, start with a digit or two dashes, and generally you don't want it to be any other pre-defined css keyword.
Inline formatting context - CSS: Cascading Style Sheets
this box will be large enough to contain all of the inline boxes in that line; when there is no more room in the inline direction another line will be created.
Card - CSS: Cascading Style Sheets
if the track does have a footer it will be auto-sized, as rows created in the implicit grid are auto-sized by default.
Cookbook template - CSS: Cascading Style Sheets
please use this as a raw template when you create a new cookbook page.
Grid wrapper - CSS: Cascading Style Sheets
using a numeric unit (pixels, ems, rems) will create a fixed maximum size for the central wrapper, whereas using percentage values or viewport units will mean this wrapper grows or shrinks in response to its context.
List group with badges - CSS: Cascading Style Sheets
in this recipe we will create a list group pattern with badges that indicate a count.
CSS reference - CSS: Cascading Style Sheets
WebCSSReference
basic selectors basic selectors are fundamental selectors; these are the most basic selectors that are frequently combined to create other, more complex selectors.
Tools - CSS: Cascading Style Sheets
WebCSSTools
this is not really yet a useful tool, but will be!linear-gradient generatorthis tool can be used to create custom css3 linear-gradient() backgrounds.
CSS Tutorials - CSS: Cascading Style Sheets
WebCSSTutorials
advanced-level css tutorials css also got new features allowing you to create complex layouts.
animation - CSS: Cascading Style Sheets
WebCSSanimation
consider providing a mechanism for pausing or disabling animation, as well as using the reduced motion media query to create a complimentary experience for users who have expressed a preference for no animated experiences.
background-position - CSS: Cascading Style Sheets
] ]where <length-percentage> = <length> | <percentage> examples positioning background images each of these three examples uses the background property to create a yellow, rectangular element containing a star image.
<blend-mode> - CSS: Cascading Style Sheets
this blend mode is similar to screen, but the foreground need only be as light as the inverse of the backdrop to create a fully lit color.
border-image-source - CSS: Cascading Style Sheets
the border-image-source css property sets the source image used to create an element's border image.
border-image-width - CSS: Cascading Style Sheets
it also applies to ::first-letter.inheritednopercentagesrefer to the width or height of the border image areacomputed valueas specified, but with relative lengths converted into absolute lengthsanimation typeby computed value type formal syntax [ <length-percentage> | <number> | auto ]{1,4}where <length-percentage> = <length> | <percentage> examples tiling a border image this example creates a border image using the following ".png" file, which is 90 by 90 pixels: thus, each circle in the source image is 30 by 30 pixels.
calc() - CSS: Cascading Style Sheets
WebCSScalc
in this example, the css creates a banner that stretches across the window, with a 40-pixel gap between both sides of the banner and the edges of the window: .banner { position: absolute; left: 40px; width: calc(100% - 80px); border: solid black 1px; box-shadow: 1px 2px; background-color: yellow; padding: 6px; text-align: center; box-sizing: border-box; } <div class="banner">this is a banner!</div> autom...
column-gap (grid-column-gap) - CSS: Cascading Style Sheets
iv></div> <div></div> </div> css #grid { grid-column-gap: 20px; } #grid { display: grid; height: 100px; grid-template-columns: repeat(3, 1fr); grid-template-rows: 100px; column-gap: 20px; } #grid > div { border: 1px solid green; background-color: lime; } result multi-column layout html <p class="content-box"> this is some multi-column text with a 40px column gap created with the css `column-gap` property.
column-width - CSS: Cascading Style Sheets
this property can help you create responsive designs that fit different screen sizes.
contain - CSS: Cascading Style Sheets
WebCSScontain
note: if applied (with value: paint, strict or content), this property creates: a new containing block (for the descendants whose position property is absolute or fixed).
cursor - CSS: Cascading Style Sheets
WebCSScursor
drag & drop alias an alias or shortcut is to be created.
direction - CSS: Cascading Style Sheets
WebCSSdirection
the property sets the base text direction of block-level elements and the direction of embeddings created by the unicode-bidi property.
<display-inside> - CSS: Cascading Style Sheets
this will result in expected behavior; for example if you specify an element to be display: grid, you would expect that the box created on the grid container would be a block level box.
<display-legacy> - CSS: Cascading Style Sheets
html <div class="container"> <div>flex item</div> <div>flex item</div> </div> not a flex item css .container { display: inline-flex; } result in the new syntax the inline flex container would be created using two values, inline for the outer display type, and flex for the inner display type.
display - CSS: Cascading Style Sheets
WebCSSdisplay
this will result in expected behavior; for example if you specify an element to be display: grid, you would expect that the box created on the grid container would be a block level box.
blur() - CSS: Cascading Style Sheets
it defines the value of the standard deviation to the gaussian function, i.e., how many pixels on the screen blend into each other; thus, a larger value will create more blur.
brightness() - CSS: Cascading Style Sheets
a value of 0% will create an image that is completely black, while a value of 100% leaves the input unchanged.
contrast() - CSS: Cascading Style Sheets
a value of 0% will create an image that is completely gray, while a value of 100% leaves the input unchanged.
drop-shadow() - CSS: Cascading Style Sheets
the box-shadow property creates a rectangular shadow behind an element's entire box, while the drop-shadow() filter function creates a shadow that conforms to the shape (alpha channel) of the image itself.
flex-direction - CSS: Cascading Style Sheets
accessibility concerns using the flex-direction property with values of row-reverse or column-reverse will create a disconnect between the visual presentation of content and dom order.
font-size - CSS: Cascading Style Sheets
WebCSSfont-size
avoid using them for font sizes if you wish to create an inclusive design.
font-style - CSS: Cascading Style Sheets
html <header> <input type="range" id="slant" name="slant" min="-90" max="90" /> <label for="slant">slant</label> </header> <div class="container"> <p class="sample">...it would not be wonderful to meet a megalosaurus, forty feet long or so, waddling like an elephantine lizard up holborn hill.</p> </div> css /* amstelvaralpha-vf is created by david berlow (https://github.com/typenetwork/amstelvar) and is used here under the terms of its license: https://github.com/typenetwork/amstelvar/blob/master/ofl.txt */ @font-face { src: url('https://mdn.mozillademos.org/files/16044/amstelvaralpha-vf.ttf'); font-family:'amstelvaralpha'; font-style: normal; } label { font: 1rem monospace; } .container { max-height: 150px; overfl...
font-variant-alternates - CSS: Cascading Style Sheets
it is similar to styleset(), but doesn't create coherent glyphs for a set of characters; individual characters will have independent and not necessarily coherent styles.
font-weight - CSS: Cascading Style Sheets
html <header> <input type="range" id="weight" name="weight" min="1" max="1000" /> <label for="weight">weight</label> </header> <div class="container"> <p class="sample">...it would not be wonderful to meet a megalosaurus, forty feet long or so, waddling like an elephantine lizard up holborn hill.</p> </div> css /* mutator sans is created by letterror (https://github.com/letterror/mutatorsans) and is used here under the terms of its license: https://github.com/letterror/mutatorsans/blob/master/license */ @font-face { src: url('https://mdn.mozillademos.org/files/16011/mutatorsans.ttf'); font-family:'mutatorsans'; font-style: normal; } label { font: 1rem monospace; white-space: nowrap; } .container { max-height: 150p...
gap (grid-gap) - CSS: Cascading Style Sheets
WebCSSgap
</div> <div></div> <div></div> <div></div> </div> css #grid { grid-gap: 20px 5px; } #grid { display: grid; height: 200px; grid-template: repeat(3, 1fr) / repeat(3, 1fr); gap: 20px 5px; } #grid > div { border: 1px solid green; background-color: lime; } result multi-column layout html <p class="content-box"> this is some multi-column text with a 40px column gap created with the css <code>gap</code> property.
mask-border-source - CSS: Cascading Style Sheets
the mask-border-source css property sets the source image used to create an element's mask border.
mask - CSS: Cascading Style Sheets
WebCSSmask
ive lengths converted into absolute lengthsmask-composite: as specifiedanimation typeas each of the properties of the shorthand:mask-image: discretemask-mode: discretemask-repeat: discretemask-position: repeatable list of simple list of length, percentage, or calcmask-clip: discretemask-origin: discretemask-size: repeatable list of simple list of length, percentage, or calcmask-composite: discretecreates stacking contextyes formal syntax <mask-layer>#where <mask-layer> = <mask-reference> | <position> [ / <bg-size> ]?
mix-blend-mode - CSS: Cascading Style Sheets
formal definition initial valuenormalapplies toall elementsinheritednocomputed valueas specifiedanimation typediscretecreates stacking contextyes formal syntax <blend-mode>where <blend-mode> = normal | multiply | screen | overlay | darken | lighten | color-dodge | color-burn | hard-light | soft-light | difference | exclusion | hue | saturation | color | luminosity examples effect of different mix-blend-mode values <div class="grid"> <div class="col"> <div class="note">blending in isolation (no blending with...
offset-path - CSS: Cascading Style Sheets
formal definition initial valuenoneapplies totransformable elementsinheritednocomputed valueas specifiedanimation typeas <angle>, <basic-shape> or <path()>creates stacking contextyes formal syntax none | ray( [ <angle> && <size>?
offset - CSS: Cascading Style Sheets
WebCSSoffset
> the absolute value, otherwise a percentageoffset-anchor: for <length> the absolute value, otherwise a percentageoffset-rotate: as specifiedanimation typeas each of the properties of the shorthand:offset-position: a positionoffset-path: as <angle>, <basic-shape> or <path()>offset-distance: a length, percentage or calc();offset-anchor: a positionoffset-rotate: as <angle>, <basic-shape> or <path()>creates stacking contextyes formal syntax [ <'offset-position'>?
overflow-wrap - CSS: Cascading Style Sheets
note: in contrast to word-break, overflow-wrap will only create a break if an entire word cannot be placed on its own line without overflowing.
overflow - CSS: Cascading Style Sheets
WebCSSoverflow
specifying a value other than visible (the default) creates a new block formatting context.
repeating-linear-gradient() - CSS: Cascading Style Sheets
the repeating-linear-gradient() css function creates an image consisting of repeating linear gradients.
repeating-radial-gradient() - CSS: Cascading Style Sheets
the repeating-radial-gradient() css function creates an image consisting of repeating gradients that radiate from an origin.
revert - CSS: Cascading Style Sheets
WebCSSrevert
the only difference is for properties that have values set by the browser or by custom stylesheets created by users (set on the browser side).
rotate - CSS: Cascading Style Sheets
WebCSSrotate
formal definition initial valuenoneapplies totransformable elementsinheritednocomputed valueas specifiedanimation typea transformcreates stacking contextyes formal syntax none | <angle> | [ x | y | z | <number>{3} ] && <angle> examples rotate an element on hover html <div> <p class="rotate">rotation</p> </div> css * { box-sizing: border-box; } html { font-family: sans-serif; } div { width: 150px; margin: 0 auto; } p { padding: 10px 5px; border: 3px solid black; border-radius: 20px; width: 150px; fo...
scale - CSS: Cascading Style Sheets
WebCSSscale
formal definition initial valuenoneapplies totransformable elementsinheritednocomputed valueas specifiedanimation typea transformcreates stacking contextyes formal syntax none | <number>{1,3} examples scaling an element on hover html <div> <p class="scale">scaling</p> </div> css * { box-sizing: border-box; } html { font-family: sans-serif; } div { width: 150px; margin: 0 auto; } p { padding: 10px 5px; border: 3px solid black; border-radius: 20px; width: 150px; font-size: 1.2rem; text-align: center...
scroll-margin-inline-end - CSS: Cascading Style Sheets
the aim here is to create four horizontally-scrolling blocks, the second and third of which snap into place, near but not quite at the right of each block.
scroll-margin-inline-start - CSS: Cascading Style Sheets
the aim here is to create four horizontally-scrolling blocks, the second and third of which snap into place, near but not quite at the left of each block.
scroll-margin-inline - CSS: Cascading Style Sheets
the aim here is to create four horizontally-scrolling blocks, the second and third of which snap into place, near but not quite at the right of each block.
scroll-margin - CSS: Cascading Style Sheets
the aim here is to create four horizontally-scrolling blocks, the second and third of which snap into place, near but not quite at the left of each block.
shape-image-threshold - CSS: Cascading Style Sheets
formal definition initial value0.0applies tofloatsinheritednocomputed valuethe same as the specified value after clipping the <number> to the range [0.0, 1.0].animation typea number formal syntax <alpha-value>where <alpha-value> = <number> | <percentage> examples aligning text to a gradient this example creates a <div> block with a gradient background image.
shape-margin - CSS: Cascading Style Sheets
the shape-margin css property sets a margin for a css shape created using shape-outside.
<string> - CSS: Cascading Style Sheets
WebCSSstring
for example, \\ will create a single backslash.
text-align - CSS: Cascading Style Sheets
accessibility concerns the inconsistent spacing between words created by justified text can be problematic for people with cognitive concerns such as dyslexia.
text-decoration-skip-ink - CSS: Cascading Style Sheets
this can be helpful with certain chinese, japanese, or korean (cjk) fonts, where the auto behavior might not create interruptions.
matrix3d() - CSS: Cascading Style Sheets
a1a2a3a4b1b2b3b4c1c2c3c4d1d2d3d4 examples cube squashing example the following example shows a 3d cube created from dom elements and transforms, which can be hovered/focused to apply a matrix3d() transform to it.
rotate() - CSS: Cascading Style Sheets
syntax the amount of rotation created by rotate() is specified by an <angle>.
rotate3d() - CSS: Cascading Style Sheets
syntax the amount of rotation created by rotate3d() is specified by three <number>s and one <angle>.
rotateX() - CSS: Cascading Style Sheets
syntax the amount of rotation created by rotatex() is specified by an <angle>.
rotateY() - CSS: Cascading Style Sheets
syntax the amount of rotation created by rotatey() is specified by an <angle>.
rotateZ() - CSS: Cascading Style Sheets
syntax the amount of rotation created by rotatez() is specified by an <angle>.
<transform-function> - CSS: Cascading Style Sheets
examples transform function comparison the following example provides a 3d cube created from dom elements and transforms, and a select menu allowing you to choose different transform functions to transform the cube with, so you can compare the effects of the different types.
transform-style - CSS: Cascading Style Sheets
formal definition initial valueflatapplies totransformable elementsinheritednocomputed valueas specifiedanimation typediscretecreates stacking contextyes formal syntax flat | preserve-3d examples transform style demonstration in this example we have a 3d cube created using transforms.
transition-timing-function - CSS: Cascading Style Sheets
consider providing a mechanism for pausing or disabling animation, as well as using the reduced motion media query to create a complimentary experience for users who have expressed a preference for no animated experiences.
<url> - CSS: Cascading Style Sheets
WebCSSurl
confusingly, this meant that url() could be used to create a <uri> css data type.
word-break - CSS: Cascading Style Sheets
note: in contrast to word-break: break-word and overflow-wrap: break-word (see overflow-wrap), word-break: break-all will create a break at the exact place where text would otherwise overflow its container (even if putting an entire word on its own line would negate the need for a break).
z-index - CSS: Cascading Style Sheets
WebCSSz-index
formal definition initial valueautoapplies topositioned elementsinheritednocomputed valueas specifiedanimation typean integercreates stacking contextyes formal syntax auto | <integer> examples visually layering elements html <div class="dashed-box">dashed box <span class="gold-box">gold box</span> <span class="green-box">green box</span> </div> css .dashed-box { position: relative; z-index: 1; border: dashed; height: 8em; margin-bottom: 1em; margin-top: 2em; } .gold-box { position: absolute; z-ind...
CSS: Cascading Style Sheets
WebCSS
the web community has created various other miscellaneous css tools for you to use.
exsl:node-set() - EXSLT
WebEXSLTexslnode-set
this lets you process the xml created within a variable to process it in multiple steps.
Common (exsl) - EXSLT
WebEXSLTexsl
this lets you process the xml created within a variable to process it in multiple steps.exsl:object-type()exsl:object-type() returns a string that indicates the type of the specified object.
WAI ARIA Live Regions/API Support - Developer guides
get_oldtext to retrieve the offsets and removed text) text inserted text_changed::insert ia2_event_text_inserted (use iaccessibletext::get_newtext to retrieve the offsets and inserted text) text replaced text_changed::delete followed immediately by text_changed::insert ia2_event_text_removed followed immediately by ia2_event_text_inserted * we do not use msaa's create/destroy at the request of screen reader vendors, who avoid those events because they cause crashes on some important system -- show/hide are the equivalent of those events.
Video player styling basics - Developer guides
ange is simple: the data-state for showing the video controls when javascript is available to the browser now needs to be set: // display the user defined video controls videocontrols.setattribute('data-state', 'visible'); progress bar support a check also needs to be made to set up the "fake" progress bar if the browser doesn't support the <progress> element: var supportsprogress = (document.createelement('progress').max !== undefined); if (!supportsprogress) progress.setattribute('data-state', 'fake'); button functionality this section looks at the javascript required for implementing the button functionality.
Writing Web Audio API code that works in every browser - Developer guides
for example, the way to create instances of gainnode used to be var gain = audiocontext.creategainnode(); but nowadays it is just var gain = audiocontext.creategain(); since the old method names are not present in firefox, existing code may crash with something like creategainnode is not a function, and you now know why.
Media buffering, seeking, and time ranges - Developer guides
var seekabletimeranges = myaudio.seekable; creating our own buffering feedback if we wish to create our own custom player, we may want to provide feedback on how much of the media is ready to be played.
Overview of events and handlers - Developer guides
ttached as: var funcinit = function(){ // user code goes here and can safely address all the html elements from the page // since the document has successfully been 'loaded' } document.addeventlistener('domcontentloaded', funcinit); so that this code will only be executed after the document object emits the 'domcontentloaded' event because the html has been parsed and javasript objects created representing each of the nodes of the html document.
Using device orientation with 3D transforms - Developer guides
r elem = document.getelementbyid("view3d"); window.addeventlistener("deviceorientation", function(e) { // remember to use vendor-prefixed transform property elem.style.transform = "rotatez(" + ( e.alpha - 180 ) + "deg) " + "rotatex(" + e.beta + "deg) " + "rotatey(" + ( -e.gamma ) + "deg)"; }); orientation compensation compensating the orientation of the device can be useful to create parallax effects or augmented reality.
Event developer guide - Developer guides
WebGuideEvents
docs creating and triggering eventsthis article demonstrates how to create and dispatch dom events.
Graphics on the Web - Developer guides
with vectors, you can create images that scale cleanly to any size.
Mobile Web Development - Developer guides
WebGuideMobile
cross-browser development write cross-browser code to create web sites that will work acceptably across different mobile browsers: try to avoid using browser-specific features, such as vendor-prefixed css properties.
Printing - Developer guides
e="text/javascript"> function closeprint () { document.body.removechild(this.__container__); } function setprint () { this.contentwindow.__container__ = this; this.contentwindow.onbeforeunload = closeprint; this.contentwindow.onafterprint = closeprint; this.contentwindow.focus(); // required for ie this.contentwindow.print(); } function printpage (surl) { var ohiddframe = document.createelement("iframe"); ohiddframe.onload = setprint; ohiddframe.style.position = "fixed"; ohiddframe.style.right = "0"; ohiddframe.style.bottom = "0"; ohiddframe.style.width = "0"; ohiddframe.style.height = "0"; ohiddframe.style.border = "0"; ohiddframe.src = surl; document.body.appendchild(ohiddframe); } </script> </head> <body> <p><span onclick="printpage('externalpage.html');" ...
User input and controls - Developer guides
contenteditable demo this is a working example showing how contenteditable can be used to create an editable document section, the state of which is then saved using localstorage.
Writing forward-compatible websites - Developer guides
don't unnecessarily create separate codepaths for different browsers don't go out of your way to run different code based on either object detection or ua sniffing if one of the codepaths involved actually works in all browsers.
Block-level elements - HTML: Hypertext Markup Language
inherent in this structural distinction is the idea that block elements create "larger" structures than inline elements.
Date and time formats used in HTML - HTML: Hypertext Markup Language
while the gregorian calendar wasn't created until the year 1582 (replacing the similar julian calendar), for html's purposes, the gregorian calendar is extended back to the year 1 c.e.
<h1>–<h6>: The HTML Section Heading elements - HTML: Hypertext Markup Language
doing so may create confusion, as the person navigating this way may be left wondering where the missing heading is.
<abbr>: The Abbreviation element - HTML: Hypertext Markup Language
WebHTMLElementabbr
html <p><dfn id="html"><abbr title="hypertext markup language">html</abbr> </dfn> is a markup language used to create the semantics and structure of a web page.</p> <p>a <dfn id="spec">specification</dfn> (<abbr title="specification">spec</abbr>) is a document that outlines in detail how a technology or api is intended to function and how it is accessed.</p> result accessibility concerns spelling out the acronym or abbreviation in full the first time it is used on a page is beneficial for helping people un...
<b>: The Bring Attention To element - HTML: Hypertext Markup Language
WebHTMLElementb
however, you should not use <b> for styling text; instead, you should use the css font-weight property to create boldface text, or the <strong> element to indicate that text is of special importance.
<button>: The Button element - HTML: Hypertext Markup Language
WebHTMLElementbutton
spacing may be created using css properties such as margin.
<del>: The Deleted Text element - HTML: Hypertext Markup Language
WebHTMLElementdel
del::before, del::after { clip-path: inset(100%); clip: rect(1px, 1px, 1px, 1px); height: 1px; overflow: hidden; position: absolute; white-space: nowrap; width: 1px; } del::before { content: " [deletion start] "; } del::after { content: " [deletion end] "; } some people who use screen readers deliberately disable announcing content that creates extra verbosity.
<div>: The Content Division element - HTML: Hypertext Markup Language
WebHTMLElementdiv
you name it!</p> </div> the result looks like this: a styled example this example creates a shadowed box by applying a style to the <div> using css.
<dl>: The Description List element - HTML: Hypertext Markup Language
WebHTMLElementdl
<dl> <div> <dt>name</dt> <dd>godzilla</dd> </div> <div> <dt>born</dt> <dd>1952</dd> </div> <div> <dt>birthplace</dt> <dd>japan</dd> </div> <div> <dt>color</dt> <dd>green</dd> </div> </dl> notes do not use this element (nor <ul> elements) to merely create indentation on a page.
<form> - HTML: Hypertext Markup Language
WebHTMLElementform
rel creates a hyperlink or annotation depending on the value, see the rel attribute for details.
<head>: The Document Metadata (Header) element - HTML: Hypertext Markup Language
WebHTMLElementhead
example <!doctype html> <html> <head> <title>document title</title> </head> </html> notes html5-compliant browsers automatically create a <head> element if its tags are omitted in the markup.
<iframe>: The Inline Frame element - HTML: Hypertext Markup Language
WebHTMLElementiframe
allow-scripts: lets the resource run scripts (but not create popup windows).
<input type="color"> - HTML: Hypertext Markup Language
WebHTMLElementinputcolor
example let's create an example which does a little more with the color input by tracking the change and input events to take the new color and apply it to every <p> element in the document.
<input type="number"> - HTML: Hypertext Markup Language
WebHTMLElementinputnumber
when you create a number input with the proper type value, number, you get automatic validation that the entered text is a number, and usually a set of up and down buttons to step the value up and down.
<input type="range"> - HTML: Hypertext Markup Language
WebHTMLElementinputrange
transform: rotate(-90deg) you can, however, create a vertical range control by drawing a horizontal range control on its side.
<input type="reset"> - HTML: Hypertext Markup Language
WebHTMLElementinputreset
if you want to create a custom button and then customize the behaviour using javascript, you need to use <input type="button">, or better still, a <button> element.
<input type="tel"> - HTML: Hypertext Markup Language
WebHTMLElementinputtel
the example below creates a 20-character wide telephone number entry box, requiring that the contents be no shorter than 9 characters and no longer than 14 characters.
<ins> - HTML: Hypertext Markup Language
WebHTMLElementins
ins::before, ins::after { clip-path: inset(100%); clip: rect(1px, 1px, 1px, 1px); height: 1px; overflow: hidden; position: absolute; white-space: nowrap; width: 1px; } ins::before { content: " [insertion start] "; } ins::after { content: " [insertion end] "; } some people who use screen readers deliberately disable announcing content that creates extra verbosity.
<isindex> - HTML: Hypertext Markup Language
WebHTMLElementisindex
kevin replies that he doesn't like the boolean nature of isindex and would prefer a system where everything is searchable and proposes to extend the current www framework with a specific httpd configuration and defined that some uris mapping create search queries.
<mark>: The Mark Text element - HTML: Hypertext Markup Language
WebHTMLElementmark
mark::before, mark::after { clip-path: inset(100%); clip: rect(1px, 1px, 1px, 1px); height: 1px; overflow: hidden; position: absolute; white-space: nowrap; width: 1px; } mark::before { content: " [highlight start] "; } mark::after { content: " [highlight end] "; } some people who use screen readers deliberately disable announcing content that creates extra verbosity.
<menu> - HTML: Hypertext Markup Language
WebHTMLElementmenu
an html menu can be used to create context menus (typically activated by right-clicking another element) or toolbars.
theme-color - HTML: Hypertext Markup Language
WebHTMLElementmetanametheme-color
image credit: from icons & browser colors, created and shared by google and used according to terms described in the creative commons 4.0 attribution license.
<optgroup> - HTML: Hypertext Markup Language
WebHTMLElementoptgroup
the html <optgroup> element creates a grouping of options within a <select> element.
<p>: The Paragraph element - HTML: Hypertext Markup Language
WebHTMLElementp
if extra space is desired, use css properties like margin to create the effect: p { margin-bottom: 2em; // increase white space after a paragraph } specifications specification status comment html living standardthe definition of '<p>' in that specification.
<pre>: The Preformatted Text element - HTML: Hypertext Markup Language
WebHTMLElementpre
example html <p>using css to change the font color is easy.</p> <pre> body { color: red; } </pre> result accessibility concerns it is important to provide an alternate description for any images or diagrams created using preformatted text.
<s> - HTML: Hypertext Markup Language
WebHTMLElements
s::before, s::after { clip-path: inset(100%); clip: rect(1px, 1px, 1px, 1px); height: 1px; overflow: hidden; position: absolute; white-space: nowrap; width: 1px; } s::before { content: " [start of stricken text] "; } s::after { content: " [end of stricken text] "; } some people who use screen readers deliberately disable announcing content that creates extra verbosity.
<slot> - HTML: Hypertext Markup Language
WebHTMLElementslot
the html <slot> element—part of the web components technology suite—is a placeholder inside a web component that you can fill with your own markup, which lets you create separate dom trees and present them together.
<tr>: The Table Row element - HTML: Hypertext Markup Language
WebHTMLElementtr
there are no groups, no cells that span multiple rows or columns, no captions, and only the most basic styling to create lines around the components of the table for something resembling clarity.
<u>: The Unarticulated Annotation (Underline) element - HTML: Hypertext Markup Language
WebHTMLElementu
u>, such as: <em> to denote stress emphasis <b> to draw attention to text <mark> to mark key words or phrases <strong> to indicate that text has strong importance <cite> to mark the titles of books or other publications <i> to denote technical terms, transliterations, thoughts, or names of vessels in western texts to provide textual annotations (as opposed to the non-textual annotations created with <u>), use the <ruby> element.
<video>: The Video Embed element - HTML: Hypertext Markup Language
WebHTMLElementvideo
other usage notes: if you don't specify the controls attribute, the video won't include the browser's default controls; you can create your own custom controls using javascript and the htmlmediaelement api.
<wbr> - HTML: Hypertext Markup Language
WebHTMLElementwbr
the html <wbr> element represents a word break opportunity—a position within text where the browser may optionally break a line, though its line-breaking rules would not otherwise create a break at that location.
is - HTML: Hypertext Markup Language
// create a class for the element class wordcount extends htmlparagraphelement { constructor() { // always call super first in constructor super(); // constructor contents ommitted for brevity ...
itemprop - HTML: Hypertext Markup Language
values the property value of a name-value pair is as given for the first matching case in the following list: if the element has an itemscope attribute the value is the item created by the element.
slot - HTML: Hypertext Markup Language
the slot global attribute assigns a slot in a shadow dom shadow tree to an element: an element with a slot attribute is assigned to the slot created by the <slot> element whose name attribute's value matches that slot attribute's value.
tabindex - HTML: Hypertext Markup Language
it's mostly useful to create accessible widgets with javascript.
x-ms-format-detection - HTML: Hypertext Markup Language
links created through format detection do not appear in the dom.
Link types - HTML: Hypertext Markup Language
shortlink shortlink specification from wikipedia, the free encyclopedia: url shortening some websites create short links to make sharing links via instant messaging easier.
HTML reference - HTML: Hypertext Markup Language
html element reference this page lists all the html elements, which are created using tags.
Microformats - HTML: Hypertext Markup Language
to create a microformats object, h-* class names are used in the class attribute.
Browser detection using the user agent - HTTP
using this information of whether the device has a touchscreen, do not change the entire layout of the website just for touch devices: you will only create more work and maintenance for yourself.
Cross-Origin Resource Sharing (CORS) - HTTP
WebHTTPCORS
the following is an example of a request that will be preflighted: const xhr = new xmlhttprequest(); xhr.open('post', 'https://bar.other/resources/post-here/'); xhr.setrequestheader('x-pingother', 'pingpong'); xhr.setrequestheader('content-type', 'application/xml'); xhr.onreadystatechange = handler; xhr.send('<person><name>arun</name></person>'); the example above creates an xml body to send with the post request.
HTTP conditional requests - HTTP
building a system of etags that creates weak validation may be complex, as it involves knowing the importance of the different elements of a page, but is very useful towards optimizing cache performance.
Content negotiation - HTTP
if you want to use screen size, resolution or other dimensions, a new http header must be created.
Access-Control-Allow-Origin - HTTP
many user agents will grant such documents access to a response with an access-control-allow-origin: "null" header, and any origin can create a hostile document with a "null" origin.
CSP: base-uri - HTTP
the use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the base64-encoded hash of the script or style.
CSP: child-src - HTTP
the use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the base64-encoded hash of the script or style.
CSP: connect-src - HTTP
the use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the base64-encoded hash of the script or style.
CSP: default-src - HTTP
the use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the base64-encoded hash of the script or style.
CSP: font-src - HTTP
the use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the base64-encoded hash of the script or style.
CSP: form-action - HTTP
the use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the base64-encoded hash of the script or style.
CSP: frame-src - HTTP
the use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the base64-encoded hash of the script or style.
CSP: img-src - HTTP
the use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the base64-encoded hash of the script or style.
CSP: manifest-src - HTTP
the use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the base64-encoded hash of the script or style.
CSP: media-src - HTTP
the use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the base64-encoded hash of the script or style.
CSP: navigate-to - HTTP
the use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the base64-encoded hash of the script or style.
CSP: object-src - HTTP
the use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the base64-encoded hash of the script or style.
CSP: prefetch-src - HTTP
the use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the base64-encoded hash of the script or style.
CSP: sandbox - HTTP
allow-scripts allows the page to run scripts (but not create pop-up windows).
CSP: script-src-attr - HTTP
the use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the base64-encoded hash of the script or style.
CSP: script-src-elem - HTTP
the use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the base64-encoded hash of the script or style.
CSP: style-src-attr - HTTP
the use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the base64-encoded hash of the script or style.
CSP: style-src-elem - HTTP
the use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the base64-encoded hash of the script or style.
CSP: trusted-types - HTTP
this directive declares a white-list of trusted type policy names created with trustedtypes.createpolicy from trusted types api.
CSP: worker-src - HTTP
the use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the base64-encoded hash of the script or style.
Feature-Policy: publickey-credentials-get - HTTP
the http feature-policy header publickey-credentials-get directive controls whether the current document is allowed to access web authentcation api to create new public-key credentials, i.e, via navigator.credentials.get({publickey: ..., ...}).
Index - HTTP
WebHTTPHeadersIndex
it only provides a meaning when served with a 3xx (redirection) or 201 (created) status response.
Set-Cookie - HTTP
note that a cookie that has been created with httponly will still be sent with javascript-initiated requests, e.g.
Strict-Transport-Security - HTTP
this creates an opportunity for a man-in-the-middle attack.
Want-Digest - HTTP
the header contains identifiers for one or more digest algorithms that the sender wishes the responder to use to create the digest.
HTTP headers - HTTP
WebHTTPHeaders
if-range creates a conditional range request that is only fulfilled if the given etag or date matches the remote resource.
HTTP Messages - HTTP
WebHTTPMessages
not all responses have one: responses with a status code that sufficiently answers the request without the need for corresponding payload (like 201 created or 204 no content) usually don't.
CONNECT - HTTP
WebHTTPMethodsCONNECT
request has body no successful response has body yes safe no idempotent no cacheable no allowed in html forms no syntax connect www.example.com:443 http/1.1 example some proxy servers might need authority to create a tunnel.
An overview of HTTP - HTTP
WebHTTPOverview
this creates sessions, despite basic http being a state-less protocol.
Protocol upgrade mechanism - HTTP
if you need to create a websocket connection from scratch, you'll have to handle the handshaking process yourself.
HTTP Public Key Pinning (HPKP) - HTTP
web clients such as browsers trust a lot of these cas, which can all create certificates for arbitrary domain names.
200 OK - HTTP
WebHTTPStatus200
the successful result of a put or a delete is often not a 200 ok but a 204 no content (or a 201 created when the resource is uploaded for the first time).
204 No Content - HTTP
WebHTTPStatus204
if the resource is created, 201 created is returned instead.
304 Not Modified - HTTP
WebHTTPStatus304
many developer tools' network panels of browsers create extraneous requests leading to 304 responses, so that access to the local cache is visible to developers.
402 Payment Required - HTTP
WebHTTPStatus402
originally it was created to enable digital cash or (micro) payment systems and would indicate that the requested content is not available until the client makes a payment.
425 Too Early - HTTP
WebHTTPStatus425
the hypertext transfer protocol (http) 425 too early response status code indicates that the server is unwilling to risk processing a request that might be replayed, which creates the potential for a replay attack.
HTTP response status codes - HTTP
WebHTTPStatus
trace: the message body contains the request message as received by the server 201 created the request has succeeded and a new resource has been created as a result.
CSS Houdini
with worklets, you can create modular css, requiring a single line of javascript to import configureable components: no pre-processors, post-processors or javascript frameworks needed.
Enumerability and ownership of properties - JavaScript
enumerable properties are those properties whose internal enumerable flag is set to true, which is the default for properties created via simple assignment or via a property initializer (properties defined via object.defineproperty and such default enumerable to false).
Introduction - JavaScript
prevent code snippets executed in the console from interacting with one-another (e.g., having something created in one console execution being used for a different console execution).
Loops and iteration - JavaScript
for...of statement the for...of statement creates a loop iterating over iterable objects (including array, map, set, arguments object and so on), invoking a custom iteration hook with statements to be executed for the value of each distinct property.
constructor - JavaScript
this.name = 'square'; } get area() { return this.height * this.width; } set area(value) { this.height = value**0.5; this.width = value**0.5; } } another example here the prototype of square class is changed—but the constructor of its base class polygon is still called when a new instance of a square is created.
static - JavaScript
these are often utility functions, such as functions to create or clone objects.
TypeError: X.prototype.y called on incompatible type - JavaScript
it creates a lambda forwarding the argument.
TypeError: can't define property "x": "obj" is not extensible - JavaScript
message typeerror: cannot create property for a non-extensible object (edge) typeerror: can't define property "x": "obj" is not extensible (firefox) typeerror: cannot define property: "x", object is not extensible.
TypeError: property "x" is non-configurable and can't be deleted - JavaScript
examples attempting to delete non-configurable properties non-configurable properties are not super common, but they can be created using object.defineproperty() or object.freeze().
TypeError: invalid assignment to const "x" - JavaScript
const columns = 80; function setupbigscreenenvironment() { const columns = 120; } const and immutability the const declaration creates a read-only reference to a value.
TypeError: "x" is not a non-null object - JavaScript
examples property descriptor expected when methods like object.create() or object.defineproperty() and object.defineproperties() are used, the optional descriptor parameter expects a property descriptor object.
TypeError: "x" is read-only - JavaScript
examples invalid cases read-only properties are not super common, but they can be created using object.defineproperty() or object.freeze().
SyntaxError: redeclaration of formal parameter "x" - JavaScript
if you want to create a new variable, you need to rename it as conflicts with the function parameter already.
ReferenceError: assignment to undeclared variable "x" - JavaScript
declared variables are created before any code is executed.
SyntaxError: function statement requires a name - JavaScript
this doesn't work: function greeter() { german: function () { return "moin"; } } // syntaxerror: function statement requires a name this would work, for example: function greeter() { german: function g() { return "moin"; } } object methods if you intended to create a method of an object, you will need to create an object.
SyntaxError: unterminated string literal - JavaScript
escape sequences work in strings created with either single or double quotes.
TypeError: 'x' is not iterable - JavaScript
function* generate(a, b) { yield a; yield b; } for (let x of generate(1,2)) console.log(x); iterating over a custom iterable custom iterables can be created by implementing the symbol.iterator method.
The arguments object - JavaScript
', 'sage', 'basil', 'oregano', 'pepper', 'parsley'); defining a function that creates html lists this example defines a function that creates a string containing html for a list.
setter - JavaScript
setters are most often used in conjunction with getters to create a type of pseudo-property.
AggregateError() constructor - JavaScript
the aggregateerror() constructor creates an error for several errors that need to be wrapped in a single error.
AggregateError - JavaScript
constructor aggregateerror() creates a new aggregateerror object.
Array.prototype.reduceRight() - JavaScript
calling reduce or reduceright on an empty array without an initial value creates a typeerror.
Array.prototype.concat() - JavaScript
description the concat method creates a new array consisting of the elements in the object on which it is called, followed in order by, for each argument, the elements of that argument (if the argument is an array) or the argument itself (if the argument is not an array).
Array.prototype.copyWithin() - JavaScript
it does not alter the length of this, but it will change its content and create new properties, if necessary.
Array.prototype.flat() - JavaScript
the flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.
Array.prototype.flatMap() - JavaScript
alternative reduce() and concat() var arr = [1, 2, 3, 4]; arr.flatmap(x => [x, x * 2]); // is equivalent to arr.reduce((acc, x) => acc.concat([x, x * 2]), []); // [1, 2, 2, 4, 3, 6, 4, 8] note, however, that this is inefficient and should be avoided for large arrays: in each iteration, it creates a new temporary array that must be garbage-collected, and it copies elements from the current accumulator array into a new array instead of just adding the new elements to the existing array.
Array.prototype.length - JavaScript
var numbers = [1, 2, 3, 4, 5]; if (numbers.length > 3) { numbers.length = 3; } console.log(numbers); // [1, 2, 3] console.log(numbers.length); // 3 create empty array of fixed length var numbers = []; numbers.length = 3; console.log(numbers); // [undefined, undefined, undefined] specifications specification ecmascript (ecma-262)the definition of 'array.length' in that specification.
Array.prototype.sort() - JavaScript
value - b.value; }); // sort by name items.sort(function(a, b) { var namea = a.name.touppercase(); // ignore upper and lowercase var nameb = b.name.touppercase(); // ignore upper and lowercase if (namea < nameb) { return -1; } if (namea > nameb) { return 1; } // names must be equal return 0; }); examples creating, displaying, and sorting an array the following example creates four arrays and displays the original array, then the sorted arrays.
BigInt() constructor - JavaScript
syntax bigint(value); parameters value the numeric value of the object being created.
BigInt.prototype.toLocaleString() - JavaScript
performance when formatting large numbers of numbers, it is better to create a numberformat object and use the function provided by its numberformat.format property.
Boolean() constructor - JavaScript
the boolean() constructor is used to create boolean objects.
DataView() constructor - JavaScript
the dataview() constructor is used to create dataview objects.
Date.UTC() - JavaScript
examples using date.utc() the following statement creates a date object with the arguments treated as utc instead of local: let utcdate = new date(date.utc(2018, 11, 1, 0, 0, 0)); specifications specification ecmascript (ecma-262)the definition of 'date.utc' in that specification.
Date.prototype.toLocaleDateString() - JavaScript
performance when formatting large numbers of dates, it is better to create an intl.datetimeformat object and use the function provided by its format property.
Date.prototype.toLocaleString() - JavaScript
performance when formatting large numbers of dates, it is better to create an intl.datetimeformat object and use the function provided by its format property.
Date.prototype.toLocaleTimeString() - JavaScript
performance when formatting large numbers of dates, it is better to create an intl.datetimeformat object and use the function provided by its format property.
Error.prototype.message - JavaScript
the message property combined with the name property is used by the error.prototype.tostring() method to create a string representation of the error.
Error.prototype.name - JavaScript
the name property, in addition to the message property, is used by the error.prototype.tostring() method to create a string representation of the error.
EvalError() constructor - JavaScript
the evalerror constructor creates a new error regarding the global eval() function.
EvalError - JavaScript
constructor evalerror() creates a new evalerror object.
Function.prototype.call() - JavaScript
function product(name, price) { this.name = name; this.price = price; } function food(name, price) { product.call(this, name, price); this.category = 'food'; } function toy(name, price) { product.call(this, name, price); this.category = 'toy'; } const cheese = new food('feta', 5); const fun = new toy('robot', 40); using call to invoke an anonymous function in this example, we create an anonymous function and use call to invoke it on every object in an array.
Function.prototype.toString() - JavaScript
function.prototype.tostring.call('foo'); // typeerror if the tostring() method is called on built-in function objects or a function created by function.prototype.bind, tostring() returns a native function string which looks like "function () {\n [native code]\n}" if the tostring() method is called on a function created by the function constructor, tostring() returns the source code of a synthesized function declaration named "anonymous" using the provided parameters and function body.
InternalError() constructor - JavaScript
the internalerror() constructor creates an error that indicates an error that occurred internally in the javascript engine.
InternalError - JavaScript
constructor internalerror() creates a new internalerror object.
Intl.Collator - JavaScript
constructor intl.collator() creates a new collator object.
Intl.DateTimeFormat - JavaScript
constructor intl.datetimeformat() creates a new datetimeformat object.
Intl.DisplayNames() constructor - JavaScript
the intl.displaynames() constructor creates objects that enables the consistent translation of language, region and script display names.
Intl​.ListFormat.prototype​.format() - JavaScript
examples using format the following example shows how to create a list formatter using the english language.
Intl.NumberFormat() constructor - JavaScript
the intl.numberformat() constructor creates objects that enable language sensitive number formatting.
Intl.NumberFormat - JavaScript
constructor intl.numberformat() creates a new numberformat object.
Intl.PluralRules() constructor - JavaScript
the intl.pluralrules() constructor creates intl.pluralrules objects.
Intl.PluralRules - JavaScript
constructor intl.pluralrules.pluralrules() creates a new intl.pluralrules object.
Map() constructor - JavaScript
the map() constructor creates map objects.
Math.E - JavaScript
property attributes of math.e writable no enumerable no configurable no description because e is a static property of math, you always use it as math.e, rather than as a property of a math object you created (math is not a constructor).
Math.LN10 - JavaScript
property attributes of math.ln10 writable no enumerable no configurable no description because ln10 is a static property of math, you always use it as math.ln10, rather than as a property of a math object you created (math is not a constructor).
Math.LN2 - JavaScript
property attributes of math.ln2 writable no enumerable no configurable no description because ln2 is a static property of math, you always use it as math.ln2, rather than as a property of a math object you created (math is not a constructor).
Math.LOG10E - JavaScript
property attributes of math.log10e writable no enumerable no configurable no description because log10e is a static property of math, you always use it as math.log10e, rather than as a property of a math object you created (math is not a constructor).
Math.LOG2E - JavaScript
property attributes of math.log2e writable no enumerable no configurable no description because log2e is a static property of math, you always use it as math.log2e, rather than as a property of a math object you created (math is not a constructor).
Math.PI - JavaScript
property attributes of math.pi writable no enumerable no configurable no description because pi is a static property of math, you always use it as math.pi, rather than as a property of a math object you created (math is not a constructor).
Math.SQRT1_2 - JavaScript
property attributes of math.sqrt1_2 writable no enumerable no configurable no description because sqrt1_2 is a static property of math, you always use it as math.sqrt1_2, rather than as a property of a math object you created (math is not a constructor).
Math.SQRT2 - JavaScript
property attributes of math.sqrt2 writable no enumerable no configurable no description because sqrt2 is a static property of math, you always use it as math.sqrt2, rather than as a property of a math object you created (math is not a constructor).
Math.abs() - JavaScript
description because abs() is a static method of math, you always use it as math.abs(), rather than as a method of a math object you created (math is not a constructor).
Math.acos() - JavaScript
because acos() is a static method of math, you always use it as math.acos(), rather than as a method of a math object you created (math is not a constructor).
Math.acosh() - JavaScript
description because acosh() is a static method of math, you always use it as math.acosh(), rather than as a method of a math object you created (math is no constructor).
Math.asin() - JavaScript
because asin() is a static method of math, you always use it as math.asin(), rather than as a method of a math object you created (math is not a constructor).
Math.asinh() - JavaScript
description because asinh() is a static method of math, you always use it as math.asinh(), rather than as a method of a math object you created (math is not a constructor).
Math.atan() - JavaScript
because atan() is a static method of math, you always use it as math.atan(), rather than as a method of a math object you created (math is not a constructor).
Math.atan2() - JavaScript
because atan2() is a static method of math, you always use it as math.atan2(), rather than as a method of a math object you created (math is not a constructor).
Math.atanh() - JavaScript
description because atanh() is a static method of math, you always use it as math.atanh(), rather than as a method of a math object you created (math is not a constructor).
Math.cbrt() - JavaScript
description because cbrt() is a static method of math, you always use it as math.cbrt(), rather than as a method of a math object you created (math is not a constructor).
Math.ceil() - JavaScript
description because ceil() is a static method of math, you always use it as math.ceil(), rather than as a method of a math object you created (math is not a constructor).
Math.cos() - JavaScript
because cos() is a static method of math, you always use it as math.cos(), rather than as a method of a math object you created (math is not a constructor).
Math.cosh() - JavaScript
description because cosh() is a static method of math, you always use it as math.cosh(), rather than as a method of a math object you created (math is not a constructor).
Math.exp() - JavaScript
description because exp() is a static method of math, you always use it as math.exp(), rather than as a method of a math object you created (math is not a constructor).
Math.expm1() - JavaScript
description because expm1() is a static method of math, you always use it as math.expm1(), rather than as a method of a math object you created (math is not a constructor).
Math.floor() - JavaScript
description because floor() is a static method of math, you always use it as math.floor(), rather than as a method of a math object you created (math is not a constructor).
Math.hypot() - JavaScript
because hypot() is a static method of math, you always use it as math.hypot(), rather than as a method of a math object you created (math is not a constructor).
Math.imul() - JavaScript
because imul() is a static method of math, you always use it as math.imul(), rather than as a method of a math object you created (math is not a constructor).
Math.log() - JavaScript
because log() is a static method of math, you always use it as math.log(), rather than as a method of a math object you created (math is not a constructor).
Math.log10() - JavaScript
because log10() is a static method of math, you always use it as math.log10(), rather than as a method of a math object you created (math is not a constructor).
Math.log1p() - JavaScript
because log1p() is a static method of math, you always use it as math.log1p(), rather than as a method of a math object you created (math is not a constructor).
Math.log2() - JavaScript
because log2() is a static method of math, you always use it as math.log2(), rather than as a method of a math object you created (math is not a constructor).
Math.min() - JavaScript
description because min() is a static method of math, you always use it as math.min(), rather than as a method of a math object you created (math is not a constructor).
Math.pow() - JavaScript
because pow() is a static method of math, you always use it as math.pow(), rather than as a method of a math object you created (math has no constructor).
Math.round() - JavaScript
because round() is a static method of math, you always use it as math.round(), rather than as a method of a math object you created (math has no constructor).
Math.sign() - JavaScript
description because sign() is a static method of math, you always use it as math.sign(), rather than as a method of a math object you created (math is not a constructor).
Math.sin() - JavaScript
because sin() is a static method of math, you always use it as math.sin(), rather than as a method of a math object you created (math is not a constructor).
Math.sinh() - JavaScript
description because sinh() is a static method of math, you always use it as math.sinh(), rather than as a method of a math object you created (math is not a constructor).
Math.sqrt() - JavaScript
because sqrt() is a static method of math, you always use it as math.sqrt(), rather than as a method of a math object you created (math is not a constructor).
Math.tan() - JavaScript
because tan() is a static method of math, you always use it as math.tan(), rather than as a method of a math object you created (math is not a constructor).
Math.tanh() - JavaScript
description because tanh() is a static method of math, you always use it as math.tanh(), rather than as a method of a math object you created (math is not a constructor).
Math.trunc() - JavaScript
because trunc() is a static method of math, you always use it as math.trunc(), rather than as a method of a math object you created (math is not a constructor).
Number.EPSILON - JavaScript
you do not have to create a number object to access this static property (use number.epsilon).
Number.MAX_SAFE_INTEGER - JavaScript
because max_safe_integer is a static property of number, you always use it as number.max_safe_integer, rather than as a property of a number object you created.
Number.MAX_VALUE - JavaScript
because max_value is a static property of number, you always use it as number.max_value, rather than as a property of a number object you created.
Number.MIN_SAFE_INTEGER - JavaScript
because min_safe_integer is a static property of number, you always use it as number.min_safe_integer, rather than as a property of a number object you created.
Number.MIN_VALUE - JavaScript
because min_value is a static property of number, you always use it as number.min_value, rather than as a property of a number object you created.
Number.NEGATIVE_INFINITY - JavaScript
because negative_infinity is a static property of number, you always use it as number.negative_infinity, rather than as a property of a number object you created.
Number.NaN - JavaScript
you do not have to create a number object to access this static property (use number.nan).
Number.POSITIVE_INFINITY - JavaScript
because positive_infinity is a static property of number, you always use it as number.positive_infinity, rather than as a property of a number object you created.
Number.prototype.toLocaleString() - JavaScript
performance when formatting large numbers of numbers, it is better to create a numberformat object and use the function provided by its numberformat.format property.
Number - JavaScript
literal syntax 123 // one-hundred twenty-three 123.0 // same 123 === 123.0 // true function syntax number('123') // returns the number 123 number('123') === 123 // true number("unicorn") // nan number(undefined) // nan constructor number() creates a new number value.
Object.assign() - JavaScript
bug 1207182 on firefox) object.getownpropertysymbols(obj); // [symbol(foo)] properties on the prototype chain and non-enumerable properties cannot be copied const obj = object.create({ foo: 1 }, { // foo is on obj's prototype chain.
Object.entries() - JavaScript
, 'bar'], ['baz', 42] ] // array like object const obj = { 0: 'a', 1: 'b', 2: 'c' }; console.log(object.entries(obj)); // [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ] // array like object with random key ordering const anobj = { 100: 'a', 2: 'b', 7: 'c' }; console.log(object.entries(anobj)); // [ ['2', 'b'], ['7', 'c'], ['100', 'a'] ] // getfoo is property which isn't enumerable const myobj = object.create({}, { getfoo: { value() { return this.foo; } } }); myobj.foo = 'bar'; console.log(object.entries(myobj)); // [ ['foo', 'bar'] ] // non-object argument will be coerced to an object console.log(object.entries('foo')); // [ ['0', 'f'], ['1', 'o'], ['2', 'o'] ] // returns an empty array for any primitive type, since primitives have no own properties console.log(object.entries(100)); // [ ] // iter...
Object.freeze() - JavaScript
it does not create a frozen copy.
Object.getOwnPropertyNames() - JavaScript
// logs ["0", "1", "2"] // logging property names and values using array.foreach object.getownpropertynames(obj).foreach( function (val, idx, array) { console.log(val + ' -> ' + obj[val]); } ); // logs // 0 -> a // 1 -> b // 2 -> c // non-enumerable property var my_obj = object.create({}, { getfoo: { value: function() { return this.foo; }, enumerable: false } }); my_obj.foo = 1; console.log(object.getownpropertynames(my_obj).sort()); // logs ["foo", "getfoo"] if you want only the enumerable properties, see object.keys() or use a for...in loop (note that this will also return enumerable properties found along the prototype chain for the object unless the latter i...
Object.getPrototypeOf() - JavaScript
examples using getprototypeof var proto = {}; var obj = object.create(proto); object.getprototypeof(obj) === proto; // true non-object coercion in es5, it will throw a typeerror exception if the obj parameter isn't an object.
Object.prototype.hasOwnProperty() - JavaScript
e dragons' }; foo.hasownproperty('bar'); // always returns false // use another object's hasownproperty // and call it with 'this' set to foo ({}).hasownproperty.call(foo, 'bar'); // true // it's also possible to use the hasownproperty property // from the object prototype for this purpose object.prototype.hasownproperty.call(foo, 'bar'); // true note that in the last case there are no newly created objects.
Object.prototype.isPrototypeOf() - JavaScript
examples using isprototypeof this example demonstrates that baz.prototype, bar.prototype, foo.prototype and object.prototype exist in the prototype chain for object baz: function foo() {} function bar() {} function baz() {} bar.prototype = object.create(foo.prototype); baz.prototype = object.create(bar.prototype); var baz = new baz(); console.log(baz.prototype.isprototypeof(baz)); // true console.log(bar.prototype.isprototypeof(baz)); // true console.log(foo.prototype.isprototypeof(baz)); // true console.log(object.prototype.isprototypeof(baz)); // true isprototypeof() method, along with the instanceof operator particularly comes in handy if...
Object.keys() - JavaScript
sole.log(object.keys(arr)); // console: ['0', '1', '2'] // array-like object const obj = { 0: 'a', 1: 'b', 2: 'c' }; console.log(object.keys(obj)); // console: ['0', '1', '2'] // array-like object with random key ordering const anobj = { 100: 'a', 2: 'b', 7: 'c' }; console.log(object.keys(anobj)); // console: ['2', '7', '100'] // getfoo is a property which isn't enumerable const myobj = object.create({}, { getfoo: { value: function () { return this.foo; } } }); myobj.foo = 1; console.log(object.keys(myobj)); // console: ['foo'] if you want all properties—including non-enumerables—see object.getownpropertynames().
Object.values() - JavaScript
0: 'a', 1: 'b', 2: 'c' }; console.log(object.values(arraylikeobj1 )); // ['a', 'b', 'c'] // array-like object with random key ordering // when using numeric keys, the values are returned in the keys' numerical order const arraylikeobj2 = { 100: 'a', 2: 'b', 7: 'c' }; console.log(object.values(arraylikeobj2 )); // ['b', 'c', 'a'] // getfoo is property which isn't enumerable const my_obj = object.create({}, { getfoo: { value: function() { return this.foo; } } }); my_obj.foo = 'bar'; console.log(object.values(my_obj)); // ['bar'] // non-object argument will be coerced to an object console.log(object.values('foo')); // ['f', 'o', 'o'] specifications specification ecmascript (ecma-262)the definition of 'object.values' in that specification.
Promise() constructor - JavaScript
examples creating a new promise a promise object is created using the new keyword and its constructor.
Promise.any() - JavaScript
status: ${response.status}`); } else { return response.blob(); } }) } let coffee = fetchanddecode('coffee.jpg'); let tea = fetchanddecode('tea.jpg'); promise.any([coffee, tea]).then(value => { let objecturl = url.createobjecturl(value); let image = document.createelement('img'); image.src = objecturl; document.body.appendchild(image); }) .catch(e => { console.log(e.message); }); specifications specification promise.any ...
Promise.prototype.catch() - JavaScript
n() { throw new error('uncaught exception!'); }, 1000); }); p2.catch(function(e) { console.error(e); // this is never called }); // errors thrown after resolve is called will be silenced var p3 = new promise(function(resolve, reject) { resolve(); throw new error('silenced exception!'); }); p3.catch(function(e) { console.error(e); // this is never called }); if it is resolved //create a promise which would not call onreject var p1 = promise.resolve("calling next"); var p2 = p1.catch(function (reason) { //this is never called console.error("catch p1!"); console.error(reason); }); p2.then(function (value) { console.log("next promise's onfulfilled"); /* next promise's onfulfilled */ console.log(value); /* calling next */ }, function (reason) { console.lo...
Promise.prototype.finally() - JavaScript
the finally() method is very similar to calling .then(onfinally, onfinally) however there are a couple of differences: when creating a function inline, you can pass it once, instead of being forced to either declare it twice, or create a variable for it a finally callback will not receive any argument, since there's no reliable means of determining if the promise was fulfilled or rejected.
Promise.prototype.then() - JavaScript
function() { // return promise here, that will be rejected with 'error' after 1 second return new promise(rejectlater); }); p3.then(function(v) { // not called console.log('resolved', v); }, function(e) { console.error('rejected', e); // "rejected", 'error' }); window.setimmediate style promise-based polyfill using a function.prototype.bind() reflect.apply (reflect.apply()) method to create a (non-cancellable) window.setimmediate-style function.
handler.get() - JavaScript
interceptions this trap can intercept these operations: property access: proxy[foo]and proxy.bar inherited property access: object.create(proxy)[foo] reflect.get() invariants if the following invariants are violated, the proxy will throw a typeerror: the value reported for a property must be the same as the value of the corresponding target object property if the target object property is a non-writable, non-configurable own data property.
handler.has() - JavaScript
interceptions this trap can intercept these operations: property query: foo in proxy inherited property query: foo in object.create(proxy) with check: with(proxy) { (foo); } reflect.has() invariants if the following invariants are violated, the proxy will throw a typeerror: a property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object.
handler.set() - JavaScript
interceptions this trap can intercept these operations: property assignment: proxy[foo] = bar and proxy.foo = bar inherited property assignment: object.create(proxy)[foo] = bar reflect.set() invariants if the following invariants are violated, the proxy will throw a typeerror: cannot change the value of a property to be different from the value of the corresponding target object property if the corresponding target object property is a non-writable, non-configurable data property.
RangeError() constructor - JavaScript
the rangeerror() constructor creates an error when a value is not in the set or range of allowed values.
ReferenceError - JavaScript
constructor referenceerror() creates a new referenceerror object.
Reflect.getPrototypeOf() - JavaScript
examples using reflect.getprototypeof() reflect.getprototypeof({}) // object.prototype reflect.getprototypeof(object.prototype) // null reflect.getprototypeof(object.create(null)) // null compared to object.getprototypeof() // same result for objects object.getprototypeof({}) // object.prototype reflect.getprototypeof({}) // object.prototype // both throw in es5 for non-objects object.getprototypeof('foo') // throws typeerror reflect.getprototypeof('foo') // throws typeerror // in es2015 only reflect throws, object coerces non-objects object.getprototypeo...
Reflect.setPrototypeOf() - JavaScript
let target = {} let proto = object.create(target) reflect.setprototypeof(target, proto) // false specifications specification ecmascript (ecma-262)the definition of 'reflect.setprototypeof' in that specification.
RegExp.prototype.exec() - JavaScript
it will create an infinite loop if there is a match, due to the lastindex property being reset upon each iteration.
Set() constructor - JavaScript
the set constructor lets you create set objects that store unique values of any type, whether primitive values or object references.
Set.prototype.delete() - JavaScript
const setobj = new set(); // create a new set.
String() constructor - JavaScript
the string constructor is used to create a new string object.
String.prototype.big() - JavaScript
the big() method creates a <big> html element that causes a string to be displayed in a big font.
String.prototype.blink() - JavaScript
the blink() method creates a <blink> html element that causes a string to blink.
String.prototype.bold() - JavaScript
the bold() method creates a <b> html element that causes a string to be displayed as bold.
String.prototype.fixed() - JavaScript
the fixed() method creates a <tt> html element that causes a string to be displayed in fixed-pitch font.
String.prototype.fontcolor() - JavaScript
the fontcolor() method creates a <font> html element that causes a string to be displayed in the specified font color.
String.prototype.fontsize() - JavaScript
the fontsize() method creates a <font> html element that causes a string to be displayed in the specified font size.
String.prototype.italics() - JavaScript
the italics() method creates an <i> html element that causes a string to be italic.
String.prototype.localeCompare() - JavaScript
performance when comparing large numbers of strings, such as in sorting large arrays, it is better to create an intl.collator object and use the function provided by its compare property.
String.prototype.matchAll() - JavaScript
nst str = 'table football, foosball'; const matches = str.matchall(regexp); for (const match of matches) { console.log(`found ${match[0]} start=${match.index} end=${match.index + match[0].length}.`); } // expected output: "found football start=6 end=14." // expected output: "found foosball start=16 end=24." // matches iterator is exhausted after the for..of iteration // call matchall again to create a new iterator array.from(str.matchall(regexp), m => m[0]); // array [ "football", "foosball" ] matchall will throw an exception if the g flag is missing.
String.prototype.replace() - JavaScript
function (replacement) a function to be invoked to create the new substring to be used to replace the matches to the given regexp or substr.
String.prototype.replaceAll() - JavaScript
function (replacement) a function to be invoked to create the new substring to be used to replace the matches to the given regexp or substr.
String.prototype.slice() - JavaScript
examples using slice() to create a new string the following example uses slice() to create a new string.
String.prototype.small() - JavaScript
the small() method creates a <small> html element that causes a string to be displayed in a small font.
String.prototype.strike() - JavaScript
the strike() method creates a <strike> html element that causes a string to be displayed as struck-out text.
String.prototype.sub() - JavaScript
the sub() method creates a <sub> html element that causes a string to be displayed as subscript.
String.prototype.sup() - JavaScript
the sup() method creates a <sup> html element that causes a string to be displayed as superscript.
String.prototype.trim() - JavaScript
polyfill running the following code before any other code will create trim() if it's not natively available.
Symbol.prototype.description - JavaScript
description symbol objects can be created with an optional description which can be used for debugging but not to access the symbol itself.
Symbol.keyFor() - JavaScript
examples using keyfor var globalsym = symbol.for('foo'); // create a new global symbol symbol.keyfor(globalsym); // "foo" var localsym = symbol(); symbol.keyfor(localsym); // undefined // well-known symbols are not symbols registered // in the global symbol registry symbol.keyfor(symbol.iterator) // undefined specifications specification ecmascript (ecma-262)the definition of 'symbol.keyfor' in that specification.
Symbol.species - JavaScript
the well-known symbol symbol.species specifies a function-valued property that the constructor function uses to create derived objects.
Symbol.toStringTag - JavaScript
for example, to acccess the symbol.tostringtag property on htmlbuttonelement: let test = document.createelement('button'); test.tostring(); // returns [object htmlbuttonelement] test[symbol.tostringtag]; // returns htmlbuttonelement specifications specification ecmascript (ecma-262)the definition of 'symbol.tostringtag' in that specification.
SyntaxError() constructor - JavaScript
the syntaxerror constructor creates a new error object that represents an error when trying to interpret syntactically invalid code.
SyntaxError - JavaScript
constructor syntaxerror() creates a new syntaxerror object.
TypeError() constructor - JavaScript
the typeerror() constructor creates a new error when an operation could not be performed, typically (but not exclusively) when a value is not of the expected type.
TypeError - JavaScript
constructor typeerror() creates a new typeerror object.
TypedArray.prototype.toString() - JavaScript
for example, the following code creates a typed array and uses tostring to convert the array to a string.
URIError() constructor - JavaScript
the urierror() constructor creates an error when a global uri handling function was used in a wrong way.
URIError - JavaScript
constructor urierror() creates a new urierror object.
WeakMap() constructor - JavaScript
the weakmap() constructor creates weakmap objects which are a collections of key/value pairs in which the keys are weakly referenced.
WeakMap - JavaScript
constructor weakmap() creates a new weakmap object.
WeakRef() constructor - JavaScript
the weakref constructor creates a weakref object referring to a given target object.
WeakSet() constructor - JavaScript
the weakset constructor lets you create weakset objects that store weakly held objects in a collection.
WebAssembly.Instance - JavaScript
constructor webassembly.instance() creates a new instance object.
WebAssembly.Memory.prototype.buffer - JavaScript
examples using buffer the following example (see memory.html on github, and view it live also) fetches and instantiates the loaded memory.wasm byte code using the webassembly.instantiatestreaming() method, while importing the memory created in the line above.
WebAssembly.Memory.prototype.grow() - JavaScript
examples using grow the following example creates a new webassembly memory instance with an initial size of 1 page (64kib), and a maximum size of 10 pages (640kib).
WebAssembly.Module.exports() - JavaScript
when the module is received, we create an instance from it using the webassembly.instantiate() method, invoke an exported function from inside it, then show how we can return information on the available exports on a module using webassembly.module.exports.
WebAssembly.Table.prototype.grow() - JavaScript
examples using grow the following example creates a new webassembly table instance with an initial size of 2 and a maximum size of 10.
WebAssembly.Table.prototype.length - JavaScript
syntax table.length; examples using length the following example creates a new webassembly table instance with an initial size of 2 and a maximum size of 10.
WebAssembly.instantiateStreaming() - JavaScript
importobject optional an object containing the values to be imported into the newly-created instance, such as functions or webassembly.memory objects.
decodeURI() - JavaScript
the decodeuri() function decodes a uniform resource identifier (uri) previously created by encodeuri() or by a similar routine.
decodeURIComponent() - JavaScript
the decodeuricomponent() function decodes a uniform resource identifier (uri) component previously created by encodeuricomponent or by a similar routine.
uneval() - JavaScript
the uneval() function creates a string representation of the source code of an object.
Standard built-in objects - JavaScript
other objects in the global scope are either created by the user script or provided by the host application.
Iteration protocols - JavaScript
however, it is easy to create an object that satisfies both the iterator and iterable protocols (as shown in the example below).
Lexical grammar - JavaScript
bigint literals are created by appending n to the end of an integer.
Comma operator (,) - JavaScript
this lets you create a compound expression in which multiple expressions are evaluated, with the compound expression's final value being the value of the rightmost of its member expressions.
Destructuring assignment - JavaScript
]; console.log(a); // 10 console.log(b); // 20 console.log(rest); // [30, 40, 50] ({ a, b } = { a: 10, b: 20 }); console.log(a); // 10 console.log(b); // 20 // stage 4(finished) proposal ({a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40}); console.log(a); // 10 console.log(b); // 20 console.log(rest); // {c: 30, d: 40} description the object and array literal expressions provide an easy way to create ad hoc packages of data.
Optional chaining (?.) - JavaScript
this is equivalent to the following, except that the temporary variable is in fact not created: let temp = obj.first; let nestedprop = ((temp === null || temp === undefined) ?
async function expression - JavaScript
the main difference between an async function expression and an async function statement is the function name, which can be omitted in async function expressions to create anonymous functions.
class expression - JavaScript
const foo = class { constructor() {} bar() { return 'hello world!'; } }; const instance = new foo(); instance.bar(); // "hello world!" foo.name; // "foo" named class expressions if you want to refer to the current class inside the class body, you can create a named class expression.
function* expression - JavaScript
the main difference between a function* expression and a function* statement is the function name, which can be omitted in function* expressions to create anonymous generator functions.
in operator - JavaScript
for example, you can specify a string created with the string constructor, but you cannot specify a string literal.
Expressions and operators - JavaScript
new the new operator creates an instance of a constructor.
block - JavaScript
examples block scoping rules with var or function declaration in non-strict mode variables declared with var or created by function declarations in non-strict mode do not have block scope.
do...while - JavaScript
the do...while statement creates a loop that executes a specified statement until the test condition evaluates to false.
export - JavaScript
in other words, one can create a single module concentrating various exports from various modules.
for...in - JavaScript
objects created from built–in constructors like array and object have inherited non–enumerable properties from object.prototype and string.prototype, such as string's indexof() method or object's tostring() method.
for...of - JavaScript
the for...of statement creates a loop iterating over iterable objects, including: built-in string, array, array-like objects (e.g., arguments or nodelist), typedarray, map, set, and user-defined iterables.
if...else - JavaScript
description multiple if...else statements can be nested to create an else if clause.
import.meta - JavaScript
the import.meta object is created by the ecmascript implementation, with a null prototype.
try...catch - JavaScript
conditional catch-blocks you can create "conditional catch-blocks" by combining try...catch blocks with if...else if...else structures, like this: try { myroutine(); // may throw three types of exceptions } catch (e) { if (e instanceof typeerror) { // statements to handle typeerror exceptions } else if (e instanceof rangeerror) { // statements to handle rangeerror exceptions } else if (e instanceof evalerror) { // ...
while - JavaScript
the while statement creates a loop that executes a specified statement as long as the test condition evaluates to true.
Template literals (Template strings) - JavaScript
function tag(strings) { console.log(strings.raw[0]); } tag`string text line 1 \n string text line 2`; // logs "string text line 1 \n string text line 2" , // including the two characters '\' and 'n' in addition, the string.raw() method exists to create raw strings—just like the default template function and string concatenation would create.
shortcuts - Web app manifests
examples the following is a list of shortcuts a calendar app might have: "shortcuts" : [ { "name": "today's agenda", "url": "/today", "description": "list of events planned for today" }, { "name": "new event", "url": "/create/event" }, { "name": "new reminder", "url": "/create/reminder" } ] specification specification status comment feedback web app manifestthe definition of 'shortcuts' in that specification.
<mmultiscripts> - MathML
the mathml <mmultiscripts> element allows you to create tensor-like objects.
<mtable> - MathML
WebMathMLElementmtable
the mathml <mtable> element allows you to create tables or matrices.
Autoplay guide for media and Web Audio APIs - Web media technologies
this sets the autoplay property on the element to true, and when autoplay is true, the media will automatically begin to play as soon as possible after the following have occurred: the page is allowed to use autoplay functionality the element has been created during page load enough media has been received to begin playback and continue to play through to the end of the media without interruption, assuming there are no dramatic changes in network performance or bandwidth.
Digital audio concepts - Web media technologies
special low frequency enhancement (lfe) channels provide the signal for special speakers designed to produce the low frequency sounds and vibration to create a visceral sensation when listening to the audio.
Digital video concepts - Web media technologies
the final color image is created by the brain, which essentially layers the colors onto the greyscale pixels.
Codecs used by WebRTC - Web media technologies
that's done for each transceiver on the rtcpeerconnection; once all of the transceivers have been updated, we call the onnegotiationneeded event handler, which will create a new offer, update the local description, send the offer along to the remote peer, and so on, thereby triggering the renegotiation of the connection.
Mapping the width and height attributes of media container elements to their aspect-ratio - Web media technologies
without the width and height attributes, no placeholder space would be created, and when the image finally loaded you would get a noticeable jank in the page layout.
OpenSearch description format
reference material opensearch documentation safari 8.0 release notes: quick website search microsoft edge dev guide: search provider discovery the chromium projects: tab to search imdb.com has a working osd.xml opensearch plugin generator ready2search - create opensearch plugins.
Recommended Web Performance Timings: How long is too long? - Web Performance
while a slower than 100ms reaction may create a disconnect between the user interaction and the response, a 100 to 200ms transition for a response may help the user notice the response their interaction initiated, such as a menu opening.
Navigation and resource timings - Web Performance
you can also create marks: performance.getentriesbytype('navigation').foreach((navigation) => { console.dir(navigation); }); performance.getentriesbytype('resource').foreach((resource) => { console.dir(resource); }); performance.getentriesbytype('mark').foreach((mark) => { console.dir(mark); }); performance.getentriesbytype("measure").foreach((measure) => { console.dir(measure); }); performance.getentri...
Optimizing startup performance - Web Performance
instead, you should write your code so that your app creates a web worker that does as much as possible in a background thread (for example, fetching and processing data.) then, anything that must be done on the main thread (such as user events and rendering ui) should be broken up into small pieces so that the app's event loop continues to cycle while it starts up.
Privacy, permissions, and information security
in this article, we examine how to create web content that minimizes the risk of users' personal information or imagery being obtained unexpectedly by third parties.
Making PWAs work offline with Service workers - Progressive web apps (PWAs)
first, a variable for storing the cache name is created, and the app shell files are listed in one array.
Media - Progressive web apps (PWAs)
place your mouse over the items in this list to see the actual pointer shapes in your browser: selector selects pointer indicating a link wait indicating that the program cannot accept input progress indicating that the program is working, but can still accept input default the default (usually an arrow) an outline property creates an outline that is often used to indicate keyboard focus.
Applying SVG effects to HTML content - SVG: Scalable Vector Graphics
using embedded svg to apply an svg effect using css styles, you first need to create the css style that references the svg to apply.
clipPathUnits - SVG: Scalable Vector Graphics
value userspaceonuse | objectboundingbox default value userspaceonuse animatable yes userspaceonuse this value indicates that all coordinates inside the <clippath> element refer to the user coordinate system as defined when the clipping path was created.
dur - SVG: Scalable Vector Graphics
WebSVGAttributedur
itʼs possible to combine those time representations to create some complex durations like hh:mm:ss.iii or mm:ss.iii.
glyph-name - SVG: Scalable Vector Graphics
the glyph names can be referenced in kerning definitions created by <hkern> and <vkern> elements.
maskContentUnits - SVG: Scalable Vector Graphics
value userspaceonuse | objectboundingbox default value userspaceonuse animatable yes userspaceonuse this value indicates that all coordinates inside the <mask> element refer to the user coordinate system as defined when the mask was created.
maskUnits - SVG: Scalable Vector Graphics
value userspaceonuse | objectboundingbox default value objectboundingbox animatable yes userspaceonuse this value indicates that all coordinates for the geometry attributes refer to the user coordinate system as defined when the mask was created.
overflow - SVG: Scalable Vector Graphics
it has the same parameter values and meaning as the css overflow property, however, the following additional points apply: if it has a value of visible, the attribute has no effect (i.e., a clipping rectangle is not created).
patternContentUnits - SVG: Scalable Vector Graphics
value userspaceonuse | objectboundingbox default value userspaceonuse animatable yes userspaceonuse this value indicates that all coordinates inside the <pattern> element refer to the user coordinate system as defined when the pattern tile was created.
target - SVG: Scalable Vector Graphics
WebSVGAttributetarget
if it does not exist, it is created (the same as '_blank', except that it now has a name).
xlink:title - SVG: Scalable Vector Graphics
it may be used, for example, to make titles available to applications used by visually impaired users, or to create a table of links, or to present help text that appears when a user lets a mouse pointer hover over a starting resource.
<animate> - SVG: Scalable Vector Graphics
WebSVGElementanimate
consider providing a mechanism for pausing or disabling animation, as well as using the reduced motion media query to create a complimentary experience for users who have expressed a preference for no animated experiences.
<cursor> - SVG: Scalable Vector Graphics
WebSVGElementcursor
a recommended approach for defining a platform-independent custom cursor is to create a png image and define a cursor element that references the png image and identifies the exact position within the image which is the pointer position (i.e., the hot spot).
<defs> - SVG: Scalable Vector Graphics
WebSVGElementdefs
objects created inside a <defs> element are not rendered directly.
<ellipse> - SVG: Scalable Vector Graphics
WebSVGElementellipse
the <ellipse> element is an svg basic shape, used to create ellipses based on a center coordinate, and both their x and y radius.
<feColorMatrix> - SVG: Scalable Vector Graphics
every pixel's color value [r,g,b,a] is matrix multiplied by a 5 by 5 color matrix to create new color [r',g',b',a'].
<feDropShadow> - SVG: Scalable Vector Graphics
the svg <fedropshadow> filter primitive creates a drop shadow of the input image.
<fePointLight> - SVG: Scalable Vector Graphics
the <fepointlight> filter primitive defines a light source which allows to create a point light effect.
<feSpotLight> - SVG: Scalable Vector Graphics
the <fespotlight> svg filter primitive defines a light source which allows to create a spotlight effect.
<feTurbulence> - SVG: Scalable Vector Graphics
the <feturbulence> svg filter primitive creates an image using the perlin turbulence function.
<line> - SVG: Scalable Vector Graphics
WebSVGElementline
the <line> element is an svg basic shape used to create a line connecting two points.
<path> - SVG: Scalable Vector Graphics
WebSVGElementpath
all the basic shapes can be created with a path element.
SVG element reference - SVG: Scalable Vector Graphics
WebSVGElement
« svg / svg attribute reference » svg drawings and images are created using a wide array of elements which are dedicated to the construction, drawing, and layout of vector images and diagrams.
Example - SVG: Scalable Vector Graphics
if( this.elt === null ) { var svg = 'http://www.w3.org/2000/svg'; this.elt = document.createelementns(svg,'line'); this.elt.setattributens(null,'stroke','green'); this.elt.setattributens(null,'stroke-width','3'); this.elt.setattributens(null,'stroke-opacity','0.5'); display().appendchild( this.elt ); } this.elt.setattributens(null,'x1',old_x); this.elt.setattributens(null,'y1',old_y); this.elt.setattributens(null,'x2',this.x); this.elt.setattributens(null...
Project - SVG: Scalable Vector Graphics
WebSVGProject
this page was auto-generated because a user created a sub-page to this page.
Replaced Element - SVG: Scalable Vector Graphics
this page was auto-generated because a user created a sub-page to this page.
Scripting - SVG: Scalable Vector Graphics
WebSVGScripting
function myrect(x,y,w,h,message){ this.message=message this.rect=document.createelementns("http://www.w3.org/2000/svg","rect") this.rect.setattributens(null,"x",x) this.rect.setattributens(null,"y",y) this.rect.setattributens(null,"width",w) this.rect.setattributens(null,"height",h) document.documentelement.appendchild(this.rect) this.rect.addeventlistener("click",this,false) this.handleevent= function(evt){ switch (evt.type){ case "click": alert(this.m...
Sizing - SVG: Scalable Vector Graphics
WebSVGSizing
this page was auto-generated because a user created a sub-page to this page.
Basic Transformations - SVG: Scalable Vector Graphics
this way you can also simply create new coordinate systems by utilizing the viewbox, width and height of the inner svg element.
Introduction - SVG: Scalable Vector Graphics
it can be used to create an image either by specifying all the lines and shapes necessary, by modifying already existing raster images, or by a combination of both.
Patterns - SVG: Scalable Vector Graphics
WebSVGTutorialPatterns
to create something like this, both the pattern and its contents must be drawn in the current userspace, so they don't change shape if the object does: <pattern id="pattern" x="10" y="10" width="50" height="50" patternunits="userspaceonuse"> <rect x="0" y="0" width="50" height="50" fill="skyblue"/> <rect x="0" y="0" width="25" height="25" fill="url(#gradient2)"/> <circle cx="25" cy="25" r="20" f...
SVG Filters Tutorial - SVG: Scalable Vector Graphics
this element has different attributes that help us create the clipping region.
SVG In HTML Introduction - SVG: Scalable Vector Graphics
like in the following example: var img = document.createelementns("http://www.w3.org/2000/svg", "image"); img.setattributens("http://www.w3.org/1999/xlink", "xlink:href", "move.png"); details the viewbox attribute establishes a logical coordinate system which the svg picture's coordinates are relative to.
SVG and CSS - SVG: Scalable Vector Graphics
below you'll create a simple demonstration that runs in your svg-enabled browser.
SVG fonts - SVG: Scalable Vector Graphics
it also shows how glyphs are created: by simply adding any graphical svg content inside.
Tools for SVG - SVG: Scalable Vector Graphics
other renderers several projects exist that can create a raster image from an svg source.
Same-origin policy - Web security
if this popup also contains javascript, that script would inherit the same origin as the script that created it.
Transport Layer Security - Web security
to assist you in configuring your site, mozilla provides a helpful tls configuration generator that will generate configuration files for the following web servers: apache nginx lighttpd haproxy amazon web services cloudformation elastic load balancer using the configurator is a recommended way to create the configuration to meet your needs; then copy and paste it into the appropriate file on your server and restart the server to pick up the changes.
Weak signature algorithms - Web security
weaknesses in hash algorithms can lead to situations in which attackers can create or obtain fraudulent certificates.
XML introduction - XML: Extensible Markup Language
for example, to create a new &warning; entity, you can do this: <?xml version="1.0" encoding="utf-8"?> <!doctype body [ <!entity warning "warning: something bad happened...
<xsl:attribute-set> - XSLT: Extensible Stylesheet Language Transformations
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the <xsl:attribute-set> element creates a named set of attributes, which can then be applied as whole to the output document, in a manner similar to named styles in css.
<xsl:element> - XSLT: Extensible Stylesheet Language Transformations
WebXSLTElementelement
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the <xsl:element> element creates an element in the output document.
An Overview - XSLT: Extensible Stylesheet Language Transformations
before transformation can take place, the primary xml document(s) and the stylesheet document(s) must be run through a parser, which creates an abstract representation of the structure of the document in memory.
Advanced Example - XSLT: Extensible Stylesheet Language Transformations
figure 7: sorting based on div contentview example // xhtml fragment: <div id="example"> <div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div> <div>6</div> <div>7</div> <div>8</div> <div>9</div> <div>10</div> </div> // javascript var xslref; var xslloaded = false; var xsltprocessor = new xsltprocessor(); var mydom; var xmlref = document.implementation.createdocument("", "", null); function sort() { if (!xslloaded){ p = new xmlhttprequest(); p.open("get", "example2.xsl", false); p.send(null); xslref = p.responsexml; xsltprocessor.importstylesheet(xslref); xslloaded = true; } // create a new xml document in memory xmlref = document.implementation.createdocument("", "", null); // we want to move a part of the dom fr...
Introduction - XSLT: Extensible Stylesheet Language Transformations
as of mozilla 1.2, gecko enables javascript to create xslt processors.
XSLT: Extensible Stylesheet Language Transformations
WebXSLT
although the process is referred to as "transformation," the original document is not changed; rather, a new xml document is created based on the content of an existing document.
Compiling a New C/C++ Module to WebAssembly - WebAssembly
we've also specified --shell-file html_template/shell_minimal.html — this provides the path to the html template you want to use to create the html you will run your example through.
Exported WebAssembly functions - WebAssembly
thertable = new webassembly.table({ element: "anyfunc", initial: 2 }); webassembly.instantiatestreaming(fetch('table.wasm')) .then(obj => { var tbl = obj.instance.exports.tbl; console.log(tbl.get(0)()); // 13 console.log(tbl.get(1)()); // 42 othertable.set(0,tbl.get(0)); othertable.set(1,tbl.get(1)); console.log(othertable.get(0)()); console.log(othertable.get(1)()); }); here we create a table (othertable) from javascript using the webassembly.table constructor, then we load table.wasm into our page using the webassembly.instantiatestreaming() method.