Search completed in 1.02 seconds.
818 results for "loading":
Your results are loading. Please wait...
Uploading and Downloading Files - Archive of obsolete content
file and stream guide: [ nsiscriptableio | accessing files | getting file information | reading from files | writing to files | moving, copying and deleting files | uploading and downloading files | working with directories ] important note: the pages from the file and stream guide use the io object (nsiscriptableio), which was not available in any released version of the platform (pending some fixes). there are alternative xpcom apis you can use, your help in updating this pages to use the supported api is very much welcome! other documentation on files and i/o not using the unavailable nsiscriptableio apis: code snippets: file i/o, open and save dialogs, reading textual data, writing textual data, list of file-related error codes. the io object and stream objects can be used to upl...
... the exact method depends on the type of upload that you wish to perform. http file upload some web sites allow one to upload a file. this is done by using an html <input> element using the file type from within a form. when the user selects a file, it can be uploaded to a server. this operation can also be performed via a script using the xmlhttprequest object. this is a common technique for uploading files as it is compatible with existing servers and formdata interface makes that task fairly simple. a formdata object will automatically generate request data with mime type multipart/form-data that existing servers can process. to add a file field to the data you use a file object that an extension can construct from file path. the formdata object can then simply be passed to xmlhttprequest: ...
...meanwhile you can read this. ...
...meanwhile you can read this. ...
HTMLImageElement.loading - Web APIs
the possible values are: eager the default behavior, eager tells the browser to load the image as soon as the <img> element is processed. ...
...the possible values are: eager the default behavior, eager tells the browser to load the image as soon as the <img> element is processed. ...
...the possible values are: eager the default behavior, eager tells the browser to load the image as soon as the <img> element is processed. ...
...And 7 more matches
Progressive loading - Progressive web apps (PWAs)
previous overview: progressive web apps in previous articles we covered apis that help us make our js13kpwa example a progressive web app: service workers, web manifests, notifications and push. in this article we will go even further and improve the performance of the app by progressively loading its resources. first meaningful paint it's important to deliver something meaningful to the user as soon as possible — the longer they wait for the page to load, the bigger the chance they will leave before waiting for everything to finish. we should be able to show them at least the basic view of the page they want to see, with placeholders in the places more content will eventually be loaded. this could be achieved by progressive loading — also known as lazy loading. this is a...
... possible — the longer they wait for the page to load, the bigger the chance they will leave before waiting for everything to finish. we should be able to show them at least the basic view of the page they want to see, with placeholders in the places more content will eventually be loaded. this could be achieved by progressive loading — also known as lazy loading. this is all about deferring loading of as many resources as possible (html, css, javascript), and only loading those immediately that are really needed for the very first experience. bundling versus splitting many visitors won't go through every single page of a website, yet the usual approach is to bundle every feature we have into one big file. a bundle.js file can be many megabytes, and a single style.css bundle can contain ev...
... small ones, but if the user doesn't need everything at the very beginning, we could load only what's crucial and then manage other resources when needed. render-blocking resources bundling is a problem, because the browser has to load the html, css, and javascript before it can paint their rendered results onto the screen. during the few seconds between initial website access and completion of loading, the user sees a blank page, which is a bad experience. to fix that we can, for example, add defer to javascript files: <script src="app.js" defer></script> they will be downloaded and executed after the document itself has been parsed, so it won't block rendering the html structure. we can also split css files and add media types to them: <link rel="stylesheet" href="style.css"> <link rel="...
...And 7 more matches
Appendix D: Loading Scripts - Archive of obsolete content
the examples below which make use of the services global assume that you're previously imported the services.jsm module. ...
...ng javascript code. because there are such a diverse array of add-ons, and because the needs of developers have grown organically over time, the gecko runtime provides a number of means to dynamically load and execute javascript files. each of these means has its own advantages and disadvantages, as well as its own quirks which may trap the unwary. below is an overview of the more common means of loading scripts, along with some of their primary advantages, disadvantages, quirks, and use cases. the examples below which make use of the services global assume that you're previously imported the services.jsm module. as this module only exists on firefox 4 and other gecko 2-based platforms, the services in question will have to be manually loaded on other platforms. <script> tags xul script ta...
... advantages, disadvantages, quirks, and use cases. the examples below which make use of the services global assume that you're previously imported the services.jsm module. as this module only exists on firefox 4 and other gecko 2-based platforms, the services in question will have to be manually loaded on other platforms. <script> tags xul script tags are traditionally the primary means of loading scripts for extension developers. these tags are generally inserted into xul overlay files or other xul documents, after which they are automatically loaded into the context of the xul window in question and executed immediately and synchronously. advantages familiarity: these tags are very similar to the html script tags familiar to most web developers. simplicity: the simple, declarative n...
...And 6 more matches
Tips for authoring fast-loading HTML pages - Learn web development
ests on pages which would normally not be cacheable. more information: http conditional get for rss hackers http 304: not modified http etag on wikipedia caching in http optimally order the components of the page download page content first, along with any css or javascript that may be required for its initial display, so that the user gets the quickest apparent response during the page loading. this content is typically text, and can, therefore, benefit from text compression in transit, thus providing an even quicker response to the user. any dynamic features that require the page to complete loading before being used, should be initially disabled, and then only enabled after the page has loaded. this will cause the javascript to be loaded after the page contents, which will improve t...
...quicker response to the user. any dynamic features that require the page to complete loading before being used, should be initially disabled, and then only enabled after the page has loaded. this will cause the javascript to be loaded after the page contents, which will improve the overall appearance of the page load. reduce the number of inline scripts inline scripts can be expensive for page loading since the parser must assume that an inline script could modify the page structure while parsing is in progress. reducing the use of inline scripts in general, and reducing the use of document.write() to output content in particular, can improve overall page loading. use modern ajax methods to manipulate page content for modern browsers, rather than the older approaches based on document.write().
... photoshop, or using a specialized tool such as compress jpeg or tiny png,. specify sizes for images and tables if the browser can immediately determine the height and/or width of your images and tables, it will be able to display a web page without having to reflow the content. this not only speeds the display of the page but prevents annoying changes in a page's layout when the page completes loading. ...
...And 5 more matches
Downloading Files - Archive of obsolete content
the following methods of downloading files may not work as expected after firefox 26, and should no longer be used. please use downloads.jsm instead. 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. components.utils.import("resource://gre/modules/privatebrowsingutils.jsm"); const webbrowserpersist = components.constructor("@mozilla.org/embedding/browser/nswebbrowserpersist;1", "nsiwebbrowserpersist"); var persist = webbrowserpersist(); var targetfile = services.dirsvc.get("desk", ci.nsifile); targetfile.append("file.bin"); // obtain the p...
...if, and only if, the url is not // related to a window, null should be used instead. var privacy = privatebrowsingutils.privacycontextfromwindow(urlsourcewindow); persist.persistflags = persist.persist_flags_from_cache | persist.persist_flags_replace_existing_files; persist.saveuri(uritosave, null, null, null, "", targetfile, privacy); if you don't need detaile...
...ull should be used instead. var privacy = privatebrowsingutils.privacycontextfromwindow(urlsourcewindow); persist.persistflags = persist.persist_flags_from_cache | persist.persist_flags_replace_existing_files; persist.saveuri(uritosave, null, null, null, "", targetfile, privacy); if you don't need detailed progress information, you might be happier with nsidownloader. ...
...And 4 more matches
Lazy loading - Web Performance
overview as the web has evolved, we have come to see huge increases in the number and size of assets sent to users. between 2011 and 2019, the median resource weight increased from ~100kb to ~400kb for desktop and ~50kb to ~350kb for mobile. while image size has increased from ~250kb to ~900kb on desktop and ~100kb to ~850kb on mobile. ...
...ee huge increases in the number and size of assets sent to users. between 2011 and 2019, the median resource weight increased from ~100kb to ~400kb for desktop and ~50kb to ~350kb for mobile. while image size has increased from ~250kb to ~900kb on desktop and ~100kb to ~850kb on mobile. one of the methods we can use to tackle this problem is to shorten the critical rendering path length by lazy loading resources that are not critical for the first render to happen. a practical example would be when, you land on the home page of an e-commerce site which has a link to a cart page/section and all its resources (js, css, images...) are downloaded only when the user navigates to that cart page. strategies lazy loading can be applied to multiple resources and through multiple strategies. g...
...ef="print.css" rel="stylesheet" media="print"> it is possible to perform some css optimizations to achieve that. fonts by default, font requests are delayed until the render tree is constructed, which can result in delayed text rendering. ...
...And 4 more matches
Preloading content with rel="preload" - HTML: Hypertext Markup Language
this ensures they are available earlier and are less likely to block the page's render, improving performance. this article provides a basic guide to how <link rel="preload"> works. ...
...the later resources are discovered and the larger they are. for example: resources that are pointed to from inside css, like fonts or images. resources that javascript can request, like json, imported scripts, or web workers. larger images and video files. preload has other advantages too. using as to specify the type of content to be preloaded allows the browser to: prioritize resource loading more accurately. store in the cache for future requests, reusing the resource if appropriate. apply the correct content security policy to the resource. set the correct accept request headers for it. what types of content can be preloaded? many different content types can be preloaded. the possible as attribute values are: audio: audio file, as typically used in <audio>. document: an ht...
...nd the web features they expect to be consumed by in the preload spec — see link element extensions. also note that the full list of values the as attribute can take is governed by the fetch spec — see request destinations. including a mime type <link> elements can accept a type attribute, which contains the mime type of the resource the element points to. this is especially useful when preloading resources — the browser will use the type attribute value to work out if it supports that resource, and will only download it if so, ignoring it if not. you can see an example of this in our video example (see the full source code, and also the live version): <head> <meta charset="utf-8"> <title>video preload example</title> <link rel="preload" href="sintel-short.mp4" as="video" type="...
...And 3 more matches
Frame script loading and lifetime
this line of code loads a frame script into the currently selected tab. the script just writes "foo" to the command line: // chrome script var mm = gbrowser.selectedbrowser.messagemanager; mm.loadframescript('data:,dump("foo\\n")', true); loadframescript() takes two mandatory parameters: a url that points to the frame script you want to load a boolean flag, allowdelayedload note: if the message manager is a global frame message manager or a window message manager, loadframescript() may load the script multiple times, once in each applicable frame. chrome: urls extension developers usually use a chrome:// url to refer to the frame scripts. ...
...er load the frame script into that one tab. passing allowdelayedload is a way to ensure that the script is loaded correctly, in case the tab is not ready when making the call. if you use allowdelayedload, you can cancel it by using removedelayedframescript: var mm = window.messagemanager; mm.removedelayedframescript("chrome://my-e10s-extension/content/frame-script.js"); this means we will stop loading the script into new tabs. note that this function will not remove any scripts which have been loaded earlier. frame script lifetime frame scripts are loaded as soon as loadframescript() is called. if you've set allowdelayedload, the script is loaded into a new tab as soon as it is created. frame scripts are associated with a browser tab and not with a page. so once you load them, they will sta...
...aded until the tab is closed, even if you reload the document or navigate. 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. unloading frame scripts frame scripts are automatically unloaded when their hosting tab is closed. there is currently no way to unload them when loaded, other than closing the tab they were loaded into. to listen for an event, when your frame script is unloaded (due to tab close for instance), you must set the third argument of addmessagelistener to true. for example, from bootstrap.js: services.mm.addm...
...wise sending message from framescript will not work during and after the unload event on the contentmessagemanager triggers ); then in your frame script, listen for the unload event of the message manager (which is the global this), and sending a message. if you did not set the third argument to true in bootstrap.js on services.mm.addmessagelistener, sending this message during, and after, the unloading event will do nothing. var gcontentframemessagemanager = this; addeventlistener('unload', function(aevent) { if (aevent.target == gcontentframemessagemanager) { sendasyncmessage('my-addon-id', 'framescript-died'); // if you did not set third argument of `services.mm.addmessagelistener` to `true`, then this will fail to send a message } }, false); note about unload during uninst...
Downloading JSON and JavaScript in extensions - Archive of obsolete content
ause the decoded javascript has full chrome privileges and could perform some nasty actions. how could the javascript an extension downloads perform nasty actions? fairly easy if the webserver where the javascript is hosted were to be hijacked or compromised. it happens to the best of us. amo takes the threat very seriously. the good news is there are several ways to workaround the problem. ...
...hrome privileges and could perform some nasty actions. how could the javascript an extension downloads perform nasty actions? fairly easy if the webserver where the javascript is hosted were to be hijacked or compromised. it happens to the best of us. amo takes the threat very seriously. the good news is there are several ways to workaround the problem. downloading json if the extension is downloading json, then the developer should be using one of the json decoding methods discussed here and not using eval() at all. json is about state and does not allow functions to be decoded. the json decoding methods available to extension developers protect the extension from malicious json and javascript. downloading state from a remote webserver using json is becoming extremely popular. use the json d...
...should be using one of the json decoding methods discussed here and not using eval() at all. json is about state and does not allow functions to be decoded. the json decoding methods available to extension developers protect the extension from malicious json and javascript. downloading state from a remote webserver using json is becoming extremely popular. use the json decoders, not eval()! downloading javascript of course there are times when javascript code modules are downloaded and injected into the extension. 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. in this case, javascript sandboxing should be used to isolate the downloaded javascript from...
Loading Content Scripts - Archive of obsolete content
this version of the api avoids the need to maintain a separate file for the content script. ...
...erted into the dom. at this point the dom content hasn't been loaded yet, so the script won't be able to interact with it. "ready" loads the scripts after the dom for the page has been loaded: that is, at the point the domcontentloaded event fires. at this point, content scripts are able to interact with the dom content, but externally-referenced stylesheets and images may not have finished loading. "end" loads the scripts after all content (dom, js, css, images) for the page has been loaded, at the time the window.onload event fires. the default value is "end". the contentscriptoptions is a json that is exposed to content scripts as a read only value under self.options property. any kind of jsonable value (object, array, string, etc.) can be used here. ...
Page Loading - Archive of obsolete content
page loading on page load how to execute code each time a new page is loaded in browser/mail progress listeners progress listeners allow extensions to be notified of events associated with documents loading in the browser and with tab switching events. post data to window code to post data to an existing or new window/tab ...
downloading - Archive of obsolete content
general info specification offline interface event bubbles no cancelable no target applicationcache default action none properties property type description target eventtarget (dom element) the event target (the topmost target in the dom tree). read only. type string the type of event. read only. canbubble boolean does the event normally bubble? read only. cancelable boolean is it possible to cancel the event? read only. ...
Document Loading - From Load Start to Finding a Handler - Archive of obsolete content
we start with the request to load a particular link in a particular window, and proceed up to the point at which the data stream is dispatched to the proper handler. the final goal is to find the correct stream listener to pump the data into when necko calls ondataavailable (e.g., we may find the html parser as the stream listener to give the data to). dramatis personae this document focuses on the interaction of three classes with each other, but other mozilla components are also involved. main roles nsdocshell this class corresponds, basically, to a "window" object in javascript -- each frame, iframe, content area, tab, etc has its own docshell. ...
Safely loading URIs - Archive of obsolete content
some other schemes are used internally by mozilla modules to communicate with each other. finally, some uris (e.g. chrome: give the loaded page expanded privileges. if a web page gets access to a window with such expanded privileges, it may be able to abuse it to gain access to those privileges itself. to solve this problem, gecko provides methods that allow the caller to check whether it's safe to load a particular uri. these methods are exposed on the nsiscriptsecuritymanager interface and are called checkloaduri, checkloaduriwithprincipal, and checkloaduristr. ...
CSS Font Loading API - Web APIs
the css font loading api provides events and interfaces for dynamically loading font resources. interfaces fontface represents a single usable font face. fontfaceset an interface loading font faces and checking their download statuses. fontfacesource a mixin providing all of the fonts used in font-related operations, unless defined otherwise. it defines the fontfacesources.fonts property available to document and workerglobalscope. fontfacesetloadevent fired whenever a fontfaceset loads. specifications specification status comment css font loading module level 3 working draft initial definition. ...
PerformanceTiming.domLoading - Web APIs
this interface of this property is deprecated in the navigation timing level 2 specification. please use the performancenavigationtiming interface instead. the legacy performancetiming.domloading read-only property returns an unsigned long long representing the moment, in miliseconds since the unix epoch, when the parser started its work, that is when its document.readystate changes to 'loading' and the corresponding readystatechange event is thrown. syntax time = performancetiming.domloading; specifications specification status comment navigation timingthe definition of 'performancetiming.domloading' in that specification. recommendation initial definition. ...
:-moz-loading - CSS: Cascading Style Sheets
the :-moz-loading css pseudo-class is a mozilla extension that matches elements that can't be displayed because they have not started loading, such as images that haven't started to arrive yet. note that images that are in the process of loading are not matched by this pseudo-class. note: this selector is mainly intended to be used by theme developers. syntax :-moz-loading examples setting a background for images that are loading :-moz-loading { background-color: #aaa; background-image: url(loading-animation.gif) center no-repeat; } specifications not part of any standard. ...
Loading and running WebAssembly code - WebAssembly
request() instance, and use its open() method to open a request, setting the request method to get, and declaring the path to the file we want to fetch. the key part of this is to set the response type to 'arraybuffer' using the responsetype property. next, send the request using xmlhttprequest.send(). we then use the onload event handler to invoke a function when the response has finished downloading — in this function we get the array buffer from the response property, and then feed that into our webassembly.instantiate() method as we did with fetch. the final code looks like this: request = new xmlhttprequest(); request.open('get', 'simple.wasm'); request.responsetype = 'arraybuffer'; request.send(); request.onload = function() { var bytes = request.response; webassembly.instantia...
Index - Web APIs
Web › API › Index
s, cssom, method, reference, supports the css.supports() method returns a boolean value indicating if the browser supports a given css feature, or not. 391 css counter styles css, css counter styles, overview the css counter styles module allows to define custom counter styles, which can be used for css list-marker and generated-content counters. 392 css font loading api api, cssfontloading, experimental, fonts, needscontent, reference the css font loading api provides events and interfaces for dynamically loading font resources. 393 css object model (cssom) api, cssom, overview, reference the css object model is a set of apis allowing the manipulation of css from javascript. it is much like the dom, but for the css rather than ...
...cument interface returns the featurepolicy interface which provides a simple api for inspecting the feature policies applied to a specific document. 912 document.fgcolor api, deprecated, html dom, needsmarkupwork, needsspectable, property, reference fgcolor gets/sets the foreground color, or text color, of the current document. 913 document.fonts api, dom, font loading api, fontface, fontfaceset, fonts, font the fonts property of the document interface returns the fontfaceset interface of the document. 914 document.forms api, dom, document, forms, html dom, html forms, property, reference the forms read-only property of the document interface returns an htmlcollection listing all the <form> elements contained in the document. 9...
...cument interface returns a collection of all <area> elements and <a> elements in a document with a value for the href attribute. 936 document.location api, document, html dom, property, read-only, reference the document.location read-only property returns a location object, which contains information about the url of the document and provides methods for changing that url and loading another url. 937 document.mozsetimageelement() api, dom, dom reference, method, non-standard, reference the document.mozsetimageelement() method changes the element being used as the css background for a background with a given background element id. 938 document.mozsyntheticdocument api, dom, non-standard, property, reference the document.mozsyntheticdoc...
...And 62 more matches
Index - Archive of obsolete content
port object. 16 communicating using "postmessage" add-on sdk no summary! 17 cross-domain content scripts add-on sdk, add-ons, extensions no summary! 18 interacting with page scripts add-on sdk, add-ons, extensions by default, content scripts loaded by add-ons and scripts loaded by web pages are insulated from each other: 19 loading content scripts no summary! 20 reddit example advanced, codingscripting, javascript, mobile no summary! 21 port no summary! 22 self this article documents the self object that is available as a global in content scripts. self provides: 23 contributor's guide no summary! 24 classes and inhe...
...ined unit of code, which is usually stored in a file, and has a well defined interface. the use of modules greatly improves the maintainability of code, by splitting it up into independent components, and enforcing logical boundaries between them. unfortunately, javascript does not yet have native support for modules: it has to rely on the host application to provide it with functionality such as loading subscripts, and exporting/ importing names. we will show how to do each of these things using the built-in components object provided by xulrunner application such as firefox and thunderbird. 28 private properties people have come up with several ways to emulate private properties using existing language features. this article discusses two common techniques: one using prefi...
... 182 drag & drop code snippets 183 embedding svg code snippets no summary! 184 examples and demos from articl...
...And 24 more matches
nsIIOService
scheme(in autf8string urlstring); unsigned long getprotocolflags(in string ascheme); nsiprotocolhandler getprotocolhandler(in string ascheme); nsichannel newchannel(in autf8string aspec, in string aorigincharset, in nsiuri abaseuri); obsolete since gecko 48 nsichannel newchannel2(in autf8string aspec, in string aorigincharset, in nsiuri abaseuri, in nsidomnode aloadingnode, in nsiprincipal aloadingprincipal, in nsiprincipal atriggeringprincipal, in uint32_t asecurityflags, in uint32_t acontentpolicytype); nsichannel newchannelfromuri(in nsiuri auri); obsolete since gecko 48 nsichannel newchannelfromuri2(in nsiuri auri, in nsidomnode aloadingnode, in nsiprincipal aloadingprincipal, in nsiprincipal atriggeringprincipal, in unsigned long asecuri...
...auri, in nsidomnode aloadingnode, in nsiprincipal aloadingprincipal, in nsiprincipal atriggeringprincipal, in unsigned long asecurityflags, in unsigned long acontentpolicytype); nsichannel newchannelfromuriwithloadinfo(in nsiuri auri, in nsiloadinfo aloadinfo); nsichannel newchannelfromuriwithproxyflags2(in nsiuri auri, in nsiuri aproxyuri, in uint32_t aproxyflags,in nsidomnode aloadingnode, in nsiprincipal aloadingprincipal, in nsiprincipal atriggeringprincipal, in uint32_t asecurityflags, in uint32_t acontentpolicytype); nsiuri newfileuri(in nsifile afile); nsiuri newuri(in autf8string aspec, in string aorigincharset, in nsiuri abaseuri); attributes attribute type description offline boolean returns true if networking is...
...y be null. abaseuri the base uri for the spec. may be null. if aspec is an absolute url, this parameter is ignored. return value returns an nsichannel based on aspec and abaseuri. newchannel2() a shortcut method to avoid repeated calls of newuri() and newchannelfromuri(). ...
...And 24 more matches
Audio for Web games - Game development
teracted with the domain. on mobile the user has added the site to their home screen. many browsers will simply ignore any requests made by your game to automatically play audio; instead playback for audio needs to be started by a user-initiated event, such as a click or tap. this means you will have to structure your audio playback to take account of that. this is usually mitigated against by loading the audio in advance and priming it on a user-initiated event. for more passive audio auto play, for example background music that starts as soon as a game loads, one trick is to detect any user initiated event and start playback then. for other more active sounds that are to be used during the game we could consider priming them as soon as something like a start button is pressed. to prime aud...
...e its capabilities. in the case of autoplay on ios, this appears to be the case currently. if possible, you should try your code on several devices and platforms to see how it works. volume programmatic volume control may be disabled in mobile browsers. the reason often given is that the user should be in control of the volume at the os level and this shouldn't be overridden. buffering and preloading likely as an attempt to mitigate runaway mobile network data use, we also often find that buffering is disabled before playback has been initiated. buffering is the process of the browser downloading the media in advance, which we often need to do to ensure smooth playback. the htmlmediaelement interface comes with lots of properties to help determine whether a track is in a state to be playabl...
...playback. the htmlmediaelement interface comes with lots of properties to help determine whether a track is in a state to be playable. note: in many ways the concept of buffering is an outdated one. as long as byte-range requests are accepted (which is the default behavior), we should be able to jump to a specific point in the audio without having to download the preceding content. however, preloading is still useful — without it, there would always need to be some client-server communication required before playing can commence. concurrent audio playback a requirement of many games is the need to play more than one piece of audio at the same time; for example, there might be background music playing along with sound effects for various things happening in the game. although the situation...
...And 8 more matches
Event reference
that can be sent; some are standard events defined in official specifications, while others are events used internally by specific browsers; for example, mozilla-specific events are listed so that add-ons can use them to interact with the browser. most common categories resource events event name fired when error a resource failed to load. abort the loading of a resource has been aborted. load a resource and its dependent resources have finished loading. beforeunload the window, the document and its resources are about to be unloaded. unload the document or a dependent resource is being unloaded. network events event name fired when online the browser has gained access to th...
... durationchange the duration attribute has been updated. emptied the media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the load() method is called to reload it. ended playback has stopped because the end of the media was reached. loadeddata the first frame of the media has finished loading. loadedmetadata the metadata has been loaded. pause playback has been paused. play playback has begun. playing playback is ready to start after having been paused or delayed due to lack of data. ratechange the playback rate has changed. seeked a seek operation completed. seeking a seek operation began. st...
... has begun. playing playback is ready to start after having been paused or delayed due to lack of data. ratechange the playback rate has changed. seeked a seek operation completed. seeking a seek operation began. stalled the user agent is trying to fetch media data, but data is unexpectedly not forthcoming. suspend media data loading has been suspended. timeupdate the time indicated by the currenttime attribute has been updated. volumechange the volume has changed. waiting playback has stopped because of a temporary lack of data. progress events event name fired when abort progression has been terminated (not due to an error). error progr...
...And 8 more matches
Modules - Archive of obsolete content
ined unit of code, which is usually stored in a file, and has a well defined interface. the use of modules greatly improves the maintainability of code, by splitting it up into independent components, and enforcing logical boundaries between them. unfortunately, javascript does not yet have native support for modules: it has to rely on the host application to provide it with functionality such as loading subscripts, and exporting/ importing names. we will show how to do each of these things using the built-in components object provided by xulrunner application such as firefox and thunderbird. to improve encapsulation, each module should be defined in the scope of its own global object. this is made possible by the use of sandboxes. each sandbox lives in its own compartment. a compartment is a se...
...te memory space. each compartment has a set of privileges that determines what scripts running in that compartment can and cannot do. we will show how sandboxes and compartments can be used to improve security in our module system. the module system used by the sdk is based on the commonjs specification: it is implemented using a loader object, which handles all the bookkeeping related to module loading, such as resolving and caching urls. we show how to create your own custom loaders, using the loader constructor provided by the sdk. the sdk uses its own internal loader, known as cuddlefish. all modules within the sdk are loaded using cuddlefish by default. 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 ...
...sing the loader constructor provided by the sdk. the sdk uses its own internal loader, known as cuddlefish. all modules within the sdk are loaded using cuddlefish by default. 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. loading subscripts when a javascript project reaches a certain size, it becomes necessary to split it up into multiple files. unfortunately, javascript does not provide any means to load scripts from other locations: we have to rely on the host application to provide us with this functionality. applications such as firefox and thunderbird are based on xulrunner. xulrunner adds a built-in object, known a...
...And 6 more matches
Application cache implementation overview
loading a top level document from offline cache this happens in nshttpchannel::opencacheentry(). all top level document loading (navigation) channels are set chooseapplicationcache flag, which happens in nsdocshell::douriload(). channels having that flag set are searching for nsiapplicationcache object prior inspecting normal http cache. nsiapplicationcacheservice::chooseapplicationcache is given the url the channel is about to load. it synchronously returns an nsiapplicationcache object representing the most recent cache version from the most recent cache group containing the entry under the url or a matching namespace. ...
...acheservice::chooseapplicationcache is given the url the channel is about to load. it synchronously returns an nsiapplicationcache object representing the most recent cache version from the most recent cache group containing the entry under the url or a matching namespace. if no nsiapplicationcache object has been found, there is no offline cache to load from and the load continues a usual way by loading from normal http cache, further steps are not executed. the channel remembers the nsiapplicationcache object. nsiapplicationcache is then queried a client id (= the manifest url + a unique time stamp). then, nsicacheservice is asked to open nsicachesession with store_offline policy and the given client id. entry is queried using that session. nshttpchannel::onofflinecacheentryavailable is then in...
...rs the nsiapplicationcache object. nsiapplicationcache is then queried a client id (= the manifest url + a unique time stamp). then, nsicacheservice is asked to open nsicachesession with store_offline policy and the given client id. entry is queried using that session. nshttpchannel::onofflinecacheentryavailable is then invoked. when aentrystatus is a success code, entry has been found and we are loading it from the cache. loadedfromapplicationcache flag is now set true on the channel. when aentrystatus is a failure code, entry has not been found, but the url is falling under one of the network or fallback namespaces. when matching fallback namespace, the associated fallback entry for it is remembered. the load then continues from the network as a usual load, using http cache. when load of the re...
...And 6 more matches
Ajax navigation example - Web APIs
this is an example of an ajax website composed only of three pages (first_page.php, second_page.php and third_page.php). 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. first_page.php: <?php $page_title = "first page"; $as_json = false; if (isset($_get["view_as"]) && $_get["view_as"] == "json") { $as_json = true; ob_start(); } else { ?> <!doctype html> <html> <head> <?php include "include/header.php"; echo "<title>" . $page_title . "</title>"; ?> </head> <body> <?php include "include/before_content.php"; ?> <p>this p...
...rd example</a> | <a class="ajax-nav" href="unexisting.php">unexisting page</a> ] </p> include/header.php: <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <script type="text/javascript" src="js/ajax_nav.js"></script> <link rel="stylesheet" href="css/style.css" /> js/ajax_nav.js: "use strict"; const ajaxrequest = new (function () { function closereq () { oloadingbox.parentnode && document.body.removechild(oloadingbox); bisloading = false; } function abortreq () { if (!bisloading) { return; } oreq.abort(); closereq(); } function ajaxerror () { alert("unknown error."); } function ajaxload () { var vmsg, nstatus = this.status; switch (nstatus) { case 200: ...
... /* unknown status */ ajaxerror(); } } closereq(); } function filterurl (surl, sviewmode) { return surl.replace(rsearch, "") + ("?" + surl.replace(rhost, "&").replace(rview, sviewmode ? ...
...And 6 more matches
HTTP Index - HTTP
Web › HTTP › Index
e, http http has a concept of conditional requests, where the result, and even the success of a request, can be changed by comparing the affected resources with the value of a validator. such requests can be useful to validate the content of a cache, and sparing a useless control, to verify the integrity of a document, like when resuming a download, or when preventing to lose updates when uploading or modifying a document on the server. 45 http cookies advertising, browser, cookies, cookies article, guide, http, history, javascript, privacy, protocols, server, storage, web development, data, request, tracking an http cookie (web cookie, browser cookie) is a small piece of data that a server sends to the user's web browser. the browser may store it and send it back with ...
...ent's <base> element. if this value is absent, then any uri is allowed. if this directive is absent, the user agent will use the value in the <base> element. 78 csp: block-all-mixed-content csp, content-security-policy, directive, http, mixed content, reference, security, block-all-mixed-content the http content-security-policy (csp) block-all-mixed-content directive prevents loading any assets using http when the page is loaded using https. 79 csp: child-src csp, child, content-security-policy, directive, http, reference, security, child-src, source the http content-security-policy (csp) child-src directive defines the valid sources for web workers and nested browsing contexts loaded using elements such as <frame> and <iframe>. for workers, non-compliant...
...tent-security-policy (csp) frame-ancestors directive specifies valid parents that may embed a page using <frame>, <iframe>, <object>, <embed>, or <applet>. 85 csp: frame-src csp, content-security-policy, directive, frame, http, reference, security, frame-src, source the http content-security-policy (csp) frame-src directive specifies valid sources for nested browsing contexts loading using elements such as <frame> and <iframe>. 86 csp: img-src csp, content-security-policy, directive, http, image, reference, security, img-src, source the http content-security-policy img-src directive specifies valid sources of images and favicons. 87 csp: manifest-src csp, content-security-policy, directive, http, manifest, reference, security, manifest-src,...
...And 6 more matches
Web Performance
re pop-ups quick to load and display, and do they animate smoothly as they do so? web performance includes both objective measurements like time to load, frames per second, and time to become interactive, and subjective experiences of how long it felt like it took the content to load. the longer it takes for a site to respond, the more users will abandon the site. it is important to minimize the loading and response times and add additional features to conceal latency by making the experience as available and interactive as possible, as soon as possible, while asynchronously loading in the longer tail parts of the experience. there are tools, apis, and best practices that help us measure and improve web performance. we cover them in this section: key performance guides animation performa...
...ering path includes the document object model (dom), css object model (cssom), render tree and layout.css and javascript animation performancebrowsers are able to optimize rendering flows. in summary, we should always try to create our animations using css transitions/animations where possible. if your animations are really complex, you may have to rely on javascript-based animations instead.lazy loadinglazy loading is a strategy to identify resources as non-blocking (non-critical) and load these only when needed. it is a way of shorten the critical rendering path length, what would translate into improved page load times. navigation and resource timingsnavigation timings are metrics measuring a browser's document navigation events. resource timings are detailed network timing measurements re...
... is a strategy to identify resources as non-blocking (non-critical) and load these only when needed. it is a way of shorten the critical rendering path length, what would translate into improved page load times. navigation and resource timingsnavigation timings are metrics measuring a browser's document navigation events. resource timings are detailed network timing measurements regarding the loading of an application's resources.optimizing startup performanceregardless of platform, it's always a good idea to start up as quickly as possible. since that's a universal issue, we won't be focusing on it too much here. instead, we're going to look at a more important issue when building web apps: starting up as asynchronously as possible. that means not running all your startup code in a single ev...
...And 6 more matches
Index - Archive of obsolete content
Archive › Mozilla › XUL › Index
ng dom calls to perform basic manipulations on a document, and then demonstrates working with anonymous xbl content using mozilla-specific methods. ...
...perform basic manipulations on a document, and then demonstrates working with anonymous xbl content using mozilla-specific methods. ...
...ccessing files | getting file information | reading from files | writing to files | moving, copying and deleting files | uploading and downloading files | working with directories ] 426 getting file information file and stream guide: [ nsiscriptableio | accessing files | getting file information | reading from files | writing to files | moving, copying and deleting files | uploading and downloading files | working with directories ] 427 io file and stream guide: [ nsiscriptableio | accessing files | getting file information | reading from files | writing to files | moving, copying and deleting files | uploading and downloading files | working with directories ] 428 moving, copying and deleting files file and stream guide: [ nsiscri...
...And 5 more matches
2D maze game with device orientation - Game development
e below is adding a new state called boot to the game: game.state.add('boot', ball.boot); the first value is the name of the state and the second one is the object we want to assign to it. the start method is starting the given state and making it active. let's see what the states are actually. managing game states the states in phaser are separate parts of the game logic; in our case we’re loading them from independent javascript files for better maintainability. the basic states used in this game are: boot, preloader, mainmenu, howto and game. boot will take care of initializing a few settings, preloader will load all of the assets like graphics and audio, mainmenu is the menu with the start button, howto shows the "how to play" instructions and the game state lets you actually play the g...
...th the start button, howto shows the "how to play" instructions and the game state lets you actually play the game. let's quickly go though the content of those states. boot.js the boot state is the first one in the game. ...
... and the game state lets you actually play the game. let's quickly go though the content of those states. boot.js the boot state is the first one in the game. ...
...And 5 more matches
Perceived performance - Learn web development
king at user perceptions, and what objective tools can be used to measure that which is subjective. prerequisites: basic computer literacy, basic software installed, and basic knowledge of client-side web technologies. objective: to gain basic familiarity of user perception of web performance. performance is about user perception. ...
...such an approach is much better than just showing nothing, which will make it feel like it is taking a lot longer and possibly lead to your users thinking it is broken and giving up. ...
...rts changing; but this change can be a simple background color update or something even less noticable. it doesn’t indicate completeness and may report a time when nothing visible is painted. first contentful paint (fcp) reports the time when the browser first rendered anything of signifigance, be that text, foreground or background image, or a canvas or svg; capturing the very beginning of the loading experience. but, just because there's content, doesn't mean it's useful content or that the user has content to consume. the first meaningful paint, or fmp, is the when content appears on the screen that is actually meaningful; which is a better metric for user-perceived loading experience, but still not ideal. largest contentful paint (lcp) metric, definited in the largest contentful paint api, ...
...And 5 more matches
Advanced techniques: Creating and sequencing audio - Web APIs
if you're familiar with these terms and you're looking for an introduction to their application within with the web audio api, you've come to the right place. demo we're going to be looking at a very simple step sequencer: in practice this is easier to do with a library — the web audio api was built to be built upon. if you are about to embark on building something more complex, tone.js would be a good place to start. ...
...reate those voices. the techniques we are using are: name of voice technique associated web audio api feature "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. the sounds are based on a dial-up modem. if you are unaware of how one sounds you can listen to one here. creating an audio context as you should ...
...= math.random() * 2 - 1; } // create a buffer source for our created data let noise = audioctx.createbuffersource(); noise.buffer = buffer; let bandpass = audioctx.createbiquadfilter(); bandpass.type = 'bandpass'; bandpass.frequency.value = bandhz; // connect our graph noise.connect(bandpass).connect(audioctx.destination); noise.start(); } "dial up" — loading a sound sample it's straightforward enough to emulate phone dial (dtmf) sounds, by playing a couple of oscillators together using the methods we've already looked at, however, in this section, we'll load in a sample file instead so we can take a look at what's involved. loading the sample we want to make sure our file has loaded and been decoded into a buffer before we use it, so let's create ...
...And 5 more matches
Index of archived content - Archive of obsolete content
dd-on sdk builder guides content scripts communicating with other scripts communicating using "port" communicating using "postmessage" cross-domain content scripts interacting with page scripts loading content scripts reddit example port self contributor's guide classes and inheritance content processes getting started modules private properties fir...
... bootstrapped extensions code snippets alerts and notifications autocomplete bookmarks boxes canvas code snippets cookies customizing the download progress bar delayed execution dialogs and prompts downloading files drag & drop embedding svg examples and demos from articles file i/o finding window handles forms related code snippets html in xul for rich tooltips html to dom isdefaultnamespace js xpcom javascript debugger service javascript timers ...
... isdefaultnamespace js xpcom javascript debugger service javascript timers javascript daemons management label and description lookupnamespaceuri lookupprefix miscellaneous modules on page load page loading post data to window preferences progress listeners queryselector rosetta running applications svg animation svg general scrollbar sidebar stringview tabbox toolbar tree uri parsing view source for xul applic...
...And 4 more matches
What is JavaScript? - Learn web development
modify html and css to update a user interface, via the document object model api (as mentioned above). note that the code in your web documents is generally loaded and executed in the order it appears on the page. if the javascript loads and tries to run before the html and css it is affecting has been loaded, errors can occur. you will learn ways around this later in the article, in the script loading strategies section. browser security each browser tab has its own separate bucket for running code in (these buckets are called "execution environments" in technical terms) — this means that in most cases the code in each tab is run completely separately, and the code in one tab cannot directly affect the code in another tab — or on another website. this is a good security measure — if th...
...nger than the onclick attribute, but it will work for all buttons — no matter how many are on the page, nor how many are added or removed. the javascript does not need to be changed. note: try editing your version of apply-javascript.html and add a few more buttons into the file. when you reload, you should find that all of the buttons when clicked will create a paragraph. neat, huh? script loading strategies there are a number of issues involved with getting scripts to load at the right time. nothing is as simple as it seems! a common problem is that all the html on a page is loaded in the order in which it appears. if you are using javascript to manipulate elements on the page (or more accurately, the document object model), your code won't work if the javascript is loaded and parsed bef...
...omcontentloaded" event, which signifies that the html body is completely loaded and parsed. the javascript inside this block will not run until after that event is fired, therefore the error is avoided (you'll learn about events later in the course). in the external example, we use a more modern javascript feature to solve the problem, the defer attribute, which tells the browser to continue downloading the html content once the <script> tag element has been reached. <script src="script.js" defer></script> in this case both the script and the html will load simultaneously and the code will work. note: in the external case, we did not need to use the domcontentloaded event because the defer attribute solved the problem for us. we didn't use the defer solution for the internal javascript examp...
...And 4 more matches
Using the Browser API
Mozilla › Gecko › Chrome › API › Browser API › Using
nt's state, interited by the htmliframeelement interface. note: an iframe enhanced by the browser api is commonly referred to as a "browser iframe". we'll be using this term throughout the current article, and other parts of the documentation. 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. to run the demo, the best approach is to clone the github repo locally (or just download it directly if you don't do github), open webide, open the repo as a packaged app, then run it either on a simulator or a real device if you have one. in any case, you should at least download the repo and refer to the code as you read th...
...note that we haven't implemented anything sophisticated in this app, like autofilling the http://, etc.). when you press the keyboard's return button, the 'submit' event is fired, which we handle like this: urlform.addeventlistener('submit',function(e) { e.preventdefault(); browser.src = urlbar.value; urlbar.blur(); }); we first call preventdefault() to stop the form just submitting and reloading the page — which is really not what we want. we then set the browser iframe's src attribute to equal the value of the url bar, which causes the new url to be loaded in the iframe. finally, we call blur() on the url bar to stop focusing it, so the keyboard moves off the screen, allowing us to get our full screen view back. there's another event listener added later on in the code that listens f...
.... zoomin.addeventlistener('touchend',function() { zoomfactor += 0.1; browser.zoom(zoomfactor); }); zoomout.addeventlistener('touchend',function() { zoomfactor -= 0.1; browser.zoom(zoomfactor); }); controlling the stop/reload button next, let's talk about the stop/reload button. as in a traditional browser, this is a single button that acts as a reload button when the page has finished loading, and a stop button while the page is loading (each with a different icon displayed). this is implemented in our sample app with the following functions: browser.addeventlistener('mozbrowserloadstart',function() { stopreload.textcontent = 'x'; }); browser.addeventlistener('mozbrowserloadend',function(e) { canmovebwd(); canmovefwd(); stopreload.textcontent = 'r'; console.log(e.detail.ba...
...And 4 more matches
nsIDocShell
when reading a document, a converter is used to translate the text from its original format into unicode. this attribute lets you: see what converter was used when retrieving the document's data. override that character set for documents for which the specified fallback or auto-detected character set is incorrect. reading this value reports the encoding that was used when loading the data into the document. setting this attribute overrides the encoding; however, to update the dom or display of the content, you need have the data reparsed. overriding the character set also sets the fallback encoding for the container frame. note: prior to gecko 12.0, this attribute was part of a separate nsidoccharset interface. chromeeventhandler nsidome...
... the apptype attribute used by thunderbird and seamonkey to indicate that email messages are displayed in this window. app_type_editor 2 this is the value of the apptype attribute used by thunderbird and seamonkey to indicate that email messages or web pages are composed in this window. ...
...ndow. app_type_editor 2 this is the value of the apptype attribute used by thunderbird and seamonkey to indicate that email messages or web pages are composed in this window. busy_flags_none 0 returned by the busyflags attribute when the nsidocshell is not loading a document. busy_flags_busy 1 returned by the busyflags attribute when the nsidocshell is loading a document from the network. busy_flags_before_page_load 2 returned by the busyflags attribute when the nsidocshell has started loading a document from the network, but no data has been received yet. busy_flags_page_loading 4 returned by the busyflags attribute when the nsidocshell is receiving data from the network. load_cmd_normal 0x1 returned by the...
...And 4 more matches
tabs - Archive of obsolete content
open, manipulate, and access tabs, and receive tab events. usage open a tab you can open a new tab, specifying various properties including location: var tabs = require("sdk/tabs"); tabs.open("http://www.example.com"); track tabs you can register event listeners to be notified when tabs open, close, finish loading dom content, or are made active or inactive: var tabs = require("sdk/tabs"); // listen for tab openings. tabs.on('open', function onopen(tab) { myopentabs.push(tab); }); // listen for tab content loads. tabs.on('ready', function(tab) { console.log('tab is loaded', tab.title, tab.url); }); access tabs the module itself can be used as a list of all opened tabs across all windows. in particular, you can enumerate it: var tabs = require('sdk/tabs'); for (let tab of tabs) ...
...tabs.open({ url: "http://www.mysite.com", innewwindow: true }); // open a new tab on active window in the background. tabs.open({ url: "http://www.mysite.com", inbackground: true }); // open a new tab as an app tab and do something once it's open. tabs.open({ url: "http://www.mysite.com", ispinned: true, onopen: function onopen(tab) { // do stuff like listen for content // loading. } }); parameters options : object required options: name type url string string url to be opened in the new tab. this is a required property. optional options: name type isprivate boolean boolean which will determine whether the new tab should be private or not. if your add-on does not support pri...
...ange its relative position. ispinned whether or not this tab is pinned as an app tab. this property is read-only. window the window object for this tab. readystate new in firefox 33. a string telling you the load state of the document hosted by this tab. this corresponds directly to document.readystate. it has one of four possible values: "uninitialized": the tab's document is not yet loading "loading": the tab's document is still in the process of loading "interactive": the tab's document has loaded and is parsed, but resources such as images and stylesheets may still be loading "complete": the tab's document and all resources are fully loaded once a tab's readystate has entered "interactive", you can retrieve properties such as the document's url. events close this event is ...
...And 3 more matches
How to convert an overlay extension to restartless - Archive of obsolete content
probably a bad idea. step 2b: audit any remaining resource:// uri usage internal to your extension if you don't need resource:// uris for anything else, then you may be able to skip the next step. if not, see if you still can't do things any other way. as with jsms, a chrome:// uri may be more appropriate. if you want to also make your add-on extractionless then you may need "step 3" if you're loading files with nsifileinputstream or something similar, or a jar: uri might work. if not, a file:// uri might be fine for you. restartless add-ons can easily get a uri for their install location on startup, so you should look into what you can do with that. step 3: no more nsifile access for files internal to your bundle for an extractionless extension, access to files internal to your bundle will ...
...lhttprequest now, how do we replace that? the answer to that question is to load your file from a chrome:// uri using xmlhttprequest. you may now have another question: wait, what does this have to do with xml or http? the answer to that question is, of course, nothing. xmlhttprequest is an api created by microsoft, adopted by mozilla and other vendors, and hacked into a swiss army knife of file loading. you can use it in a web page to fetch a file from your server and you can use it in your add-on to fetch a local file from your installation. the name is a vestigial structure that just makes things confusing. it is nonetheless the "correct" and best way to do things. it's available in the global for a window, but in jsm you'll need to fetch it from an interface: const xmlhttprequest = componen...
...to your chrome mapping, and then do the following line once during your startup: services.scriptloader.loadsubscript("chrome://myaddon/content/defaultprefs.js", {pref:setdefaultpref} ); that's it. once you've got the machinery to load and save preferences without having to jump through the various pref type hoops the actual preferences api sends you through, loading the actual preferences file is one line. i'd generally still recommend using the type specific functions for each pref individually, but to load the defaults just use the generic functions above and it's quite simple. the other generic functions are provided above in case you need them. unfortunately, the built in apis for dealing with preferences are missing this basic stuff, and its plain text ...
...And 3 more matches
What is web performance? - Learn web development
previous overview: performance next web performance is all about making web sites fast, including making slow processes seem fast. does the site load quickly, allow the user to start interacting with it quickly, and offer reassuring feedback if something is taking time to load (e.g. a loading spinner)? are scrolling and animations smooth? this article provides a brief introduction to objective, measureable web performance*, looking at what technologies, techniques, and tools are involved in web optimization. prerequisites: basic computer literacy, basic software installed, and basic knowledge of client-side web technologies. objective: to gain basic familiarity of what is involved with web performance. * versus subjective, perceived performance, covered i...
...r areas: reducing overall load time: how long does it take the files required to render the web site to download on to the user's computer? this tends to be affected by latency, how big your files are, how many files there are, and other factors besides. a general strategy is to make your files as small as possible, reduce the number of http requests made as much as possible, and employ clever loading techniques (such as preload) to make files available sooner. making the site usable as soon as possible: this basically means loading your web site assets in a sensible order so that the user can start to actually use it really quickly. any other assets can continue to load in the background while the user gets on with primary tasks, and sometimes we only load assets when they are actually neede...
...eload) to make files available sooner. making the site usable as soon as possible: this basically means loading your web site assets in a sensible order so that the user can start to actually use it really quickly. any other assets can continue to load in the background while the user gets on with primary tasks, and sometimes we only load assets when they are actually needed (this is called lazy loading). the measurement of how long it takes the site to get to a usable start after it has started loading is called time to interactive. smoothness and interactivity: does the application feel reliable and pleasurable to use? is the scrolling smooth? are buttons clickable? are pop-ups quick to open up, and do they animate smoothly as they do so? there are a lot of best practices to consider in makin...
...And 3 more matches
Handling common JavaScript problems - Learn web development
se the install option in the left-hand menu. in the search packages text field, type "jslint" and press enter/return to search for linting-related packages. you should see a package called lint at the top of the list. install this first (using the install button), as other linters rely on it to work. after that, install the linter-jshint plugin. after the packages have finished installing, try loading up a javascript file: you'll see any issues highlighted with green (for warnings) and red (for errors) circles next to the line numbers, and a separate panel at the bottom provides line numbers, error messages, and sometimes suggested values or other fixes. other popular editors have similar linting packages available. for example, see the "plugins for text editors and ides" section of the jsh...
...onal breakpoints and watch expressions. for a lot more information, see the debugger page. performance issues as your apps get more complex and you start to use more javascript, you may start to run into performance problems, especially when viewing apps on slower devices. performance is a big topic, and we don't have time to cover it in detail here. some quick tips are as follows: to avoid loading more javascript than you need, bundle your scripts into a single file using a solution like browserify. in general, reducing the number of http requests is very good for performance. make your files even smaller by minifying them before you load them onto your production server. minifying squashes all the code together onto a huge single line, making it take up far less file size. it is ugly, bu...
...k. talk to other developers to find out what they recommend, see how much activity and how many contributors the library has on github (or wherever else it is stored), etc. note: javascripting.com gives you a good idea of just how many javascript libraries there are available, and can be useful for finding libraries for specific purposes. library usage at a basic level tends to consist of downloading the library's files (javascript, possibly some css or other dependencies too) and attaching them to your page (e.g. via a <script> element), although there are normally many other usage options for such libraries, like installing them as bower components, or including them as dependencies via the webpack module bundler. you will have to read the libraries' individual install pages for more inform...
...And 3 more matches
Using files from web applications - Web APIs
esn't need to be done here. each image has the css class obj added to it, making it easy to find in the dom tree. we also add a file attribute to each image specifying the file for the image; this will let us fetch the images for actual upload later. we use node.appendchild() to add the new thumbnail to the preview area of our document. next, we establish the filereader to handle asynchronously loading the image and attaching it to the img element. after creating the new filereader object, we set up its onload function and then call readasdataurl() to start the read operation in the background. when the entire contents of the image file are loaded, they are converted into a data: url which is passed to the onload callback. our implementation of this routine sets the img element's src attribute ...
...he blob url. set the image's height to 60 pixels. set up the image's load event handler to release the object url since it's no longer needed once the image has been loaded. this is done by calling the url.revokeobjecturl() method and passing in the object url string as specified by img.src. append the new list item to the list. here is a live demo of the code above: example: uploading a user-selected file another thing you might want to do is let the user upload the selected file or files (such as the images selected using the previous example) to a server. this can be done asynchronously very easily. creating the upload tasks continuing with the code that built the thumbnails in the previous example, recall that every thumbnail image is in the css class obj with the corres...
...h as the images selected using the previous example) to a server. this can be done asynchronously very easily. creating the upload tasks continuing with the code that built the thumbnails in the previous example, recall that every thumbnail image is in the css class obj with the corresponding file attached in a file attribute. this allows us to select all of the images the user has chosen for uploading using document.queryselectorall(), like this: function sendfiles() { const imgs = document.queryselectorall(".obj"); for (let i = 0; i < imgs.length; i++) { new fileupload(imgs[i], imgs[i].file); } } line 2 fetches a nodelist, called imgs, of all the elements in the document with the css class obj. in our case, these will be all of the image thumbnails. once we have that list, it's ...
...And 3 more matches
Navigation and resource timings - Web Performance
navigation timings are metrics measuring a browser's document navigation events. resource timings are detailed network timing measurements regarding the loading of an application's resources. both provide the same read-only properties, but navigation timing measures the main document's timings whereas the resource timing provides the times for all the assets or resources called in by that main document and the resources' requested resources. ...
...operties, but navigation timing measures the main document's timings whereas the resource timing provides the times for all the assets or resources called in by that main document and the resources' requested resources. the general performance timings below have been deprecated in favor of the performance entry api, which provides for marking and measuring times along the navigation and resource loading process. while deprecated, they are supported in all browsers. performance timings the performancetiming api, a javascript api for measuring the loading performance of the requested page, is deprecated but supported in all browsers. it has been replaced with the performancenavigationtiming api. the performance timing api provided read only times, in milliseconds(ms), describing at what time ea...
...cated, they are supported in all browsers. performance timings the performancetiming api, a javascript api for measuring the loading performance of the requested page, is deprecated but supported in all browsers. it has been replaced with the performancenavigationtiming api. the performance timing api provided read only times, in milliseconds(ms), describing at what time each point in the page loading process was reached. ...
...And 3 more matches
Tabbed browser - Archive of obsolete content
mostrecentwindow("navigator:browser"); mainwindow.gbrowser.addtab(...); opening a url in a new tab // add tab gbrowser.addtab("http://www.google.com/"); // add tab, then make active gbrowser.selectedtab = gbrowser.addtab("http://www.google.com/"); manipulating content of a new tab if you want to work on the content of the newly opened tab, you'll need to wait until the content has finished loading. ...
....gbrowser.addtab(...); opening a url in a new tab // add tab gbrowser.addtab("http://www.google.com/"); // add tab, then make active gbrowser.selectedtab = gbrowser.addtab("http://www.google.com/"); manipulating content of a new tab if you want to work on the content of the newly opened tab, you'll need to wait until the content has finished loading. ...
...but if its an ajax call you may end up here } } } }; here's a cleaner example of the same thing: cu.import('resource://gre/modules/services.jsm'); var httprequestobserver = { observe: function (subject, topic, data) { var httpchannel, requesturl; if (topic == "http-on-modify-request") { httpchannel = subject.queryinterfac...
...And 2 more matches
Multimedia: Images - Learn web development
eed to be stored in memory. optimizing image delivery despite being the largest consumer of bandwidth, images load asynchronously so the visitor can see the page as they download and therefore, their impact on perceived performance is far lower than many expect. however, images are mostly used for content, so it's important that a visitor can see them as soon as possible for a good experience. loading strategy one of the biggest improvements to most websites is lazy-loading images beneath-the-fold, rather than downloading them all on initial page load regardless of whether a visitor scrolls to see them or not. many javascript libraries can implement this for you, such as lazysizes, and browser vendors are working on a native lazyload attribute that is currently in the experimental phase. bey...
...ategy one of the biggest improvements to most websites is lazy-loading images beneath-the-fold, rather than downloading them all on initial page load regardless of whether a visitor scrolls to see them or not. many javascript libraries can implement this for you, such as lazysizes, and browser vendors are working on a native lazyload attribute that is currently in the experimental phase. beyond loading a subset of images, next you should look into the format of the images themselves: are you loading the most optimal file formats? have you compressed the images well? are you loading the correct sizes? the most optimal format the optimal file format typically depends on the character of the image. the less colors an image has and the less photographic it is, the better it is to use the s...
...h. with photographic motifs that do not feature transparency there is a lot wider range of formats to chose from. if you want to play it safe, then you would go for well compressed progressive jpegs. progressive jpegs, in contrast to normal jpegs, render progressively (hence the name), meaning the user sees a low-resolution version that gains clarity as the image downloads, rather than the image loading at full resolution top-to-bottom or even only rendering once completely downloaded. a good compressor for these would be mozjpeg, e.g. available to use in the online image optimization tool squoosh. a quality setting of 75% should yield decent results. other formats improve on jpeg's capabilities in regards to compression, but are not available on every browser: webp — created by google an...
...And 2 more matches
Gecko info for Windows accessibility vendors
ozillacontentwindowclass or a mozillauiwindowclass. if it is a content window, you may use accessibleobjectfromwindow() to get the root iaccessible for the content, and begin traversing the tree from there. gecko also helps determine when to load a new window by firing two event_state_change's on the root role_document accessible -- the first state change indicates the document pane is now busy loading. the second state change indicates the document pane has finished. when handling the event, use get_accstate() to check the state_busy flag. when the document has finished loading the busy flag will be cleared. msaa support: iaccessible methods to use msaa with gecko, you'll need the tools and docs that come with the active accessibility 2.0 sdk tools. the method accessibleobjectfromwindow() ...
...on accnavigate get_acckeyboardshortcut msaa support: iaccessible events and unique id's what msaa events do we support? event_focus is fired for focus changes on any kind of focusable object event_statechange is used in check boxes, radio buttons, text fields, combo boxes and list boxes. it's also used in the root pane object to show when the state_busy flag changes from loading new content. event_scrollingend is used to indicate when a document has scrolled, even if only 1 line. gecko fires this event when the scrolling is finished, rather than fire excessive events. event_scrollingstart is fired when the user has jumped to a named anchor within the page. the event is fired on the first accessible object in the part of the document that has been jumped to. e...
...ocument changes, retrieving the iaccessible more than once for the same object will return the same iaccessible*. the uniqueid will remain the same as well. if the document does change, event_reorder, event_hide and event_show are used to indicate where the changes will occur. because of the persistence, relations and events can be mapped within an assistive technology's internal model. page loading is tracked via state_change events when a new document is about to be loaded, an event_state_change occurs on the root role_document object for a window. the state_busy flag is now set for the root pane object. 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. next, another event_state_ch...
...And 2 more matches
A brief guide to Mozilla preferences
what is a preference? a preference is any value or defined behavior that can be set (presumably, one setting is preferable to another). preference changes via user interface usually take effect immediately. the values are saved to the user profile (in prefs.js), for both firefox and thunderbird. ...
...he values are saved to the user profile (in prefs.js), for both firefox and thunderbird. a preference is read from a file, and can call up to four methods: pref(), user_pref(), sticky_pref() and lockpref(). all preferences files may call pref(), user_pref() and sticky_pref(), while the config file in addition may call lockpref(). preferences files to protect privacy by preventing inadvertent loading of a preferences file in the browser, the first line of the file is made un-parseable and skipped on loading. the only exception to this is user.js . on application launch, several preferences files are loaded. they are: default preference files firefox ships default preferences in several files, all in the application directory: greprefs.js - preferences shared by all applications us...
...) function. details on the config file is beyond the scope of this document. user pref. files in the profile directory are two user pref files: prefs.js and user.js. 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. preferences loading and resolution on application launch, the application loads preferences in the following order: load all default pref files. optionally load the config file. load user pref files, first prefs.js, then user.js . preference conflicts are resolved in favor of the last entry; for example, user.js takes precedence over prefs.js . if the application encounters any error during ...
...And 2 more matches
URLs - Plugins
uniform resource locator (url) protocols provide a means for locating and accessing resources that are available on the internet and on intranets. plug-ins can request and receive the data associated with urls of any type that the browser can handle, including http, ftp, news, mailto, and gopher. the table below summarizes urls supported by gecko. in addition, gecko may support urls not listed on this table. ...
...uent npp_urlnotify call (which returns this value) and/or to pass a pointer to some request-related payload. if a request is not completed successfully (for example, because the url is invalid or an http server is down), the browser should call npp_urlnotify as soon as possible. if a request completes successfully, and the target is non-null, the browser calls npp_urlnotify after it has finished loading the url. if the target is null, it calls npp_urlnotify after calling npp_destroystream to close the stream. both the npn_geturlnotify and npn_posturlnotify functions call the npp_urlnotify method to notify the plug-in of the result of a request. both functions pass the notifydata value to npp_urlnotify, which tells the plug-in that the url request was completed and the reason for completion. vo...
...f its parents/ancestors, the instance is destroyed and the plug-in may be unloaded. here's an example of getting a url: a plug-in instance draws a button that acts like a link to another web page. when the user clicks the button, the plug-in calls npn_geturl to go to the page. err = npn_geturl( instance, "http://www.example.com/", "_blank"); posting urls posting data to an http server uploading files to an ftp server sending mail the plug-in calls npn_posturl to post data from a file or buffer to a url. this function is the counterpart of npn_geturl. npn_posturl writes data from a file or buffer to the url and either displays the server response in the target window or delivers it to the plug-in. npn_geturl reads data from the url and either displays it in the target window or de...
...And 2 more matches
FontFaceSet - Web APIs
the fontfaceset interface of the css font loading api manages the loading of font-faces and querying of their download status. properties fontfaceset.status read only indicates the font-face's loading status. it will be one of 'loading' or 'loaded'. fontfaceset.ready read only promise which resolves once font loading and layout operations have completed. events fontfaceset.onloading an eventlistener called whenever an event of type loading is fired, indicating a font-face set has started loading. fontfaceset.onloadingdone an eventlistener called whenever an event of type loadingdone is fired, indicating that a font face set has finished loading. ...
... methods fontfaceset.add() adds a font to the font set. fontfaceset.check() a boolean that indicates whether a font is loaded, but doesn't initiate a load when it isn't. ...
... methods fontfaceset.add() adds a font to the font set. fontfaceset.check() a boolean that indicates whether a font is loaded, but doesn't initiate a load when it isn't. fontfaceset.clear() removes all manually-added fonts from the font set. ...
...And 2 more matches
Using the Resource Timing API - Web APIs
the resource timing api provides a way to retrieve and analyze detailed network timing data regarding the loading of an application's resource(s). an application can use the timing metrics to determine, for example, the length of time it takes to fetch a specific resource such as an xmlhttprequest, <svg>, image, script, etc.). 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. the interface also includes other properties that provide data about the size of the fetched resource as well as the type of resource that initiated the fetch. this document shows the use of resource timing interfaces. for more details about th...
...d resource as well as the type of resource that initiated the fetch. this document shows the use of resource timing interfaces. for more details about the interfaces, including examples, see each interface's reference page and the references in the see also section. a live version of the examples is available on github, as is the source code. pull requests and bug reports are welcome. resource loading phases an application can get timestamps for the various phases of resource loading such as redirection, dns lookup, and tcp connection setup. those phases and their property names are illustrated in figure 1. figure 1. resource timing properties an application developer can use the property values to calculate the length of time a phase takes and that information can help diagnose performanc...
... get timestamps for the various phases of resource loading such as redirection, dns lookup, and tcp connection setup. those phases and their property names are illustrated in figure 1. figure 1. resource timing properties an application developer can use the property values to calculate the length of time a phase takes and that information can help diagnose performance issues. timing resource loading phases the following example illustrates using the resource timing properties to calculate the amount of time the following phases take: redirection (redirectstart and redirectend ), dns lookup (domainlookupstart and domainlookupend), tcp handshake (connectstart and connectend), and response (responsestart and responseend). this example also calculates the time from the start of the fetch and re...
...And 2 more matches
Using textures in WebGL - Web APIs
« previousnext » now that our sample program has a rotating 3d cube, let's map a texture onto it instead of having its faces be solid colors. this example uses the glmatrix library to perform its matrix and vertex math. you'll need to include it if you create your own project based on this code. our sample loads a copy from a cdn in our html's <head>. loading textures the first thing to do is add code to load the textures. in our case, we'll be using a single texture, mapped onto all six sides of our rotating cube, but the same technique can be used for any number of textures. note: it's important to note that the loading of textures follows cross-domain rules; that is, you can only load textures from sites for which your content has cors approval. see cross-domain textures below...
...same technique can be used for any number of textures. note: it's important to note that the loading of textures follows cross-domain rules; that is, you can only load textures from sites for which your content has cors approval. see cross-domain textures below for details. the code that loads the texture looks like this: // // initialize a texture and load an image. // when the image finished loading copy it into the texture. // function loadtexture(gl, url) { const texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); // because images have to be download over the internet // they might take a moment until they are ready. ...
...hen the image finished loading copy it into the texture. // function loadtexture(gl, url) { const texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); // because images have to be download over the internet // they might take a moment until they are ready. // until then put a single pixel in the texture so we can // use it immediately. when the image has finished downloading // we'll update the texture with the contents of the image. const level = 0; const internalformat = gl.rgba; const width = 1; const height = 1; const border = 0; const srcformat = gl.rgba; const srctype = gl.unsigned_byte; const pixel = new uint8array([0, 0, 255, 255]); // opaque blue gl.teximage2d(gl.texture_2d, level, internalformat, width, height, border, s...
...And 2 more matches
Cross-browser audio basics - Developer guides
window.onload = function(){ var myaudio = document.getelementbyid('my-audio'); var play = document.getelementbyid('play'); var pause = document.getelementbyid('pause'); // associate functions with the 'onclick' events play.onclick = playaudio; pause.onclick = pauseaudio; function playaudio() { myaudio.play(); } function pauseaudio() { myaudio.pause(); } } media loading events above we have shown how you can create a very simple audio player, but what if we want to show progress, buffering and only activate the buttons when the media is ready to play? fortunately, there are a number of events we can use to let our player know exactly what is happening. first, let's take a look at the media loading process in order: loadstart the loadstart event tells us simp...
...d is in position but not quite ready to play. myaudio.addeventlistener("loadeddata", function() { //you could display the playhead now }); progress the progress event indicates that the download of media is still in progress. it is good practice to display some kind of 'loader' at this point. myaudio.addeventlistener("progress", function() { // you could let the user know the media is downloading }); canplay canplay is a useful event to detect should you want to determine whether the media is ready to play. you could, for example, disable custom controls until this event occurs. myaudio.addeventlistener("canplay", function() { //audio is ready to play }); canplaythrough canplaythrough is similar to canplay but it lets you know that the media is ready to be played all the way throug...
...lay }); canplaythrough canplaythrough is similar to canplay but it lets you know that the media is ready to be played all the way through (that is to say that the file has completely downloaded, or it is estimated that it will download in time so that buffering stops do not occur). myaudio.addeventlistener("canplaythrough", function() { //audio is ready to play all the way through }); media loading event order to recap, the order of the media loading events are: loadstart > durationchange > loadedmetadata > loadeddata > progress > canplay > canplaythrough loading interruption events we also have a few events available that will fire when there is some kind of interruption to the media loading process. suspend media data is no longer being fetched even though the file has not been en...
...And 2 more matches
<link>: The External Resource Link element - HTML: Hypertext Markup Language
Web › HTML › Element › link
edia="print"> <link href="mobile.css" rel="stylesheet" media="screen and (max-width: 600px)"> some interesting new performance and security features have been added to the <link> element too. take this example: <link rel="preload" href="myfont.woff2" as="font" type="font/woff2" crossorigin="anonymous"> a rel value of preload indicates that the browser should preload this resource (see preloading content with rel="preload" for more details), with the as attribute indicating the specific class of content being fetched. the crossorigin attribute indicates whether the resource should be fetched with a cors request. other usage notes: a <link> element can occur either in the <head> or <body> element, depending on whether it has a link type that is body-ok. for example, the stylesheet link...
...lesheet"> is permitted in the body. however, this isn't a good practice to follow; it makes more sense to separate your <link> elements from your body content, putting them in the <head>. when using <link> to establish a favicon for a site, and your site uses a content security policy (csp) to enhance its security, the policy applies to the favicon. if you encounter problems with the favicon not loading, verify that the content-security-policy header's img-src directive is not preventing access to it. the html and xhtml specifications define event handlers for the <link> element, but it is unclear how they would be used. under xhtml 1.0, empty elements such as <link> require a trailing slash: <link />. webtv supports the use of the value next for rel to preload the next page in a document ser...
...for example: <link href="print.css" rel="stylesheet" media="print"> <link href="mobile.css" rel="stylesheet" media="all"> <link href="desktop.css" rel="stylesheet" media="screen and (min-width: 600px)"> <link href="highres.css" rel="...
...And 2 more matches
<video>: The Video Embed element - HTML: Hypertext Markup Language
Web › HTML › Element › video
owser's default video controls, etc. the content inside the opening and closing <video></video> tags is shown as a fallback in browsers that don't support the element. attributes like all other html elements, this element supports the global attributes. autoplay a boolean attribute; if specified, the video automatically begins to play back as soon as it can do so without stopping to finish loading the data. note: sites that automatically play audio (or videos with an audio track) can be an unpleasant experience for users, so should be avoided when possible. if you must offer autoplay functionality, you should make it opt-in (requiring a user to specifically enable it). however, this can be useful when creating media elements whose source will be set at a later time, under user control. se...
...lenced. its default value is false, meaning that the audio will be played when the video is played. playsinline a boolean attribute indicating that the video is to be played "inline", that is within the element's playback area. note that the absence of this attribute does not imply that the video will always be played in fullscreen. poster a url for an image to be shown while the video is downloading. if this attribute isn't specified, nothing is displayed until the first frame is available, then the first frame is shown as the poster frame. preload this enumerated attribute is intended to provide a hint to the browser about what the author thinks will lead to the best user experience with regards to what content is loaded before the video is played. it may have one of the following values:...
...gth) is fetched. auto: indicates that the whole video file can be downloaded, even if the user is not expected to use it. empty string: synonym of the auto value. the default value is different for each browser. the spec advises it to be set to metadata. note: the autoplay attribute has precedence over preload. if autoplay is specified, the browser would obviously need to start downloading the video for playback. the specification does not force the browser to follow the value of this attribute; it is a mere hint. src the url of the video to embed. this is optional; you may instead use the <source> element within the video block to specify the video to embed. width the width of the video's display area, in css pixels (absolute values only; no percentages). events ...
...And 2 more matches
panel - Archive of obsolete content
var textentrypanel = 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": "./ico...
...s lib directory, and the other files go in your add-on's data directory: my-addon/ data/ get-text.js icon-16.png icon-32.png icon-64.png text-entry.html lib/ main.js the "main.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 textentrypanel = 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: hand...
...don object, whereas content scripts access them through the self object. to show the difference, we can easily convert the text-entry add-on above to use normal page scripts instead of content scripts. the main add-on code is exactly the same as the main add-on code in the previous example, except that we don't attach a content script: 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 textentrypanel = require("sdk/panel").panel({ contenturl: data.url("text-entry.html") }); // 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"...
...ger needed it can be deactivated using destroy(). the content of a panel is specified using the contenturl option. an add-on can interact with the content of a panel using content scripts which it supplies in the contentscript and/or contentscriptfile options. for example, a content script could create a menu and send the user's selection to the add-on. methods destroy() destroys the panel, unloading any content that was loaded in it. once destroyed, the panel can no longer be used. if you just want to hide the panel and might show it later, use hide instead. postmessage(message) sends a message to the content scripts. parameters message : value the message to send. must be stringifiable to json. show(options) displays the panel. if the options argument is given, it will be shallow me...
Listening to events in Firefox extensions - Archive of obsolete content
r are listed here: event description domlinkadded dispatched when a new html <link> element is detected in the document. domtitlechanged dispatched when the title of the page changes. domcontentloaded dispatched when the initial dom for the page is completely loaded. load dispatched after the page—including images—has first finished loading. unload dispatched when the user has navigated away from the page. pageshow dispatched when a page is newly displayed. pagehide dispatched when a page is hidden. standard behavior for web pages is: user navigates to a page. as the page loads, inline scripts run. once the page is loaded, the onload handler fires. some pages include a fourth step. i...
... uses an unload or beforeunload handler, it fires when the user navigates away from the page. if an unload handler is present, the page will not be cached. when a user navigates to a cached page, inline scripts and the onload handler do not run (steps 2 and 3), since in most cases, the effects of these scripts have been preserved. if the page contains scripts or other behaviors that fire during loading that you want to continue to execute every time the user navigates to the page, or if you want to know when a user has navigated to a cached page, use the new pageshow event. if you have behaviors that fire when a user navigates away from the page, but you want to take advantage of this new caching feature, and therefore don't want to use the unload handler, use the new pagehide event. pageshow...
...in document fires. when the user navigates away from the cached page, the pagehide event from each frame fires before the pagehide event in the main document. for navigation that occurs inside a single frame, events fire only in the affected frame. web progress listeners for more information about web loads a web progress listener can be used; these provide more details about the progress of loading data from the web. both browser and tabbrowser elements support the following: var progresslistener = { // add nsiwebprogressimplementation here } b.addprogresslistener(progresslistener); where b is the browser or tabbrowser you want to listen to events for. there are code snippets available that give more detail on using web progress listeners. for a tabbrowser, the above code will only g...
...et progress events for the currently visible browser. it is used to update the ui for many different reasons: update the progress bar and status messages as pages load turn on and off the throbber as pages load set the site icon when available update the address bar as the user navigates hide notification bars when appropriate as the user navigates apply the site zoom preferences to newly loading pages update the bookmarking star button ui update the identity display as the site's security changes tabsprogresslistener this object is a tabs progress listener and receives events for all browsers in the window. it is used to detect when a webpage attempts to refresh itself and allow the user to block the attempt. how events are used by the tabbrowser tabbrowser maintains a set of obje...
Migrate apps from Internet Explorer to Mozilla - Archive of obsolete content
e 4 and earlier, returning the year minus 1900 for years 1900-1999, and the full year for any other year. (i.e. for 1999, getyear() returns 99, for 2000, it returns 2000). javascript execution differences different browsers execute javascript differently. for example, the following code assumes that the div node already exists in the dom by the time the script block executes: ... ...
... such timing-related issues are also hardware-related -- slower systems can reveal bugs that faster systems hide. ...
...stems can reveal bugs that faster systems hide. one concrete example is window.open, which opens a new window: <script> function doopenwindow(){ var mywindow = window.open("about:blank"); mywindow.location.href = "http://www.ibm.com"; } </script> the problem with the code is that window.open is asynchronous -- it does not block the javascript execution until the window has finished loading. therefore, you may execute the line after the window.open line before the new window has finished. you can deal with this by having an onload handler in the new window and then call back into the opener window (using window.opener). differences in javascript-generating html javascript can, through document.write, generate html on the fly from a string. the main issue here is when javascript, e...
... initialization. if async is false, the request is synchronous, else it defaults to asynchronous. optionally, you can specify a username and password for the given url needed. int readystate state of the request. possible values: value description 0 uninitialized - open() has not been called yet. 1 loading - send() has not been called yet. 2 loaded - send() has been called, headers and status are available. 3 interactive - downloading, responsetext holds the partial data. 4 completed - finished with all operations. string responsetext string containing the response. domdocu...
Monitoring downloads - Archive of obsolete content
. handling download state changes once the code above is run, our ondownloadstatechange() method is called whenever a download's state changes. this is part of the nsidownloadprogresslistener interface. that code looks like this: ondownloadstatechange: function(astate, adownload) { var statement; switch(adownload.state) { case components.interfaces.nsidownloadmanager.download_downloading: // add a new row for the download being started; each row includes the // source uri, size, and start time. the end time and download speed // are both set to 0 at first, since we don't know those yet. // status is the same status value that came from the download manager. var dbconn = this.storageservice.opendatabase(this.dbfile); statement = dbconn...
...sidownloadmanager.download_finished: case components.interfaces.nsidownloadmanager.download_failed: case components.interfaces.nsidownloadmanager.download_canceled: this.logtransfercompleted(adownload); break; } }, we're interested in four states. if the download's state, indicated by the adownload.state field, is components.interfaces.nsidownloadmanager.download_downloading, the file has begun to download. the adownload object is an nsidownload object. in that case, we create a new row in our database for the new file by opening the database and building a replace into sqlite command. the first three rows are set to the values of the source uri, file size, and start time fields from the download object. the remaining rows are set to zeroes since that's not informat...
...nt.createelement('listcell'); cell.setattribute("label", speed.tofixed(1) + "kb/sec"); cell.setattribute("style", "text-align:right"); row.appendchild(cell); var status = statement.getint32(5); var style = "color:black"; cell = document.createelement('listcell'); var statusstr; switch(status) { case 0: statusstr = "downloading"; break; case 1: statusstr = "complete"; style = "color:green"; break; case 2: statusstr = "failed"; style = "color:red"; break; case 3: statusstr = "canceled"; style = "color:purple"; break; case 4: statusstr = "paused"; style = "...
... add searching. see also storage, nsidownloadmanager, nsidownload, nsidownloadprogresslistener ...
Venkman Introduction - Archive of obsolete content
irst start venkman, the basic views are arranged as in the screenshot above—though you can customize the layout and presence of the different views however you want, as we describe in the view customization section below. the scripts that have been loaded by the javascript engine appear in the loaded scripts window (for more information about how scripts are loaded and accessed in venkman, see "loading scripts into the debugger"). the menubar, toolbar, and all of the views can be collapsed or hidden, giving you a lot of control over the debugging environment. the source code view is empty until you select a script, and the interactive session view starts up with basic startup information. each of the views has a label, a float button that lets you display the view in its own window, and a c...
...float in their own separate windows. to make a view float, click the float button in the upper left of that view. you can access any of the basic views from the show/hide submenu of the view menu. the list displayed there includes all of the basic views in venkman. as you change which views are displayed and where in the ui they appear, your preferences are stored and persisted across sessions. loading scripts into the debugger whether or not you start venkman first or the browser component, when the mozilla suite starts up, the javascript engine begins to keep track of and compile all the scripts that are loaded in web pages and in the various mozilla user interfaces themselves. the engine tells venkman about the scripts it knows about, and those scripts are loaded into the "loaded scripts" v...
...on provides a brief example of a debugging session in order to familiarize you with some of the basic commands and operations of the debugger. start venkman note: at one point, the debugger needed to be started before the scripts it was going to debug. this limitation is fixed, and now the javascript compiler makes all the scripts you access via the browser available to the debugger. see loading scripts into the debugger for more information about finding and loading scripts in venkman. launch a browser window and go to http://wp.netscape.com/fishcam/dhtmltank.html. note that in mozilla 1.x and netscape 7.x, the debugger contains a window menu like other major components in the application suite. from this menu, you can access the browser, mail, and other applications. typ...
...scripts can have. but the steps described here can give you a basic feel for the debugger if you haven't already had some experience using it, and they provide the basis for the more interesting and practical examples in the articles that follow this one. the best way to get to know venkman, of course, is to play around with it — to set it up in the way that makes the most sense to you, to try loading scripts and setting breakpoints, evaluating expressions in the interactive session view, watching the values of variables as they change when scripts are executed, getting profile data. debugging extensions although at first glance it might seem that venkman cannot debug extensions, doing so is in fact fully supported; it's just disabled by default. to debug your extension with venkman (xul fi...
XUL Questions and Answers - Archive of obsolete content
aries the frequently asked questions should be moved to xul faq (make sure they have a clear answer.) where can i get more information about creating mozsearch plugins? creating mozsearch plugins contains more help information about creating mozsearch plugin on firefox 2. more documentation on search plugins is available in the search plugins category. is localizing remote xul possible? loading remote dtds for xml documents is currenty not supported in xul. the following bugs were reported on this issue: bug 22942, bug 133698. is there an editor widget in xul that supports syntax highlighting? daniel glazman has been working on this for his projects. he said the code will be open-source, but it is not released yet (as of oct 2006). some teasers are on his blog. overlaying element...
... a scheme is in development to allow servers to open up their site for cross-site access, but that's not yet done. hidechrome="true" doesn’t work on a ...
... a scheme is in development to allow servers to open up their site for cross-site access, but that's not yet done. hidechrome="true" doesn’t work on a mac? unfortunately, no simple solution to this was posted. a w...
...in addition i need to evaluate the browser contentdocument dom in order to clean "target" attributes on links, and so on. */ how do i create xul elements dynamically in javascript? use the following snippet of code to add a new element under an existing element: var elem = document.getelementbyid(xul_element_id); var node = document.createelement(xul_element_na...
RDF in Mozilla FAQ - Archive of obsolete content
pen directory dataset is available as a (huge) rdf/xml dump. it describes thousands of web sites using a mix of the dublin core metadata vocabulary and the dmoz taxonomy. see their rdf pages for more information. if you have problems with the dmoz and chefmoz data, it's best to contact those projects directly. but if you do something interesting with this content (eg. have mozilla use it, eg. by loading chunks of it into a xul ui from a remote site), don't forget to let mozilla-rdf and the rdf interest group lists know. those lists would probably also be interested in tools for cleaning / re-processing / storing the dmoz data too. see the sites using odp data pages for some directories based on the odp rdf dumps. what is a datasource? rdf can generally be viewed in two ways: either as a graph ...
...ervice;1"] .getservice(components.interfaces.nsirdfservice); // get the datasource. var ds = rdf.getdatasource("http://www.mozilla.org/some-rdf-file.rdf"); // now see if it's loaded or not... var remote = ds.queryinterface(components.interfaces.nsirdfremotedatasource); if (remote.loaded) { alert("the datasource was already loaded!"); } else { alert("the datasource wasn't loaded, but it's loading now!"); } say the datasource wasn't loaded, and is loading asynchronously. using this api and javascript's settimeout(), one could set up a polling loop that would continually check the loaded property. this is kludgy, and even worse, won't detect a failed load, for example, if there wasn't any data at the url! for this reason, there is an observer interface that allows you to spy on a datasou...
...ervice;1"] .getservice(components.interfaces.nsirdfservice); // get the datasource. var ds = rdf.getdatasource("http://www.mozilla.org/some-rdf-file.rdf"); // now see if it's loaded or not... var remote = ds.queryinterface(components.interfaces.nsirdfremotedatasource); if (remote.loaded) { alert("the datasource was already loaded!"); } else { alert("the datasource wasn't loaded, but it's loading now!"); // rdf/xml datasources are all nsirdfxmlsinks var sink = ds.queryinterface(components.interfaces.nsirdfxmlsink); // attach the observer to the datasource-as-sink sink.addxmlsinkobserver(observer); // now observer's methods will be called-back as // the load progresses. } note that the observer will remain attached to the rdf/xml datasource unless removexmlsinkobserver is...
...ivering the file as text/xml (recommended) or text/rdf (bogus). note that the w3c rdf core wg are registering application/rdf+xml, though this isn't understood by any mozilla code yet. (do we have a bug registered to track this? -- danbri) another possible problem: for remotely-loaded xul and rdf, you might need to adjust mozilla's security restrictions (see belowfor example code). if xul isn't loading your rdf, and the mimetype is ok, this could well be your problem. you can use the rdfcat and rdfpoll utilities to verify that the rdf/xml is actually valid. both of these programs are built by default on windows, and on linux when the configure --enable-tests is specified. rdfcat url takes as a parameter a url from which to read an rdf/xml file, and will "cat" the file back to the console.
The "why" of web performance - Learn web development
owser, and how well it responds to user interaction. bad performing sites are slow to display and slow to respond to input. bad performing sites increase site abandonment. at its worst, bad performance causes content to be completely inaccessible. a good goal for web performance is for users to not notice performance. while an individual's perception of site performance performance is subjective, loading and rendering can be measured. good performance may not be obvious to most site visitors, but most will immediately recognize a sluggish site. that is why we care. why care about performance? web performance—and its assocatiated best practices—are vital for your website visitors to have a good experience. in a sense, web performance can be considered a subset of web accessibility. with perf...
...re. why care about performance? web performance—and its assocatiated best practices—are vital for your website visitors to have a good experience. in a sense, web performance can be considered a subset of web accessibility. with performance as with accessibility, you consider what device a site visitor is using to access the site and the device connection speed. ...
...good experience. in a sense, web performance can be considered a subset of web accessibility. with performance as with accessibility, you consider what device a site visitor is using to access the site and the device connection speed. as an example, consider the loading experience of cnn.com, which at the time of this writing had over 400 http requests with a file size of over 22.6mb. imagine loading this on a desktop computer connected to a fibre optic network. this would seem relatively fast, and the file size would be largely irrelevant. imagine loading that same site using tethered mobile data on a 9 year-old ipad while commuting home on public transportation. the same site will be slow to load, possibly verging on unusable depending on cell coverage. you might give up before it finishes...
...this on a desktop computer connected to a fibre optic network. this would seem relatively fast, and the file size would be largely irrelevant. imagine loading that same site using tethered mobile data on a 9 year-old ipad while commuting home on public transportation. the same site will be slow to load, possibly verging on unusable depending on cell coverage. you might give up before it finishes loading. imagine loading that same site on a $35 huawei device in a rural india with limited coverage or no coverage. the site will be very slow to load—if it loads at all—with blocking scripts possibly timing out, and adverse cpu impact causing browser crashes if it does load. a 22.6 mb site could take up to 83 seconds to load on a 3g network, with domcontentloaded (meaning the site's base html s...
Introduction to automated testing - Learn web development
if you get errors, check that you've added all the dependencies and the tests as shown above; also try commenting out the html/css/javascript code sections and then rerunning gulp to see if you can isolate what the problem is. gulp comes with a watch() function that you can use to watch your files and run tests whenever you save a file. for example, try add...
...al number of tests to date, and more. to start off with manual testing you need to select the "real time testing" tab from the left navigation menu. as you click on the real time testing you will be directed to a screen where you can choose the browser configuration, browser version, os, and screen resolution with which you want to test your website. as you click on the start button, a loading screen will appear, providing you with a vm (virtual machine) based on your configurations. once loaded, you can perform live, interactive cross-browser testing with a website. if you notice an issue with the ui, then you can share it with your colleagues by capturing a screenshot of your vm with the screenshot button. you can also record a video of your test session by hitting the recorder ...
...al tests tab. click start a new manual session. in the next screen, type in the url of a page you want to test (use http://mdn.github.io/learning-area/javascript/building-blocks/events/show-video-box-fixed.html, for example), then choose a browser/os combination you want to test by using the different buttons and lists. there is a lot of choice, as you'll see! when you click start session, a loading screen will then appear, which spins up a virtual machine running the combination you chose. when loading has finished, you can then start to remotely test the web site running in the chosen browser. from here you can see the layout as it would look in the browser you are testing, move the mouse around and try clicking buttons, etc. the top menu allows you to: stop the session give som...
... should happen automatically after you verify your e-mail address. the basics: manual tests the testingbot dashboard lists the various options you can choose from. for now, make sure you are on the live web testing tab. enter the url of the page you want to test. choose the browser/os combination you want to test by selecting the combination in the grid. when you click start browser, a loading screen will then appear, which spins up a virtual machine running the combination you chose. when loading has finished, you can then start to remotely test the web site running in the chosen browser. from here you can see the layout as it would look in the browser you are testing, move the mouse around and try clicking buttons, etc. the side menu allows you to: stop the session change ...
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. ...
...ote: visual c++ will show you something in the quick watch window, but not the stack, you have to look in the os console for the output. also this magical command only works when the vc++ stack is in certain states. it works when you have js_interpret() in the newest stackframe debugging minidumps see debugging a minidump. debugging tinderbox builds see running windows debug builds problems loading debug symbols if both your application and visual c++ hang shortly after launching the application under the debugger, you may be hitting a known deadlock in the way visual studio downloads debug symbols for the system libraries; see https://connect.microsoft.com/visualstudio/feedback/details/422970/hang-loading-rasapi32-pdb-when-using-symbol-server. there are two ways to work around this probl...
...ion and visual c++ hang shortly after launching the application under the debugger, you may be hitting a known deadlock in the way visual studio downloads debug symbols for the system libraries; see https://connect.microsoft.com/visualstudio/feedback/details/422970/hang-loading-rasapi32-pdb-when-using-symbol-server. there are two ways to work around this problem: turn off automatic symbol downloading for system libraries: in tools > options > debugging > symbols, uncheck the microsoft symbol server. pre-load all the windows debug symbols. these instructions apply to visual studio 10 on windows 7; other software versions likely need to have file paths adjusted. locate the microsoft utility "symchk.exe" on your system (it will likely be in the installation directory of your windows debug...
... open the menu to tools > options > debugging > symbols and copy the field "cache symbols in this directory". in a command window, run symchk.exe /r c:\windows\syswow64\ /s "srv*<your cache symbols directory>\microsoftpublicsymbols*http://msdl.microsoft.com/download/symbols" note the "\microsoftpublicsymbols" appended to the cache directory configured in visual studio. downloading all symbols can take a long time; you can replace c:\windows\syswow64\ with the name of a single .dll to download symbols only for the specific libraries you are trying to debug. unfortunately, it's hard to know which symbols to download without having vs hang and seeing the "downloading symbols for <library>" status at the bottom left of the main window. problems post-mortem debugging on window...
Index
pecting, and use the correct template for parsing, based on the context of your software's interaction. data described as pem is a base64 encoded presentation of der, usually wrapped between human readable begin/end lines. nss prefers the binary presentation, but is often capable to use base64 or ascii presentations, especially when importing data from files. a recent development adds support for loading external pem files that contain private keys, in a software library called nss-pem, which is separately available, but should eventually become a core part of nss. looking at the code level, nss deals with blocks of raw data all the time. the common structure to store such an untyped block is secitem, which contains a size and an untyped c pointer variable. when dealing with memory, nss mak...
...layer and an ssl library layer. the mozilla applications define a third layer where application specific processing is performed. you can find more details in the nspr reference documents. nss occassionally has to create outbound network connections, in addition to the connections requested by the application. examples are retrieving ocsp (online certificate status protocol) information or downloading a crl (certificate revocation list). however, nss doesn't have an implementation to work with network proxies. if you must support proxies in your application, you are able to register your own implementation of an http request callback interface, and nss can use your application code that supports proxies. when using hashing, encryption, and decryption functions, it is possible to stream data...
... certificate db token manufacturer: mozilla foundation token model: nss 3 token serial number: 0000000000000000 token version: 8.3 token firmware version: 0.0 access: not write protected login type: login required user pin: initialized a related command, -rawlist returns information about the database configuration for the modules. (this information can be edited by loading new specs using the -rawadd command.) modutil -rawlist -dbdir sql:/home/my/sharednssdb name="nss internal pkcs #11 module" parameters="configdir=. certprefix= keyprefix= secmod=secmod.db flags=readonly " nss="trustorder=75 cipherorder=100 slotparams={0x00000001=[slotflags=rsa,rc4,rc2,des,dh,sha1,md5,md2,ssl,tls,aes,random askpw=any timeout=30 ] } flags=internal,critical" setting a de...
...tokenname argument can search a specific token or all tokens. o if there are multiple key types available, then the -k key-type argument can search a specific type of key, like rsa, dsa, or ecc. listing security modules the devices that can be used to store certificates -- both internal databases and external devices like smart cards -- are recognized and used by loading security modules. the -u command option lists all of the security modules listed in the secmod.db database. the path to the directory (-d) is required. $ certutil -u -d sql:/home/my/sharednssdb slot: nss user private key and certificate services token: nss certificate db slot: nss internal cryptographic services token: nss generic crypto services adding certificate...
Finishing the Component
e component will be recognized by xpcom and registered with the category manager so that it starts up when xpcom initializes. when the component starts up, it populates a list of urls read in from a file stored next to the gecko binary on the local system. using frozen interfaces the core functionality of blocking sites is still missing, however. the interfaces needed to block certain urls from loading are not frozen, and there is still some debate about how exactly this functionality should be exposed to embedders and component developers, so the apis are not ready to be published. this puts you in the same situation as many developers using mozilla - you want to use some specific functionality, but the interfaces seem to change on a daily basis. all of the mozilla source code is publicly ava...
... as might be the case when the weblock component is used in a corporate intranet, for example - there are networking apis in gecko that will support this. or you could implement the web lock so that instead of blocking any site, the component would simply log all urls that are loaded. in any case, the process to make the xpcom component is the same. the method that handles the check before page loading and the only method we care about in our own implementation of nsicontentpolicy is shouldload(). the other method on the nsicontentpolicy interface is for blocking processing of specific elements in a document, but our policy is more restrictive: if the url isn't on the white list, the entire page should be blocked. in the weblock component, the shouldload method looks like this: ns_imethodimp w...
...ts the uri of the file. when you pass that string to necko, it creates an object that implements at least the nsiuri interface (and perhaps other interfaces as well). currently, the weblock implementation of the shouldload method compares the in parameter with each string in the white list. but it only should do this comparison for remote urls, because we don't want to block the application from loading local content that it requires, like files it gets via the resource:// protocol. if uris of this kind are blocked, then gecko will not be able to start up, so we'll restrict the content policy to the http and ftp protocols. instead of extracting the string spec out of the nsiuri to do a string comparison, which would require you to do the parsing yourself, you can compare the nsiuri objects with...
...the parsing yourself, you can compare the nsiuri objects with each other, as in the following section. this ensures that the urls are canonical before they are compared. checking the white list the weblock implementation of the shouldload method starts by extracting the scheme of the incoming nsiuri. if the scheme isn't "http", "https", or "ftp", it immediately returns true, which continues the loading process unblocked. these three are the only kinds of uri that weblock will try to block. when it has one, it walks the linked list and creates a new nsiuri object for each string url in the list. from each object, shouldload() extracts the host and compares it to the uri. if they match, the component allows the load to continue by returning true. if these two strings do not match, then the compo...
Index
Mozilla › Tech › XPCOM › Index
rface reference the parentprocessmessagemanager is used for this, so messages send from childprocessmessagemanagers will be heard. 745 nsimessenger interfaces, interfaces:scriptable, messages, needscontent, xpcom api reference, xpcom interface reference, thunderbird the nsimessenger interface provides functions for managing the history, undo and redo operations, and for loading, saving, or deleting messages and attachments in mailnews. 746 nsimicrosummary interfaces, interfaces:scriptable, microsummaries, xpcom, xpcom api reference, xpcom interface reference add a microsummary observer to this microsummary. 747 nsimicrosummarygenerator interfaces, interfaces:scriptable, microsummaries, xpcom, xpcom api reference, xpcom interface refer...
... 883 available no summary! 884 close no summary! 885 init no summary! 886 ...
... 883 available no summary! 884 close no summary! 885 init no summary! 886 read ...
...070 nsiwebpagedescriptor interfaces, interfaces:scriptable, xpcom interface reference tells the object to load the page specified by the page descriptor. 1071 nsiwebprogress interfaces, interfaces:scriptable, xpcom, xpcom api reference, xpcom interface reference the nsiwebprogress interface is used to add or remove nsiwebprogresslistener instances to observe the loading of asynchronous requests (usually in the context of a dom window). 1072 nsiwebprogresslistener interfaces, interfaces:scriptable, needsmarkupwork, xpcom, xpcom api reference, xpcom interface reference nsiwebprogress describes the parent-child relationship of nsiwebprogress instances. 1073 nsiwebprogresslistener2 interfaces, interfaces:scriptable, xpcom, xpcom i...
nsIWebProgressListener
inherits from: nsisupports last changed in gecko 15 (firefox 15 / thunderbird 15 / seamonkey 2.12) nsiwebprogress describes the parent-child relationship of nsiwebprogress instances. ...
... normal requests. state_is_document 0x00020000 this flag indicates that the state transition is for a document request. this flag is set in addition to state_is_request. a document request supports the nsichannel interface and its loadflags attribute includes the nsichannel::load_document_uri flag. a document request does not complete until all requests associated with the loading of its corresponding document have completed. this includes other document requests (for example corresponding to html <iframe> elements). the document corresponding to a document request is available via the domwindow attribute of onstatechange()'s awebprogress parameter. state_is_network 0x00040000 this flag indicates that the state transition corresponds to the start or sto...
...on. methods onlocationchange() called when the location of the window being watched changes. this is not when a load is requested, but rather once it is verified that the load is going to occur in the given window. for instance, a load that starts in a window might send progress and status messages for the new site, but it will not send the onlocationchange until we are sure that we are loading this new page here. another example: the loading of a pdf or flash file might not not send onlocationchange if the document is handed off to a third-party tool rather than being loaded into the browser. void onlocationchange( in nsiwebprogress awebprogress, in nsirequest arequest, in nsiuri alocation, [optional] in unsigned long aflags ); parameters awebprogress the nsiwebprogress ...
...for all requests associated with awebprogress. amaxtotalprogress the total progress for all requests associated with awebprogress. onsecuritychange() notification called for security progress. this method will be called on security transitions (for example http -> https, https -> http, foo -> https) and after document load completion. it might also be called if an error occurs during network loading. note: these notifications will only occur if a security package is installed. void onsecuritychange( in nsiwebprogress awebprogress, in nsirequest arequest, in unsigned long astate ); parameters awebprogress the nsiwebprogress instance that fired the notification. arequest the nsirequest that has new security state. astate a value composed of the security state flags and the se...
XUL Overlays
Mozilla › Tech › XUL › Overlays
> <menuitem name="super stream player"/> </menupopup> </menu> ... if you are developing a mozilla extension, note that the id namespace is shared by all the extensions. so, in order to avoid unpredicted behaviors you will probably benefit from using a unique prefix for the ids of the xul elements of your extension. for instance, you can use the name of your extension, or an abbreviation of it. ...
...our extension. for instance, you can use the name of your extension, or an abbreviation of it. loading overlays overlays can be loaded explicitly or dynamically. when you load an overlay explicitly, it means that you intend to make it available every time the base file is loaded. since one of the main purposes of overlays is to provide ui for additions or components to the basic package, explicit loading can be somewhat problematic when the overlay defines optional ui elements. loading overlays explicitly a processing instruction is used to load overlay files explicitly into the master document. inserting the following processing instruction before the doctype declaration in a base file tells the layout engine to load the named overlay file: <?xul-overlay href="chrome://component/content/componen...
... incremental insertion in menus, boxes, tables, and forms are avoided. any number of overlays can be loaded into a master document, and an overlay can also load other overlays. because an overlay is superimposed on the master document, there are no ambiguities relating to scoping of style sheets or scripts. style sheets and scripts loaded by the overlay simply apply to the entire master document. loading overlays dynamically the chrome registry makes it possible to load xul overlays dynamically -- or only when necessary. the chrome registry, which is a special rdf datasource into which user-specific information is persisted, or stored, contains information about the components or additional packages that have been installed with the browser. when a component such as the "super stream player" from...
... into which user-specific information is persisted, or stored, contains information about the components or additional packages that have been installed with the browser. when a component such as the "super stream player" from the examples above is registered there, overlays associated with that component are loaded automatically. when the component is not present, only the base files are loaded. loading overlays at runtime firefox 1.5 and other gecko 1.8-based applications also support loading overlays on-the-fly via the document.loadoverlay() function. todo: elaborate overlays and skins warning: always load master skins from base files. never load master skins from overlays. unlike base files, overlays should never load the master skin file for a package. the navigatoroverlay.xul file, for ex...
Console messages - Firefox Developer Tools
ges shown in the web console help developers find potential or actual vulnerabilities in their sites. additionally, many of these messages help educate developers because they end with a “learn more” link that takes you to a page with background information and advice for mitigating the issue. ...
...he issue. the complete list of security messages is as follows: message details blocked loading mixed active content the page contained mixed active content: that is, the main page was served over https, but asked the browser to load "active content", such as scripts, over http. the browser blocked this active content. see mixed content for more details. blocked loading mixed display content the page contained mixed display content: that is, the main page was served over https, but asked the browser to load "display content", such as images, over http. the browser blocked this display content. see mixed content for more details. ...
...s scripts, over http. the browser blocked this active content. see mixed content for more details. blocked loading mixed display content the page contained mixed display content: that is, the main page was served over https, but asked the browser to load "display content", such as images, over http. the browser blocked this display content. see mixed content for more details. loading mixed (insecure) active content on a secure page the page contained mixed active content: that is, the main page was served over https, but asked the browser to load "active content", such as scripts, over http. the browser loaded this active content. ...
...the browser loaded this display content. see mixed content for more details. ...
Using images - Web APIs
would be to use a second canvas element as a thumbnail view of the other larger canvas. creating an image from scratch another option is to create new htmlimageelement objects in our script. to do this, you can use the convenient image() constructor: var img = new image(); // create new img element img.src = 'myimage.png'; // set source path when this script gets executed, the image starts loading. if you try to call drawimage() before the image has finished loading, it won't do anything (or, in older browsers, may even throw an exception). so you need to be sure to use the load event so you don't try this before the image has loaded: var img = new image(); // create new img element img.addeventlistener('load', function() { // execute drawimage statements here }, false); img.src = 'm...
... img = new image(); // create new img element img.addeventlistener('load', function() { // execute drawimage statements here }, false); img.src = 'myimage.png'; // set source path if you're only using one external image this can be a good approach, but once you need to track more than one we need to resort to something more clever. it's beyond the scope of this tutorial to look at image pre-loading tactics, but you should keep that in mind. embedding an image via data: url another possible way to include images is via the data: url. data urls allow you to completely define an image as a base64 encoded string of characters directly in your code. var img = new image(); // create new img element img.src = 'data:image/gif;base64,r0lgodlhcwalaiaaaaaa3pn/zih5baeaaaealaaaaaalaasaaaiuha+hkcuo4...
...the images are hidden from output by setting the css property display to none for those images. screenshotlive sample the script itself is very simple. each <img> is assigned an id attribute, which makes them easy...
.../div> </body> </html> function draw() { var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); // draw slice ctx.drawimage(document.getelementbyid('source'), 33, 71, 104, 124, 21, 20, 87, 104); // draw frame ctx.drawimage(document.getelementbyid('frame'), 0, 0); } we took a different approach to loading the images this time. instead of loading them by creating new htmlimageelement objects, we included them as <img> tags directly in our html source and retrieved the images from those. the images are hidden from output by setting the css property display to none for those images. screenshotlive sample the script itself is very simple. each <img> is assigned an id attribute, which makes them easy to select using document.getelementbyid(...
Document: DOMContentLoaded event - Web APIs
the domcontentloaded event fires when the initial html document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. bubbles yes cancelable yes (although specified as a simple event that isn't cancelable) interface event event handler property none a different event, load, should be used only to detect a fully-loaded page. it is a common mistake to use load where domcontentloaded would be more appropriate. synchronous javascript pauses parsing of the dom. if you want the dom to get parsed as fast as possible after the user has requested the page, you can make your javascript asynchronous and optimize loading of stylesheets. if loaded as usual, stylesheets slow down dom parsing as ...
... console.log('dom fully loaded and parsed'); }); delaying domcontentloaded <script> document.addeventlistener('domcontentloaded', (event) => { console.log('dom fully loaded and parsed'); }); for( let i = 0; i < 1000000000; i++) {} // this synchronous script is going to delay parsing of the dom, // so the domcontentloaded event is going to launch later. ...
...00; i++) {} // this synchronous script is going to delay parsing of the dom, // so the domcontentloaded event is going to launch later. </script> checking whether loading is already complete domcontentloaded may fire before your script has a chance to run, so it is wise to check before adding a listener. ...
...his synchronous script is going to delay parsing of the dom, // so the domcontentloaded event is going to launch later. </script> checking whether loading is already complete domcontentloaded may fire before your script has a chance to run, so it is wise to check before adding a listener. ...
HTMLMediaElement.load() - Web APIs
the amount of media data that is prefetched is determined by the value of the element's preload attribute. this method is generally only useful when you've made dynamic changes to the set of sources available for the media element, either by changing the element's src attribute or by adding or removing <source> elements nested within the media element itself. ...
...ute or by adding or removing <source> elements nested within the media element itself. load() will reset the element and rescan the available sources, thereby causing the changes to take effect. syntax mediaelement.load(); parameters none. return value undefined. usage notes calling load() aborts all ongoing operations involving this media element, then begins the process of selecting and loading an appropriate media resource given the options specified in the <audio> or <video> element and its src attribute or child <source> element(s). this is described in more detail in supporting multiple formats in video and audio content. the process of aborting any ongoing activities will cause any outstanding promises returned by play() being resolved or rejected as appropriate based on their sta...
... media resource given the options specified in the <audio> or <video> element and its src attribute or child <source> element(s). this is described in more detail in supporting multiple formats in video and audio content. the process of aborting any ongoing activities will cause any outstanding promises returned by play() being resolved or rejected as appropriate based on their status before the loading of new media can begin. pending play promises are aborted with an "aborterror" domexception. appropriate events will be sent to the media element itself as the load process proceeds: if the element is already in the process of loading media, that load process is aborted and the abort event is sent. if the element has already been initialized with media, the emptied event is sent. if resetti...
... from this point onward, events are sent just like any media load. example this example finds a <video> element in the document and resets it by calling load(). ...
Using Navigation Timing - Web APIs
her techniques. it also offers the advantage of being able to provide timing information as perceived by the user rather than data that has no correlation to what the user experiences. collecting timing information using the api is as simple as obtaining the performance object using window.performance and looking up what you need within the object returned. ...
...er rather than data that has no correlation to what the user experiences. collecting timing information using the api is as simple as obtaining the performance object using window.performance and looking up what you need within the object returned. for example, to measure the perceived loading time for a page: window.addeventlistener("load", function() { let now = new date().gettime(); let loadingtime = now - performance.timing.navigationstart; document.queryselector(".output").innertext = loadingtime + " ms"; }, false); this code, executed when the load event occurs, subtracts from the current time the time at which the navigation whose timing was recorded began (performance.timing.navigationstart), and outputs that information to the screen by inserting it into an element. ...
... how many (if any) redirects were required in order to complete the navigation? this information is provided by the performance.navigation property, which returns a performancenavigation object that includes the needed information. let's add this information to the example above. ...
...is information is provided by the performance.navigation property, which returns a performancenavigation object that includes the needed information. let's add this information to the example above. ...
Resource Timing API - Web APIs
the resource timing interfaces enable retrieving and analyzing detailed network timing data regarding the loading of an application's resource(s). an application can use the timing metrics to determine, for example, the length of time it takes to load a specific resource, such as an xmlhttprequest, <svg>, image, or script. 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. the interface also includes other properties that provide data about the size of the fetched resource as well as the type of resource that initiated the fetch. this document provides an overview of the resource timing interfaces. for more details...
... the difference in time between two discrete points in time. the unit of domhighrestimestamp is milliseconds and should be accurate to 5 µs (microseconds). however, if the browser is unable to provide a time value accurate to 5 µs (because, for example, due to hardware or software constraints), the browser can represent a the value as a time in milliseconds accurate to a millisecond. resource loading timestamps an application can get timestamps for the various stages used to load a resource. the first property in the processing model is starttime which returns the timestamp immediately before the resource loading process begins. the fetchstart timestamps follows and redirect processing (if applicable) and preceeds dns lookup. the next stages are connectstart and connectend which are the time...
.... when cors is in effect, many of these values are returned as zero unless the server's access policy permits these values to be shared. this requires the server providing the resource to send the timing-allow-origin http response header with a value specifying the origin or origins which are allowed to get the restricted timestamp values. the properties which are returned as 0 by default when loading a resource from a domain other than the one of the web page itself: redirectstart, redirectend, domainlookupstart, domainlookupend, connectstart, connectend, secureconnectionstart, requeststart, and responsestart. the performanceresourcetiming interface also includes several network timing properties. the redirectstart and redirectend properties return timestamps for redirect start and end time...
...ncludes several network timing properties. the redirectstart and redirectend properties return timestamps for redirect start and end times, respectively. likewise, the the domainlookupstart and domainlookupend properties return timestamps for dns lookup start and end times, respectively. this would be a nice place to have a diagram showing the relationships between these segments of the resource loading time. resource size the performanceresourcetiming interface has three properties that can be used to obtain size data about a resource. the transfersize property returns the size (in octets) of the fetched resource including the response header fields plus the response payload body. the encodedbodysize property returns the size (in octets) received from the fetch (http or cache), of the payloa...
XMLHttpRequest.readyState - Web APIs
equest.readystate property returns the state an xmlhttprequest client is in. an xhr client exists in one of the following states: value state description 0 unsent client has been created. open() not called yet. 1 opened open() has been called. 2 headers_received send() has been called, and headers and status are available. 3 loading downloading; responsetext holds partial data. 4 done the operation is complete. unsent the xmlhttprequest client has been created, but the open() method hasn't been called yet. opened open() method has been invoked. during this state, the request headers can be set using the setrequestheader() method and the send() method can be called which will initiate the fetch. ...
... complete. unsent the xmlhttprequest client has been created, but the open() method hasn't been called yet. opened open() method has been invoked. during this state, the request headers can be set using the setrequestheader() method and the send() method can be called which will initiate the fetch. headers_received send() has been called and the response headers have been received. loading response's body is being received. if responsetype is "text" or empty string, responsetext will have the partial text response as it loads. done the fetch operation is complete. this could mean that either the data transfer has been completed successfully or failed. the state names are different in versions of internet explorer earlier than 11. instead of unsent, opened, headers_received, l...
...pty string, responsetext will have the partial text response as it loads. done the fetch operation is complete. this could mean that either the data transfer has been completed successfully or failed. the state names are different in versions of internet explorer earlier than 11. ...
...e names readystate_uninitialized (0), readystate_loading (1), readystate_loaded (2), readystate_interactive (3) and readystate_complete (4) are used. ...
Overview of events and handlers - Developer guides
il they receive all of the resources associated with a page, to parse, process, draw, and present the page to the user. the displayed page remains unchanged until the browser requests a new page. with the change to dynamic page rendering, browsers loop continuously between processing, drawing, presenting content, and waiting for some new event trigger. event triggers include the completion of the loading of a resource on the network e.g., downloads an image that can now be drawn on the screen, the completion of parsing a resource by the browser e.g., processes the html content of a page, the interaction of a user with the contents of the page e.g., clicks a button. douglas crockford explains this change effectively in several lectures, notably his talk, an inconvenient api: the theory of the dom,...
...tical to list them all. the event reference attempts to maintain a list of the standard events used in modern web browsers. in general, we can distinguish events of different kinds based on the object emitting the event including: the window object, such as due to resizing the browser, the window.screen object, such as due to changes in device orientation, the document object, including the loading, modification, user interaction, and unloading of the page, the objects in the dom (document object model) tree including user interactions or modifications, the xmlhttprequest objects used for network requests, and the media objects such as audio and video, when the media stream players change state. although this list is currently incomplete. some notable events are: note: this list of ...
...or network requests, and the media objects such as audio and video, when the media stream players change state. although this list is currently incomplete. some notable events are: note: this list of events will need work to make relevant; that work is awaiting some global reorganization work on the documents. this will also need finding a good explanation of the events involved during page loading, such as discussed partially in this web page or in this stack overflow question. the global object window emits an event called 'load' when the page has finished rendering, meaning that all resources have been downloaded and acted upon, so that the scripts have been run and the images displayed, the global object window emits an event called 'resize' when the height or the width of the bro...
... the event object hierarchy the web browser defines many events of different kinds. each definition includes, as the data structure passed to the handler function, an object which inherits from the eventprototype o...
<audio>: The Embed Audio element - HTML: Hypertext Markup Language
Web › HTML › Element › audio
ult audio controls, etc. the content inside the opening and closing <audio></audio> tags is shown as a fallback in browsers that don't support the element. attributes this element's attributes include the global attributes. autoplay a boolean attribute: if specified, the audio will automatically begin playback as soon as it can do so, without waiting for the entire audio file to finish downloading. note: sites that automatically play audio (or videos with an audio track) can be an unpleasant experience for users, so should be avoided when possible. if you must offer autoplay functionality, you should make it opt-in (requiring a user to specifically enable it). however, this can be useful when creating media elements whose source will be set at a later time, under user control. see our aut...
...etched. auto: indicates that the whole audio file can be downloaded, even if the user is not expected to use it. empty string: a synonym of the auto value. the default value is different for each browser. the spec advises it to be set to metadata. usage notes: the autoplay attribute has precedence over preload. if autoplay is specified, the browser would obviously need to start downloading the audio for playback. the browser is not forced by the specification to follow the value of this attribute; it is a mere hint. src the url of the audio to embed. this is subject to http access controls. this is optional; you may instead use the <source> element within the audio block to specify the audio to embed. events event name fired when audioprocess ...
... durationchange the duration attribute has been updated. emptied the media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the load() method is called to reload it. ended playback has stopped because the end of the media was reached. loadeddata the first frame of the media has finished loading. loadedmetadata the metadata has been loaded. pause playback has been paused. play playback has begun. playing playback is ready to start after having been paused or delayed due to lack of data. ratechange the playback rate has changed. seeked a seek operation completed. seeking a seek operation began. s...
...has begun. playing playback is ready to start after having been paused or delayed due to lack of data. ratechange the playback rate has changed. seeked a seek operation completed. seeking a seek operation began. stalled the user agent is trying to fetch media data, but data is unexpectedly not forthcoming. suspend media data loading has been suspended. timeupdate the time indicated by the currenttime attribute has been updated. volumechange the volume has changed. waiting playback has stopped because of a temporary lack of data usage notes browsers don't all support the same file types and audio codecs; you can provide multiple sources inside nested <source> elements, and the brows...
Index - HTTP
Web › HTTP › Headers › Index
ve restricts the urls which can be used in a document's <base> element. if this value is absent, then any uri is allowed. if this directive is absent, the user agent will use the value in the <base> element. 30 csp: block-all-mixed-content csp, directive, http, mixed content, reference, security the http content-security-policy (csp) block-all-mixed-content directive prevents loading any assets using http when the page is loaded using https. 31 csp: child-src csp, directive, http, reference, security the deprecated http content-security-policy (csp) child-src directive defines the valid sources for web workers and nested browsing contexts loaded using elements such as <frame> and <iframe>. for workers, non-compliant requests are treated as fatal network e...
... csp, directive, http, security the http content-security-policy (csp) frame-ancestors directive specifies valid parents that may embed a page using <frame>, <iframe>, <object>, <embed>, or <applet>. 37 csp: frame-src csp, directive, http, reference, security the http content-security-policy (csp) frame-src directive specifies valid sources for nested browsing contexts loading using elements such as <frame> and <iframe>. 38 csp: img-src csp, directive, http, reference, security the http content-security-policy img-src directive specifies valid sources of images and favicons. 39 csp: manifest-src csp, directive, http, reference, security the http content-security-policy: manifest-src directive specifies which manifest can be app...
...d sources of images and favicons. 39 csp: manifest-src csp, directive, http, reference, security the http content-security-policy: manifest-src directive specifies which manifest can be applied to the resource. 40 csp: media-src csp, directive, http, reference, security the http content-security-policy (csp) media-src directive specifies valid sources for loading media using the <audio> and <video> elements. 41 csp: object-src csp, directive, http, reference, security the http content-security-policy object-src directive specifies valid sources for the <object>, <embed>, and <applet> elements. 42 csp: plugin-types csp, directive, flash, http, java, plugins, security the http content-security-policy (csp) plugin-ty...
...owser should be allowed to render a page in a <frame>, <iframe>, <embed> or <object> . sites can use this to avoid clickjacking attacks, by ensuring that their content is not embedded into other sites. 122 x-xss-protection http, reference, security, xss, header the http x-xss-protection response header is a feature of internet explorer, chrome and safari that stops pages from loading when they detect reflected cross-site scripting (xss) attacks. although these protections are largely unnecessary in modern browsers when sites implement a strong content-security-policy that disables the use of inline javascript ('unsafe-inline'), they can still provide protections for users of older web browsers that don't yet support csp. ...
Link prefetching FAQ - HTTP
when the user visits one of the prefetched documents, it can be served up quickly out of the browser's cache. ...
...ifications, and we approximate idle time as the period between the last document stop and the next document start. the last document stop notification occurs roughly when the onload handler would fire for the toplevel document. this is when we kick off prefetch requests. if a subframe contains prefetching hints, prefetching will not begin until the top-most frame and all its "child" frames finish loading. what happens if i click on a link while something is being prefetched? when the user clicks on a link, or initiates any kind of page load, link prefetching will stop and any prefetch hints will be discarded. if a prefetched document is partially downloaded, then the partial document will still be stored in the cache provided the server sent an "accept-ranges: bytes" response header. this heade...
...document is partially downloaded, then the partial document will still be stored in the cache provided the server sent an "accept-ranges: bytes" response header. this header is typically generated by webservers when serving up static content. when the user visits a prefetched document for real, the remaining portion of the document will be fetched using a http byte-range request. what if i'm downloading something in the background? will link prefetching compete for bandwidth? yes and no. if you are downloading something using mozilla, link prefetching will be delayed until any background downloads complete. for example, if you load a bookmark group (which opens several tabs), any prefetch requests initiated by one of the bookmarked pages will not begin until all of the tabs finish loading. if y...
...e obscure preference. what about folks who pay-per-byte for network bandwidth? basically, there are two ways of looking at this issue: websites can already cause things to be silently downloaded using js/dom hacks. prefetching is a browser feature; users should be able to disable it easily. it is important that websites adopt <link> tag based prefetching instead of trying to roll-in silent downloading using various js/dom hacks. the <link> tag gives the browser the ability to know what sites are up to, and we can use this information to better prioritize document prefetching. the user preference to disable <link> tag prefetching may simply encourage websites to stick with js/dom hacks, and that would not be good for users. this is one reason why prefetching is enabled by default. which browse...
Performance fundamentals - Web Performance
he high scores list", etc. those work items are not on the critical path to painting the first frame. it seems obvious, but to reach a user-perceived startup event more quickly, the main "trick" is run only the code on the critical path. shorten the critical path by simplifying the scene. the web platform is highly dynamic. javascript is a dynamically-typed language, and the web platform allows loading code, html, css, images, and other resources dynamically. these features can be used to defer work that's off the critical path by loading unnecessary content "lazily" some time after startup. another problem that can delay startup is idle time, caused by waiting for responses to requests (like database loads). to avoid this problem, applications should issue requests as early as possible in sta...
...then when the data is needed later, hopefully it's already available and the application doesn't have to wait. note: for much more information on improving startup performance, read optimizing startup performance. ...
...ode are running slowly while the profiler runs. this is a bit more complex to use, but provides a lot of useful details. note: you can use these tools with the android browser by running firefox and enabling remote debugging. in particular, making dozens or hundreds of network requests takes longer in mobile browsers. rendering large images and css gradients can also take longer. simply downloading large files can take longer, even over a fast network, because mobile hardware is sometimes too slow to take advantage of all the available bandwidth. for useful general tips on mobile web performance, have a look at maximiliano firtman's mobile web high performance talk. testcases and submitting bugs if the firefox and chrome developer tools don't help you find a problem, or if they seem to in...
... maximiliano firtman's mobile web high performance talk. testcases and submitting bugs if the firefox and chrome developer tools don't help you find a problem, or if they seem to indicate that the web browser has caused the problem, try to provide a reduced test case that maximally isolates the problem. that often helps in diagnosing problems. see if you can reproduce the problem by saving and loading a static copy of an html page (including any images/stylesheets/scripts it embeds). if so, edit the static files to remove any private information, then send them to others for help (submit a bugzilla report, for example, or host it on a server and share the url). you should also share any profiling information you've collected using the tools listed above. ...
Structural overview of progressive web apps - Progressive web apps (PWAs)
when building your pwa. architecture of an app there are two main, different approaches to rendering a website — on the server or on the client. they both have their advantages and disadvantages, and you can mix the two approaches to some degree. server-side rendering (ssr) means a website is rendered on the server, so it offers quicker first load, but navigating between pages requires downloading new html content. it works great across browsers, but it suffers in terms of time navigating between pages and therefore general perceived performance — loading a page requires a new round trip to the server. client-side rendering (csr) allows the website to be updated in the browser almost instantly when navigating to different pages, but requires more of an initial download hit and extra ren...
...st popular approach is the app shell concept, which mixes ssr and csr in exactly the way described above, and in addition follows the "offline first" methodology which we will explain in detail in upcoming articles and use in our example application. there is also a new approach involving the streams api, which we'll mention briefly. the app shell concept the app shell concept is concerned with loading a minimal user interface and content as soon as possible, caching it so it's available offline for subsequent visits before then loading the remainder of the app's contents. that way, the next time someone visits the app from the device, the ui loads from the cache immediately and any new content is requested from the server (if it isn’t available in the cache already). this structure is fast,...
...it also allows the website to be accessible offline if the network connection is not available. we can control what is requested from the server and what is retrieved from the cache with a service worker, which will be explained in detail in the next article — for now let's focus on the structure itself. ...
... console.log('[service worker] install'); e.waituntil( caches.open(cachename).then(function(cache) { console.log('[service worker] caching all: app shell and content'); return cache.addall(contenttocache); }) ); }); with that done, we implement the service worker's fetch event handler; its job is to return the contents of the specified file, either from the cache or by loading it over the network (caching it upon doing so): self.addeventlistener('fetch', function(e) { e.respondwith( caches.match(e.request).then(function(r) { console.log('[service worker] fetching resource: '+e.request.url); return r || fetch(e.request).then(function(response) { return caches.open(cachename).then(function(cache) { console.log('[service worker] cachin...
Progressive web apps (PWAs)
s), discussing what they are and the advantages they offer over regular web apps.making pwas work offline with service workersin this article we took a simple look at how you can make your pwa work offline with service workers. be sure to check out our further documentation if you want to learn more about the concepts behind the service worker api and how to use it in more detail. ...
...er documentation if you want to learn more about the concepts behind the service worker api and how to use it in more detail. progressive loadingin previous articles we covered apis that help us make our js13kpwa example a progressive web app: service workers, web manifests, notifications and push. in this article we will go even further and improve the performance of the app by progressively loading its resources.progressive web app structurenow that we know the theory behind pwas, let's look at the recommended structure of an actual app. we will start with analyzing the js13kpwa application, why it is built that way, and what benefits it brings.pwa developer guidein the articles listed here, you'll find guides about every aspect of development specific to the greation of progressive web app...
...ontent is overhauled. core pwa guides the following guides show you what need to do to implement a pwa, by examining a simple example and showing you how all the pieces work. ...
... using the push api — learn the essentials behind the web push api. using the notifications api — web notifications in a nutshell. ...
/loader - Archive of obsolete content
re, unload } = components.utils.import('resource://gre/modules/commonjs/toolkit/loader.js'); it can be required as a commonjs module from a module loaded in the loader itself: let { loader, require, unload } = require('toolkit/loader'); what is it good for ? create somewhat standardized js environments that people doing non-browser js are familiar with. provide an environment for loading commonjs style modules, which makes it possible to consume lots of interesting code that has already been developed. secure each module in an isolated js sandbox and makes any capability imports explicit via calls to the require() function. create task specific loaders with restricted module access. provide unload hooks that may be used to undo changes made by anything loaded into it. instan...
...}), "net/utils": cu.import("resource:///modules/netutil.jsm", {}) } }); loader instances the loader produces instances that are nothing more than representations of the environment into which modules are loaded. it is intentionally made immutable and all its properties are just an implementation detail that no one should depend on, they may change at any point without any further notice. loading modules the commonjs specification defines the notion of a main module, which represents an entry point to a program. the loader module exposes a main() function that can be used to load a main module. all other modules will be loaded by this module or its dependencies: let { main, loader } = require('toolkit/loader'); let loader = loader(options); let program = main(loader, './main'); a modu...
...es. defaults to 1. options.version: version of js used, defaults to '1.8'. // load script from the given location to a given sandbox: evaluate(sandbox, 'resource://path/to/script.js') // evaluate `code` as if it was from `foo/bar.js`: evaluate(sandbox, 'foo/bar.js', { source: code, version: '1.7' // you could also use other options described above. }) require() as already mentioned in loading modules it's common to start execution by loading a main module. but sometimes you may want to prepare the environment using existing modules before doing that. in such cases you can create a requirer module instance and a version of require exposed to it with this function: let requirer = module(requirerid, requireruri); let require = require(loader, requirer); let boostrap = require(bootstrapi...
remote/parent - Archive of obsolete content
s can have other remote processes where untrusted content like webpages are loaded. each process can contain many frames. frame every dom page loaded as a part of the application is loaded in a content frame. this includes the content of every tab in an application like firefox and also some other ui elements. ...
... process can contain many frames. frame every dom page loaded as a part of the application is loaded in a content frame. this includes the content of every tab in an application like firefox and also some other ui elements. each frame loads in a process but sometimes the application may choose to switch from loading a tab in one process to another. in this case the frame for that tab changes. loading modules into the child process to load a module into the child process, use remoterequire(): const { remoterequire } = require("sdk/remote/parent"); remoterequire("./my-module.js", module); inter-process communication a module loaded into a different process cannot directly communicate or share state with the module that loaded it. instead, the two sides communicate using port objects like th...
...s that contains content frames. 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. parameters id : string the module to load. to use a relative path you must pass the module parameter. module : object the module to resolve the relative module id against. to resolve relative to the loading module, pass module here. properties processes a processes object. frames a frames object. processes the processes object lets you interact with the processes currently running. you can use it as a simple list of all running processes: const { processes } = require("sdk/remote/parent"); for (var p of processes) { console.log(p.isremote); } each element in this list is a process. there...
jpm - Archive of obsolete content
spaces, quote them: jpm run --binary-args '-url mzl.la -jsconsole' --debug run the add-on debugger attached to the add-on. -o --overload path rather than use the sdk modules built into firefox, use the modules found at path. if -o is specified and path is omitted, jpm looks for the jetpack_root environment variable and use its value as the path. see overloading the built-in modules for more information. -p --profile= profile by default, jpm uses a clean temporary firefox profile each time you call jpm run. use the --profile option to instruct jpm to launch firefox with an existing profile. the profile value may be a profile name or the path to the profile. see using profiles for more information. -v --verbose ...
... the above command only runs tests in files whose names contain "base64", and in those files only runs tests whose names contain "btoa". -o --overload path rather than use the sdk modules built into firefox, use the modules found at path. if -o is specified and path is omitted, jpm will look for the jetpack_root environment variable and use its value as the path. see overloading the built-in modules for more information. -p --profile profile by default, jpm uses a clean temporary firefox profile each time you call jpm run. use the --profile option to instruct jpm to launch firefox with an existing profile. the profile value may be a profile name or the path to the profile. see using profiles for more information. --stop-on-erro...
...or example: jpm watchpost --post-url http://localhost:8888/ note that the logging level defined for the console is different when you use this method, compared to the logging level used when an add-on is run using jpm run. this means that if you want to see the output from console.log() messages, you have to tweak a setting. see the documentation on logging levels for the details on this. overloading the built-in modules the sdk modules you use to implement your add-on are built into firefox. when you run or package an add-on using jpm run or jpm xpi, the add-on uses the versions of the modules in the version of firefox that hosts it. as an add-on developer, this is usually what you want. but if you're developing the sdk modules themselves, of course, it isn't. in this case you need to: ...
Code snippets - Archive of obsolete content
on of typed arrays in ecmascript allow us, in theory, to build full virtual machines in pure ecmascript. therefore, it is also possible, in theory, to use ecmascript for a smaller task: parsing exotic programming languages (i.e., creating compilers). this snippets shows a possible way to start from. ...
...e ecmascript for a smaller task: parsing exotic programming languages (i.e., creating compilers). this snippets shows a possible way to start from. ...
...efox/seamonkey) basic operations, such as page loading, with the tabbed browser, which is the heart of mozilla's browser applications cookies reading, writing, modifying, and removing cookies page loading code used to load pages, reload pages, and listen for page loads interaction between privileged and non-privileged code how to communicate from extensions to websites and vice-versa. ...
Intercepting Page Loads - Archive of obsolete content
some of the techniques presented here apply only to content loaded in the main browser area, while others detect content being loaded in other xul windows, or even detect xul content being loaded. also, the different techniques tap into different steps of the load process. which one you should use solely depends on your needs. we will start with the simplest one, which is also the most common to use. note: performance is very important when it comes to add-ons and page loads. ...
...l need to compare the page url with some string or regular expression: if (some_regular_expression.test(doc.defaultview.location.href)) you can access and modify the dom of the loaded page, just like you normally would for xul and html documents. you can't, however, easily cancel the page load. you can close the tab, redirect the tab to about:blank or another page, or tell the browser to stop loading this page, but in general you don't want to do this because it will be visible to the user and it will look like a bug. there are better ways to intercept page loads before any content is downloaded, and before the user sees anything in the tab. http observers another common way of detecting and intercepting loads is using http observer topics. this is how the tamper data extension and others d...
...olicy.shouldload() method is the only one in this interface that is really useful. it actually allows for cleaner-looking code than most of the previously seen solutions, because you get the content uri directly as an argument, and you indicate if the content should be loaded or not with the return value, which has well-defined possible values. the context parameter gives you access to the window loading the content. as with all other solutions, you need to be efficient, and a good way to do this is to filter out unneeded cases right from the start. shouldload is called for every load operation firefox tries to do, including images, scripts and xul documents. a good filter would look like this: shouldload : function(acontenttype, acontentlocation, arequestorigin, acontext, amimetypeguess, aextr...
Performance best practices in extensions - Archive of obsolete content
xtension has features that only work when the user has logged into a service, don't load the resources for those features until the user actually logs in. use javascript code modules you can create your own javascript code modules incorporating sets of features that are only needed under specific circumstances. ...
...se javascript code modules you can create your own javascript code modules incorporating sets of features that are only needed under specific circumstances. this makes it easy to load chunks of your extension on the fly as needed, instead of loading everything all at once. while javascript modules can be extremely useful, and provide significant performance benefits, they should be used wisely. loading modules incurs a small cost, so breaking code up to an unnecessary degree can be counter-productive. code should be modularized to the extent that doing so increases clarity, and loading of large or expensive chunks of code fragments can be significantly deferred. defer everything that you can most extensions have a load event listener in the main overlay that runs their startup functions. do a...
...:hover" like the plague. avoid dom mutation event listeners dom mutation event listeners are extremely expensive and, once added to a document even briefly, significantly harm its performance. as mutation events are officially deprecated, and there are many alternatives, they should be avoided at all costs. 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. see examples. definelazyservicegetter() defines a function on a specified object which acts as a getter for a service. the service isn't obtained until the first time it's used. look through the source for examples. many common services are already cached...
Using Dependent Libraries In Extension Components - Archive of obsolete content
the basic strategy of the stub is to dynamically load the dependent libraries, then load the component library and continue registration. ...
... to the glue libraries. /* * os x stubloader * original stubloader code by benjamin smedberg <benjamin@smedbergs.us> copyright (c) 2005 * adapted for os x by walter johnson <zinkyu@gmail.com>, sept. 2008 */ //include the stuff from mozilla glue that we need #include "nsilocalfile.h" #include "nsstringapi.h" #include "nscomptr.h" //include things from the mach-o libraries that we need for loading the libraries. #include <mach-o/loader.h> #include <mach-o/dyld.h> static char const *const kdependentlibraries[] = { // dependent1.dll on windows, libdependent1.so on linux, libdependent1.dylib on mac moz_dll_prefix "dependent1" moz_dll_suffix, moz_dll_prefix "dependent2" moz_dll_suffix, nsnull // note: if the dependent libs themselves depend on other libs, the subdependencies // sh...
... os x. instead, we use nsaddimage. nsaddimage(path.get(), nsaddimage_option_return_on_error | nsaddimage_option_with_searching | nsaddimage_option_match_filename_by_installname); // 1) we don't care if this failed! if you update your dependencies in your component, // but forget to remove a dependant library in the stubloader, then we don't want to // fail loading the component since the dependant library isn't required. // // 2) we are going to leak this library. we don't care about that either. // nsaddimage adds the image to the process. when the process terminates, the library // will be properly unloaded. } library->setnativeleafname(ns_literal_cstring(krealcomponent)); rv = library->getnativepath(path); if (ns_failed(rv)) return...
Creating a dynamic status bar extension - Archive of obsolete content
our extension will refresh the stock information display when the user clicks ...
...pened: window.addeventlistener("load", function(e) { stockwatcher.startup(); }, false); our new extension has two primary functions: startup() and refreshinformation(). the refreshinformation() function contains another function, called inforeceived(). the following sections will examine these one by one. startup() the startup() function is called when a new browser window is opened. ...
...js component responsible for communication with the server is a good idea for one of the future articles startup: function() { this.refreshinformation(); window.setinterval(this.refreshinformation, 10*60*1000); }, this starts by calling our refreshinformation() function, which is responsible for fetching and displaying stock ticker information in the status bar panel. we do this so that upon loading, the stock information is displayed as soon as possible. after doing that, we install an interval routine on the browser window by calling window.setinterval(). this configures our refreshinformation() routine to be called every 10 minutes (the time interval is specified in milliseconds). refreshinformation() the refreshinformation() function is called whenever we want to update the stock informa...
Plugin Architecture - Archive of obsolete content
ocument documents how trunk works, i.e. gecko 1.9. no released product uses this specific architecture. note: this document describes how things are, not necessarily how things should be. it is not set in stone. do not use this document for deciding what plugins can rely on. the described sequences are subject to change at any time. classes there are some classes involved in plugins: nsobjectloadingcontent embed, object and applet nodes inherit from that class, which provides services for loading various kinds of objects. it takes care of most of the work involved in loading the data and instantiating plugins. nsobjectframe the frame responsible for displaying plugins nsplugininstanceowner glue between plugin code (modules/plugin) and layout code (layout/generic). a refcounted object,...
...hat class, which provides services for loading various kinds of objects. it takes care of most of the work involved in loading the data and instantiating plugins. nsobjectframe the frame responsible for displaying plugins nsplugininstanceowner glue between plugin code (modules/plugin) and layout code (layout/generic). a refcounted object, contrary to nsobjectframe. note that while nsobjectloadingcontent also deals with images and documents, this document concentrates on plugins. 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, ...
...irectly 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. if a frame comes into existance independent of that, it tells the content node that it exists now (nsiobjectloadingcontent::hasnewframe). that function will post an event and when that fires, asks the frame to instantiate the plugin. (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/l...
Using the Editor from XUL - Archive of obsolete content
the <iframe> contents are then editable. note that the <editor> element is really just an <iframe> which takes over some of the task of creating the editor from javascript. editor creation so let's trace through the process of editor creation when bringing up the composer window. ...
...an find the relevant xul parts in editor.xul, the javascript parts in editor.js, and the xbl binding for the editor element in editor.xml. something, somewhere, tells mozilla to open the composer window. editor.xul is loaded. in editor.xul, the <window> tag has an onload handler: onload="editoronload()". that causes the editoronload() javascript function to get executed when the xul is done loading. the xul contains an <editor> tag, e.g.: <editor type="content-primary" id="content-frame" src="about:blank" flex="1"/> the attribute type="content-primary" identifies this as the window content element, i.e. that which you get from window._content. having an id attribute, id="content-frame", allows us to find this element with document.getelementbyid("content-frame"), and to style it fr...
...t part here. when the xul was parsed, the src attribute on the content frame was set to about:blank (our default 'blank page' url). we can't set that before xul parsing, so we have to force a load of the page we now want to edit. we get the url to load from the args element, then kick off the load: var url = document.getelementbyid("args").getattribute("value"); editorshell.loadurl(url); loading the document in the <iframe> of course happens asynchronously, so we need to know when we have a document that we can start editing. nseditorshell is able to observe the document load on the <iframe>, because it implements nsidocumentloaderobserver, and registered itself as a doc loader when it was assigned the content window. it thus gets callbacks for the start, progress, and end of the docu...
browser - Archive of obsolete content
y using window.content. content-targetable one browser among many for content. the content that is loaded inside the browser is not allowed to access the chrome above it. this is the preferred value for any browser element in an application, which will use multiple browsers of equal privileges, and is unselected at the moment. chrome (default behaviour): a browser, intended to be used for loading privileged content using a chrome:// uri. don't use for content from web, as this may cause serious security problems! properties accessibletype type: integer a value indicating the type of accessibility object for the element. cangoback type: boolean this read-only property is true if there is a page to go back to in the session history...
... contains the nsiwebnavigation object for the document. most of its methods are callable directly on the element itself, such as goback and goforward. it also contains the load constants used by reloadwithflags and loaduriwithflags. webprogress type: nsiwebprogress this read-only property contains an nsiwebprogress object which is used to monitor the progress of a document loading. methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(),...
...ignoring the proxy server. load_flags_charset_change: this flag is used if the document needs to be reloaded because the character set changed. removeprogresslistener( listener ) return type: no return value remove a nsiwebprogresslistener from the browser. stop() return type: no return value equivalent to pressing the stop button, this method stops the currently loading document. swapdocshells( otherbrowser ) return type: no return value swaps the content, history and current state of this browser with another browser. during the swap, pagehide and pageshow events are fired on both browsers. this method can be used to move browser between windows or tear off a browser into a new window. note: both browsers must be either standalone brow...
Initialize the framework - Game development
this tutorial uses phaser v2 — it won't work with the current version on phaser (v3). the v2 library is still available on the phaser download page, below the links for the v3 download. go to the phaser download page. choose an option that suits you best — i...
...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. this tutorial uses phaser v2 — it won't work with the current version on phaser (v3). the v2 library is still available on the phaser download page, below the links for the v3 download. go to the phaser download page. choose an option that suits you best — i would recommend the min.js option as it keeps the source code smaller, ...
...ailable in the browser, falling back to canvas 2d if not. the id of the <canvas> to use for rendering if one already exists on the page (we've specified null because we want phaser to create its own.) the names to use for phaser's three key functions that load and start the game, and update the game loop on every frame; we will use the same names to keep it clean. preload takes care of preloading the assets create is executed once when everything is loaded and ready update is executed on every frame. compare your code here's the full source code of the first lesson, running live in a jsfiddle: next steps now we've set up the basic html and learned a bit about phaser initialization, let's continue to the second lesson and learn about scaling. « previousnext » ...
Index - MDN Web Docs Glossary: Definitions of Web-related terms
e has happened and web fonts have loaded. it is when the answer to "is it useful?" becomes "yes", upon first meaningful paint completion. 148 first contentful paint glossary, performance, reference, web performance first contentful paint (fcp) is when the browser renders the first bit of content from the dom, providing the first feedback to the user that the page is actually loading. the question "is it happening?" is "yes" when the first contentful paint completes. 149 first input delay glossary, reference, web performance first input delay (fid) measures the time from when a user first interacts with your site (i.e. when they click a link, tap on a button, or use a custom, javascript-powered control) to the time when the browser is actually able to res...
... to reach its destination. 248 layout viewport codingscripting, glossary, layout, layout viewport, viewport the layout viewport is the viewport into which the browser draws a web page. essentially, it represents what is available to be seen, while the visual viewport represents what is currently visible on the user's display device. 249 lazy load glossary, lazy loading, reference, web performance lazy loading is a strategy that delays the loading of some assets (e.g., images) until they are needed by the user based on the user's activity and navigation pattern; typically, these assets are only loaded when they are scrolled into view. 250 ligature css, design, glossary a ligature is a joining of two characters into one shape. for exam...
...load, measured from navigation start to the start of the load event 314 page prediction glossary, security, web performance, page prediction page prediction is a browser feature or script which, when enabled, tells the browser to download resources the user is likely to visit before the user requests the content. page prediction improves performance by enabling almost instant loading of predicted content. however, page prediction may also download content a user does not seek. 315 parameter codingscripting, glossary, javascript a parameter is a named variable passed into a function. parameter variables are used to import arguments into functions. 316 parent object codingscripting, glossary, needscontent the object to which a given pro...
Legacy layout methods - Learn web development
{ width: 220px; } /* and so on... */ .col.span4 { width: 300px; } .col.span5 { width: 380px; } .col.span6 { width: 460px; } .col.span7 { width: 540px; } .col.span8 { width: 620px; } .col.span9 { width: 700px; } .col.span10 { width: 780px; } .col.span11 { width: 860px; } .col.span12 { width: 940px; } with these classes created we can now lay out different width columns on the grid. try saving and loading the page in your browser to see the effects. note: if you are having trouble getting the above example to work, try comparing it against our finished version on github (see it running live also). try modifying the classes on your elements or even adding and removing some containers, to see how you can vary the layout. for example, you could make the second row look like this: <div class="row...
...gin-left: 10.41666666%; } you can now add this class to any container you want to leave a one column wide empty space on the left hand side of it. for example, if you have this in your html: <div class="col span6">14</div> try replacing it with <div class="col span5 offset-by-one">14</div> note: notice that you need to reduce the number of columns spanned, to make room for the offset! try loading and refreshing to see the difference, or check out our fluid-grid-offset.html example (see it running live also). the finished example should look like this: note: as an extra exercise, can you implement an offset-by-two class? floated grid limitations when using a system like this you do need to take care that your total widths add up correctly, and that you don’t include elements in a ...
... note: if you are having trouble getting this example to work, try comparing it to our html-skeleton-finished.html file (see it running live also). if you look in the skeleton.css file you can see how this works. for example, skeleton has the following defined to style elements with “three columns” classes added to them. .three.columns { width: 22%; }...
What software do I need to build a website? - Learn web development
prerequisites: you should already know the difference between webpages, websites, web servers, and search engines. objective: learn which software components you need if you want to edit, upload, or view a website. summary you can download most of the programs you need for web development for free. we'll provide a few links in this article. ...
...you can buy space on a server from various providers (see how much does it cost to do something on the web?). once you settle on which provider to use, the provider will email you the access information, usually in the form of an sftp url, username, password, and other informat...
...ur web server. you can buy space on a server from various providers (see how much does it cost to do something on the web?). once you settle on which provider to use, the provider will email you the access information, usually in the form of an sftp url, username, password, and other information needed to connect to their server. bear in mind that (s)ftp is now somewhat old-fashioned, and other uploading systems are starting to become popular, such as rsync and git/github. note: ftp is inherently insecure. you should make sure your hosting provider allows use of a secure connection, e.g. sftp or rsync over ssh. uploading files to a web server is a very important step while creating a website, so we cover it in detail in a separate article. for now, here's a short list of free basic (s)ftp cli...
Index - Learn web development
ers throughout most of the learning area, we tell you to just open your examples directly in a browser — this can be done by double clicking the html file, dragging and dropping it into the browser window, or choosing file > open... and navigating to the html file. there are many ways to achieve this. 21 how do you upload your files to a web server? beginner, ftp, github, uploading, webmechanics, hosting, rsync, sftp if you have built a simple web page (see html basics for an example), you will probably want to put it online, on a web server. in this article we'll discuss how to do that, using various available options such as sftp clients, rsync and github. 22 how does the internet work? beginner, tutorial, webmechanics the internet is the backbo...
...nd, contains several active regions (called "hotspots") that each link to a different resource. 254 define terms with html beginner, guide, html, learn when you need a term defined, you probably go straight to a dictionary or glossary. dictionaries and glossaries formally associate keywords with one or more descriptions, as in this case: 255 tips for authoring fast-loading html pages advanced, guide, html, needsupdate, performance, web, web performance these tips are based on common knowledge and experimentation. 256 use javascript within a webpage beginner, html, javascript, openpractices javascript is a programming language mostly used client-side to make webpages interactive. you can create amazing webpages without javascript, but ...
...ving blocking css. 348 what is web performance? beginner, introduction, learn, performance, reference, tutorial, web performance web performance is all about making web sites fast, including making slow processes seem fast. does the site load quickly, allow the user to start interacting with it quickly, and offer reassuring feedback if something is taking time to load (e.g. a loading spinner)? are scrolling and animations smooth? this article provides a brief introduction to objective, measureable web performance*, looking at what technologies, techniques, and tools are involved in web optimization. ...
Routing in Ember - Learn web development
location = config.locationtype; rooturl = config.rooturl; } router.map(function() { this.route('completed'); this.route('active'); }); the highlighted lines were added when the 2nd and 3rd commands above were run. router.js behaves as a "sitemap" for developers to be able to quickly see how the entire app is structured. it also tells ember how to interact with your route, such as when loading arbitrary data, handling errors while loading that data, or interpreting dynamic segments of the url. since our data is static, we won't get to any of those fancy features, but we'll still make sure that the route provides the minimally required data to view a page. creating the "index" route did not add a route definition line to router.js, because like with url navigation and javascript module...
... to adjust our old way of rendering the todolist app, we'll first need to replace the todolist component invocation from the application template with an {{outlet}} call, which means "any sub-route will be rendered in place here". ...
...l todos, and a getter that returns incomplete todos. the getter we are missing is one to return just the completed todos. add the following below the existing getters: get completed() { return this.todos.filter(todo => todo.iscompleted); } models now we need to add models to our route javascript files to allow us to easily return specific data sets to display in those models. model is a data loading lifecycle hook. for todomvc, the capabilities of model aren't that important to us; you can find more information in the ember model guide if you want to dig deeper. we also provide access to the service, like we did for the components. the index route model first of all, update todomvc/app/routes/index.js so it looks as follows: import route from '@ember/routing/route'; import { inject as ser...
Package management basics - Learn web development
your own packages. in theory you may not need a package manager and you could manually download and store your project dependencies, but a package manager will seamlessly handle installing and uninstalling packages. if you didn't use one, you'd have to manually handle: finding all the correct package javascript files. checking them to make sure they don't have any known vulnerabilities. downloading them and putting them in the correct locations in your project. writing the code to include the package(s) in your application (this tends to be done using javascript modules, another subject that is worth reading up on and understanding). doing the same thing for all of the packages' sub-dependencies, of which there could be tens, or hundreds. removing all the files again if you want to remov...
...rectory (under node_modules). building our code for production however, this code is not ready for production. most build tooling systems will have a "development mode" and a "production mode". the important difference is that a lot of the helpful features you will use in development are not needed in the final site, so will be stripped out for production, e.g. "hot module replacement", "live reloading", and "uncompressed and commented source code". though far from exhaustive, these are some of the common web development features that are very helpful at the development stage, but are not very useful in production. in production, they will just bloat your site. now stop the previous parcel command (using ctrl + c). we can now prepare our bare bones example site for an imaginary deployment. pa...
...n, but lets look at the others. the list will grow over time, but at time of writing, the following main package managers are available: npm at npmjs.org pnpm at pnpm.js.org yarn at yarnpkg.com npm and pnpm are similar from a command line point of view — in fact pnpm aims to have full parity over the argument options that npm offers. it differs in that it uses a different method for downloading and storing the packages on your computer, aiming to reduce the overall disk space required. where npm is shown in the examples below, pnpm can be swapped in and the command will work. yarn is often thought to be quicker than npm in terms of installation process (though your mileage may vary). this is important to developers because there can be a significant amount of time wasted on waiting fo...
Mozilla accessibility architecture
or nsiframe::getaccessible(), new accessibles are created by calling back to the accessibility service, and using a specific method for creating each type of accessible. for example, nshtmltablecellframe::getaccessible() will eventually call nsiaccessibilityservice::createhtmltablecellaccessible(), which uses |new nshtmltablecellaccessible(domnode, weakpresshell); special exception: traversal overloading in some cases the necessary accessible children are not in the dom subtree for a node. this is the case for: nshtmlimageaccessible: in msaa an image accessible can have accessible children if it has an image map. the children are the image map areas, which are in a different part of the dom tree. nshtmlcomboboxaccessible: an html combo box doesn't have a dom node or anonymous content for its...
...ology client. however, on windows there are crash issues with the automatic windows-generated versions of event_create and event_destroy, so the msaa client cannot listen to them. we fire the safer event_reorder in their place.. to see what parts of the accessibility cache need to be invalidated. however, we are careful not to do this work for mutation events fired because the document is still loading. currently (as of may 2003), we do not yet use domattrmodied to listen to attribute changes on a node. we need to listen to some attribute changes because they might signal the need to invalidate parts of our cache; for example, if the name or href attribute on an anchor element changes, or the usemap attribute of an img changes. these cases are not very likely, but we should try to think of rea...
...ide it to do their own special initialization. if they do, they must also call their parent class' init() method when finished. nsaccessnode::shutdown() shutdown() is used when the dom node for the given nsaccessnode/nsaccessible no longer exists. it can be called in a number of ways: in the destructor for nswindow: when the document is destroyed, its window also goes away. if there is a newly loading document, it has its own separate window which has already been created and rendered into. in fact, for about a second two nsdocaccessible's exist for the same screen space - one for the old document about to be destroyed, and one for the loading document which hasn't been displayed yet. side note: we do not fire the event indicating the new document is ready, until the new document is displayed.
Embedding API for Accessibility
m factors on a content window. a zoom factor of 1.0 represents 100%, or normal zoom. for double-sized text, use nsidomwindow::settextzoom(2.0); using accessibility preferences there are a number of prefs related to accessibility. for the most part, an automatic reframe is performed when one of these prefs is changed. a reframe fixes the appearance of the page to match the new prefs, without reloading the document over the network. be aware that in debug builds, this can cause a great number of assertions (bug 71598) to use prefs in embedding, use something like the following code: #include "nsipref.h"; nsresult rv; nscomptr<nsipref> prefs(do_getservice(ns_pref_contractid, &rv)); prefs->setboolpref("bool.pref.name", pr_true /* or pr_false */); prefs->setintpref("int.pref.name", newvalue);...
...ex color value */); setcharpref("browser.display.background_color", "#abcdef" /* hex color value */); setboolpref("browser.display.use_system_colors", boolsystemcolors); setboolpref("browser.display.use_document_colors", booluseauthorcolors); /* setting use_document_colors also stops background images from loading */ moz 0.8 link appearance setcharpref("browser.anchor_color", "#abcdef" /* hex color value */); setcharpref("browser.visited_color", "#abcdef" /* hex color value */); setboolpref("browser.underline_anchors", boolunderlinelinks); moz 0.8 focus...
...ference, to allow configuration of sound files to go with each type of content. the audio file could be a clip of a human voice saying "you've got video" or even a simple beep. how we expose this through the user interface is another matter. accepting special content on an instance basis after being notified of special content, the user needs to be able to select specific unloaded content for loading. one way of doing this is to build up the nsiwebbrowseraccessible interface, so that there is a method to force loading each type of content just for the current page in the current session. open issue: accessibility settings per url a powerful possibility is that we design an interface for setting certain preferences based on the url. if we can find a clean way to present it to the user, t...
Creating reftest-based unit tests
tests/simpletest/windowsnapshot.js. register them in the chrome package in layout/tools/reftest/jar.mn, and reference the chrome uris in the manifest file (see an example). testing invalidation testing that a document displays correctly once it has loaded is only one part of testing rendering. another part is testing invalidation - testing that when a document is changed after it has finished loading and displaying, that the browser correctly "invalidates" the parts of the screen that should change so that the screen displays the correct output the next time it is repainted. invalidation tests check both that the internal state of the document has been updated correctly, and that the browser then correctly invalidates and repaints the appropriate parts of the screen. in order to test invalid...
... that should change so that the screen displays the correct output the next time it is repainted. invalidation tests check both that the internal state of the document has been updated correctly, and that the browser then correctly invalidates and repaints the appropriate parts of the screen. in order to test invalidation it is important that invalidation tests let the document completely finish loading and displaying before making the changes for which invalidation and repainting is to be tested. making the changes before the document has completely finished loading and painting would mean that the test may not actually test the browser's invalidation logic, since the changed parts of the document may end up displaying correctly purely due to a pending post-load paint. to write an invalidation...
...he test may not actually test the browser's invalidation logic, since the changed parts of the document may end up displaying correctly purely due to a pending post-load paint. to write an invalidation reftest requires three extra steps. first you need to add class="reftest-wait" to the root element in the test to tell the reftest framework not to check the rendering as soon as the test finishes loading and moving on to the next test. next you need to add a listener for the 'mozreftestinvalidate' event, and only make the changes you want to test invalidation for after that event has fired. third, you need to remove 'reftest-wait' from the root element's 'class' attribute to tell the reftest framework that the test is now ready to have its rendering tested. the reason for using the 'mozreftestin...
Browser API
upport the requirement of a browser <iframe>, the htmliframeelement dom interface has been extended with new methods that give the <iframe> some super powers. navigation methods the following navigation methods allow navigation through the browsing history of the <iframe>. they are necessary to be able to implement back, forward, stop, and reload buttons. htmliframeelement.reload() allows reloading of the <iframe> element content. htmliframeelement.stop() allows stopping of the <iframe>'s content loading. htmliframeelement.getcangoback() indicates whether it's possible to navigate backwards. htmliframeelement.goback() changes the location of the <iframe> for the previous location in its browsing history. htmliframeelement.getcangoforward() indicates whether it's possible to navigate...
...ontent (see htmliframeelement search methods.) mozbrowserfirstpaint sent when the <iframe> paints content for the first time (this doesn't include the initial paint from about:blank.) mozbrowsericonchange sent when a new icon (e.g. <link rel="icon"> or <link rel="apple-touch-icon">) is available in the browser <iframe>'s content. mozbrowserloadend sent when the browser <iframe> has finished loading all its assets. mozbrowserloadstart sent when the browser <iframe> starts to load a new page. mozbrowserlocationchange sent when a browser <iframe>'s location changes. mozbrowsermanifestchange sent when a the path to the app manifest changes, in the case of a browser <iframe> with an open web app embedded in it. mozbrowsermetachange sent when a <meta> elelment is added to, removed from or...
... user issuing a command to open a link target in a new tab (for example ctrl/cmd + click.) mozbrowserresize sent when the browser <iframe>'s window size has changed. mozbrowserscroll sent when the browser <iframe> content scrolls. mozbrowserscrollareachanged sent when the available scrolling area in the browser <iframe> changes. this can occur on resize and when the page size changes (while loading for example.) mozbrowserscrollviewchange sent when asynchronous scrolling (i.e. apcz) starts or stops. mozbrowsersecuritychange sent when the ssl state changes within a browser <iframe>. mozbrowserselectionstatechanged sent when the text selected inside the browser <iframe> content changes. note that this is obsolete, and newer implementations use mozbrowsercaretstatechanged instead. mozbr...
HTTP Cache
concurrent read/write. concurrent read and write important difference in behavior from the old cache: the cache now supports reading a cache entry data while it is still being written by the first consumer - the writer. this can only be engaged for resumable responses that (bug 960902) don't need revalidation. reason is that when the writer is interrupted (by e.g. external canceling of the loading channel) concurrent readers would not be able to reach the remaning unread content. this could be improved by keeping the network load running and being stored to the cache entry even after the writing channel has been canceled. when the writer is interrupted, the first concurrent reader in line does a range request for the rest of the data - and becomes that way a new writer. the rest of the...
...extinfo passed to a *storage method on nsicachestorageservice. invoking open callbacks cacheentry, implementing the nsicacheentry interface, is responsible for managing the cache entry internal state and to properly invoke oncacheentrycheck and oncacheentryavaiable callbacks to all callers of nsicachestorage.asyncopenuri. keeps a fifo of all openers. keeps its internal state like notloaded, loading, empty, writing, ready, revalidating. keeps the number of consumers keeping a reference to it. refers a cachefile object that holds actual data and meta data and, when told to, persists it to the disk. the openers fifo is an array of cacheentry::callback objects. cacheentry::callback keeps a strong reference to the opener plus the opening flags. nsicachestorage.asyncopenuri forwards to cache...
...chestorageservice hash tables up if not found: create a new one, add it to the proper hash table and set its state to notloaded consumer reference ++ call to cacheentry::asyncopen consumer reference -- cacheentry::asyncopen (entry atomic): the opener is added to fifo, consumer reference ++ (dropped back after an opener is removed from the fifo) state == notloaded: state = loading when open_truncate flag was used: cachefile is created as 'new', state = empty otherwise: cachefile is created and load on it started cacheentry::onfileready notification is now expected state == loading: just do nothing and exit call to cacheentry::invokecallbacks cacheentry::invokecallbacks (entry atomic): called on: a new opene...
InstallListener
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. void onnewinstall( in addoninstall install ) parameters install the addoninstall representing the install ondownloadstarted() called when downloading begins for an add-on install. only called for add-ons that need to be downloaded. a listener may return false to cancel the download. void ondownloadstarted( in addoninstall install ) parameters install the addoninstall representing the install ondownloadprogress() called as data is received during a download. check the progress property for the amount of data downloaded and the maxpro...
... ondownloadprogress() called as data is received during a download. check the progress property for the amount of data downloaded and the maxprogress property for the total data expected. a listener may return false to cancel the download. void ondownloadprogress( in addoninstall install ) parameters install the addoninstall representing the install ondownloadended() called when downloading completes successfully for an add-on install. only called for add-ons that need to be downloaded. void ondownloadended( in addoninstall install ) parameters install the addoninstall representing the install ondownloadcancelled() called when downloading is cancelled. only called for add-ons that need to be downloaded. void ondownloadcancelled( in addoninstall install ) parameters ...
...only called for add-ons that need to be downloaded. void ondownloadfailed( in addoninstall install ) parameters install the addoninstall representing the install oninstallstarted() called when installation of an add-on begins. ...
Examples
lue: " + avalue); }, function onreject(areason) { console.log("rejected with this reason: " + areason); }); // unexpected errors should always be reported at the end of a promise chain. newpromise.then(null, components.utils.reporterror); note: more examples for consuming promises are available in the promise object documentation. make user defined promise return after multiple images finish loading (promise.all and promise.defer) this example shows how to use promise.all to wait to create multiple promises with promise.defer() and return at the end of it. components.utils.import("resource://gre/modules/promise.jsm"); var mypromise = myuserdefinedpromise(); mypromise.then( function(asuccessreason) { alert('mypromise was succesful and reason was = "' + asuccessreason + '"'); }, f...
...change the array...
... loadthisimagepromise.reject('image loaded but it has 0 width at path = "' + path + '" the naturalwidth was 0'); } } myimage.onerror = function(e) { loadthisimagepromise.reject('an error occured while loading path = "' + path + '". the error = ' + uneval(e)); } myimage.onabort = function(e) { loadthisimagepromise.reject('image load was aborted loading path = "' + path + '".'); } myimage.src = path; }); return promise.all(mysubpromises); } catch(ex) { return promise.reject(ex); } } to test and see what happens when you get an error. change the array in the code above. change this line: var imagepaths = ['http://www.mozilla.org/media/img/firefox/favicon.png', 'https://developer.cdn.mozilla.net/media/redesig...
Using JSS
Mozilla › Projects › NSS › JSS › Using JSS
processor-specific optimized big-number arithmetic library. not present on all platforms. more information... fort fortezza support. optional swft pkcs #11 module implementing fortezza in software. optional. if you built jss from source, you have these libraries in the mozilla/dist/<platform>/lib directory of your build tree. if you are downloading binaries, get them from the binary release locations in the above table. you need to select the right version of the components, based on the version of jss you are using. generally, it is safe to use a later version of a component than what jss was tested with. for example, although jss 4.2 was tested with nss 3.11. component versions jss version component...
... nss 3.4.2 jss 3.1.1 nspr 4.1.2 nss 3.3.1 jss 3.1 nspr 4.1.2 nss 3.3 jss 3.0 nspr 3.5.1 jss shared library the jss shared library is jss4.dll (windows) or libjss4.so (unix). if you built jss from source, it is in mozilla/dist/<platform>/lib. if you are downloading binaries, get it from http://ftp.mozilla.org/pub/mozilla.org/security/jss/releases/. jss classes if you built jss from source, the compiled jss classes are in mozilla/dist/classes[_dbg]. you can put this directory in your classpath to run applications locally; or, you can package the class files into a jar file for easier distribution: cd mozilla/dist/classes[_dbg] zip -r ../jss42.j...
...p://ftp.mozilla.org/pub/mozilla.org/security/jss/releases/. jss classes if you built jss from source, the compiled jss classes are in mozilla/dist/classes[_dbg]. you can put this directory in your classpath to run applications locally; or, you can package the class files into a jar file for easier distribution: cd mozilla/dist/classes[_dbg] zip -r ../jss42.jar . if you are downloading binaries, get jss42.jar from http://ftp.mozilla.org/pub/mozilla.org/security/jss/releases/. setup your runtime environment you need to set some environment variables before building and running java applications with jss. classpath include the path containing the jss classes you built, or the path to jss42.jar. (the path to jss34.jar ends with the string "/jss42.jar". it is not ...
Using the Places favicon service
n service, you should do something like this: var faviconservice = components.classes["@mozilla.org/browser/favicon-service;1"] .getservice(components.interfaces.nsifaviconservice); caching the favicon service stores an expiration time for each favicon. ...
... var faviconservice = components.classes["@mozilla.org/browser/favicon-service;1"] .getservice(components.interfaces.nsifaviconservice); caching the favicon service stores an expiration time for each favicon. this time is used by nsifaviconservice.setandloadfaviconforpage() to determine if the data is fresh or needs reloading from the server. if you are manually loading favicon data, you can specify the expiration time yourself. otherwise, nsifaviconservice.setandloadfaviconforpage() will use the default expiration time. currently, the default expiration time is set to one day in the future. this makes sure that we aren't obsessively reloading favicons into the database for every page viewed, but also that changes in the favicon will be picked up quickly. most o...
...he places annotation service. you should always use nsifaviconservice.getfaviconimageforpage() to get the favicon for a page. if the page has no favicon, or we have never heard of the page, this function will return a "chrome:" uri of the default favicon. this allows efficient caching, since the default favicon will probably be cached in its decoded form by the image library. if there is an error loading the favicon for an annotation uri, the default favicon data will be returned by the annotation service's protocol handler. however, since the uri will be different from the default favicon, the decoded image will not be cached by the image library. see also nsifaviconservice ...
Bundling multiple binary components
he more likely case is that the component uses "unfrozen" interfaces and those interfaces can change between gecko versions. this can create a difficult situation for extension developers trying to support multiple gecko versions (firefox 2 and 3, for example). possible solutions this article covers two possible ways to make binary components support multiple version of gecko: dynamic method loading stub loader dynamic method loading the idea with this approach is to figure out all the methods imported from gecko and dynamically load the methods. create small wrappers for calling the methods, as you may need to thunk parameters depending on how much has changed between gecko versions. this means using something like loadlibrary / getprocaddress / freelibrary on windows. actually, nspr ha...
...for calling the methods, as you may need to thunk parameters depending on how much has changed between gecko versions. this means using something like loadlibrary / getprocaddress / freelibrary on windows. actually, nspr has portable versions of those features that work across platforms. 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. the costs get higher if you have many methods that need to be loaded. stub loader this approach involves using a stub loader component. the stub component is an xpcom component itself and when registered by xpcom, the code would sniff the runtime version and operating system then the stub load the appropriate "real" xpcom component for the current configur...
...e real components are manually loaded and registered using the stub ("krealcomponent" in the sample). this approach uses one binary component for each version of gecko and platform, plus the stub loader component therefore, to support 2 gecko versions on three platforms, you need seven components (6 real components + 1 stub). on the other hand, this approach is much more simple than the dynamic loading approach. the stub component can be either binary or javascript, but it is far easier in javascript is cross-platform and does not have compile- or load- time compatibility problems. the gears project contains an example of a javascript-based stub loader. ...
nsIApplicationUpdateService
toolkit/mozapps/update/nsiupdateservice.idlscriptable this interface describes a global application service that handles performing background update checks. it also provides utilities for selecting and downloading update patches. 1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview void adddownloadlistener(in nsirequestobserver listener); astring downloadupdate(in nsiupdate update, in boolean background); void pausedownload(); void removedownloadlistener(in nsirequestobserver listener); nsiupdate selectupdate([array, size_is(updatecount)] in nsiupdate updates, in unsigned long updatecount); attributes attribute type description backgroundchecker nsi...
...e service can check for updates. application updates might be disabled by the application and the platform the application is running on. read only. canupdate boolean true if the update service is able to download and install updates. this depends on whether or not the current user has the necessary access privileges for the install directory. read only. obsolete since gecko 1.9.1.7pre isdownloading boolean true if a download is in progress, otherwise false. read only. methods adddownloadlistener() adds a listener that receives progress and state information about the update that is currently being downloaded. this information is most commonly used to update a user interface that informs the user as to the status of an update. void adddownloadlistener( in nsirequestobserver listener ); ...
...ded. this information is most commonly used to update a user interface that informs the user as to the status of an update. void adddownloadlistener( in nsirequestobserver listener ); parameters listener an object implementing nsirequestobserver and optionally nsiprogresseventsink that will be notified of state and progress information as the update is downloaded. downloadupdate() starts downloading a software update. astring downloadupdate( in nsiupdate update, in boolean background ); parameters update an nsiupdate object indicating the update to download. background true to download the update in the background or false to download it in the foreground. return value a string indicating the status of the update upon return: "downloading" the update is being downloaded. "pending...
nsIFaviconService
in the favicon service. can be null. setandloadfaviconforpage() obsolete since gecko 22.0 (firefox 22.0 / thunderbird 22.0 / seamonkey 2.19) note: this method was removed in gecko 22.0. you should use the new async api moziasyncfavicons.setandfetchfaviconforpage() instead. this method is same as setfaviconurlforpage() except that this also attempts to set the data by loading the favicon uri. 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. if the icon data already exists, we won't normally try to re-load the icon from the net (or more likely the cache). if the icon is in the failed favicon cache we won't do anything. use aforcereload to force a reload...
... not let the message loop run between calls or your icon may get deleted. it is best to set the favicon data, and then associate it with a page. this will make the notifications more efficient since the icon will already have data when the set favicon observer messages goes out. the expiration time is stored. this will be used if you call setandloadfaviconforpage() to see whether the data needs reloading. do not use this function for "chrome:" icon urls. you should reference the chrome image yourself. the getfaviconlinkforicon() and getfaviconforpage() will ignore any associated data if the favicon uri is "chrome:" and just return the same chrome uri. this function does not send out notifications that the data has changed. potentially, many pages could be referencing the favicon and they could be...
...ble favicon size, the entire operation fails and the favicon isn't saved. it is best to set the favicon data, and then associate it with a page. this will make the notifications more efficient since the icon will already have data when the set favicon observer messages goes out. the expiration time is stored. this will be used if you call setandloadfaviconforpage() to see whether the data needs reloading. do not use this function for "chrome:" icon urls. you should reference the chrome image yourself. the getfaviconlinkforicon() and getfaviconforpage() will ignore any associated data if the favicon uri is "chrome:" and just return the same chrome uri. this function does not send out notifications that the data has changed. potentially, many pages could be referencing the favicon and they could be...
nsIMsgFolder
the nsimsgfolder interface is used to interact with folders in thunderbird. this page is out of date. check //github.com/realityripple/uxp/blob/master/mailnews/base/public/nsimsgfolder.idl for the newer methods (esp. isspecialfolder and such). ...
... the nsimsgfolder interface is used to interact with folders in thunderbird. this page is out of date. check //github.com/realityripple/uxp/blob/master/mailnews/base/public/nsimsgfolder.idl for the newer methods (esp. isspecialfolder and such). ...
...re is new mail. nsmsgdispositionstate_none -1 nsmsgdispositionstate_replied 0 nsmsgdispositionstate_forwarded 1 allmessagecountnotifications 0 turn notifications on/off for various notification types. currently only supporting allmessagecountnotifications which refers to both total and unread message counts. methods startfolderloading() void startfolderloading(); endfolderloading() void endfolderloading(); updatefolder() get new headers for the database. void updatefolder(nsimsgwindow awindow); getfilterlist() get the filter list on folder's server (or in the case of news, the filter list for this newsgroup). nsimsgfilterlist getfilterlist(nsimsgwindow msgwindow); setfilterlist() void setfilterlist(in nsims...
nsIProtocolHandler
p to the application to decide what origins should have such access. protocols like file that point to local data should set this flag. uri_loadable_by_subsumers 1<<14 the uris for this protocol can be loaded only by callers with a principal that subsumes this uri. for example, privileged code and websites that are same origin as this uri. uri_non_persistable 1<<10 loading channels from this protocol has side-effects that make it unsuitable for saving to a local file. uri_does_not_return_data 1<<11 channels using this protocol never call ondataavailable() on the listener passed to asyncopen(), and therefore do not return any usable data. uri_is_local_resource 1<<12 uris for this protocol are considered to be local resources.
...s being requested. return value return true if the override is approved; otherwise, return false. newchannel() constructs a new channel from the given uri for this protocol handler. nsichannel newchannel( in nsiuri auri ); parameters auri the uri for which to construct a channel. return value return the newly constructed channel. newuri() makes a uri object that is suitable for loading by this protocol, where the uri string is given as an utf-8 string. the caller may provide the charset from which the uri string originated, so that the uri string can be translated back to that charset (if necessary) before communicating with, for example, the origin server of the uri string. (many servers do not support utf-8 iris at the present time, so we must be careful about tracking the na...
...unicating this uri to an origin server. if this is null, then utf-8 encoding is assumed and no character transformation is not performed. abaseuri if null, aspec must specify an absolute uri. otherwise, aspec may be resolved relative to abaseuri, depending on the protocol. if the protocol has no concept of relative uris, this parameter is ignored. return value the new uri object suitable for loading using the protocol. see also nsiproxiedprotocolhandler adding a new protocol to mozilla writing a firefox protocol handler custom about: urls - similar to adding new protocol but adding onto the existing about: protocol ...
nsIWebBrowserPersist
in nsichannel achannel, in nsisupports afile ); parameters achannel the nsichannel to save to a file. afile target local file. this may be a nsilocalfile object or an nsiuri object with a file scheme. savedocument() save the specified dom document to file and optionally all linked files (for example images, css, js & subframes). do not call this method until the document has finished loading! void savedocument( in nsidomdocument adocument, in nsisupports afile, in nsisupports adatapath, in string aoutputcontenttype, in unsigned long aencodingflags, in unsigned long awrapcolumn ); parameters adocument document to save to file. some implementations of this interface may also support nsnull to imply the currently loaded document. afile target local file. this may be...
...rts adatapath, in string aoutputcontenttype, in unsigned long aencodingflags, in unsigned long awrapcolumn ); parameters adocument document to save to file. some implementations of this interface may also support nsnull to imply the currently loaded document. afile target local file. this may be a nsilocalfile object or an nsiuri object with a file scheme or a scheme that supports uploading (for example ftp). adatapath path to directory where uris linked to the document are saved or nsnull if no linked uris should be saved. this may be a nsilocalfile object or an nsiuri object with a file scheme. aoutputcontenttype the desired mime type format to save the document and all sub-documents into or nsnull to use the default behavior. aencodingflags flags to pass to the encoder. aw...
...rrer uri to pass with an http request or nsnull. areferrerpolicy the referrer policy to use for the request, taken from nsihttpchannel. apostdata post data to pass with an http request or nsnull. aextraheaders additional headers to supply with an http request or nsnull. afile target file. this may be a nsilocalfile object or an nsiuri object with a file scheme or a scheme that supports uploading (for example ftp). aprivacycontext a context derived from a relevant window or document (eg. the window containing a link being saved) via a docshell that qis to nsiloadcontext. used to ensure that privacy-sensitive operations (such as saving a uri related to a private browsing session) do not leak any information (eg. cookies, permanent cache, etc.) null must only be passed in the event that n...
Troubleshooting XPCOM components registration
om changes in gecko 2.0 parsing errors in javascript components the most common reason for components written in javascript to fail is that there are parsing errors. these parsing errors should show up in the error console if chrome errors are enabled. to learn more about enabling chrome errors, see "how can i see errors in my code" in the extension faqs. registration failure if the module is loading correctly but doesn't register its components, try adding calls to components.utils.reporterror("debug me!"); in nsgetmodule() and other functions to try and find any errors. general hints you may need to delete compreg.dat in your profile folder to force re-registration. this should not occur if you uninstalled/installed your extension via the extension manager. when adding a component to a...
...y dependencies. linux-specific hints check if you have missing dependent libraries: from your firefox (/xulrunner) install directory, run "./run-mozilla.sh `which ldd` -r path/to/your/component.so". there should be no "not found" entries and no undefined symbols. (the -r switch from gnu ldd lists function relocations; adjust as suitable for your version) trace shared library loading by setting the environment variable ld_debug=all while launching firefox (see `man ld.so` for details). use strace to see if firefox is trying to load your components. pass the -wl,-z,defs flag to gcc when linking your component. this will ensure that undefined symbols show an error at link time instead of failing at run time. mac-specific hints use ktrace to see if firefox is trying to lo...
... `man ld.so` for details). use strace to see if firefox is trying to load your components. pass the -wl,-z,defs flag to gcc when linking your component. this will ensure that undefined symbols show an error at link time instead of failing at run time. mac-specific hints use ktrace to see if firefox is trying to load your components. use dyld environment variables to trace binary component loading: dyld_print_apis=1 dyld_print_libraries=1 (see `man dyld` for details). further help if the component still does not load, you may wish to ask for help. the extension-related places are often useful; please refer to the community section on the extensions page. ...
Mozilla
in addition, you'll find helpful articles about how the code works, how to build add-ons for mozilla applications and the like. a bird's-eye view of the mozilla framework the purpose of this article is to provide a high-level technical overview of the architecture of the extensible, object-based mozilla application framework. accessibility and mozilla accessibility is the idea that software (among other things) should be designed to be usable and, as much as possible, convenient to use for people with disabilities. ...
...base. android-specific test suites there are several android-specific test suites that run on the firefox for android codebase: api change rules until further notice, the following rules govern api changes: application cache implementation overview this happens in nshttpchannel::opencacheentry(). all top level document loading (navigation) channels are set chooseapplicationcache flag, which happens in nsdocshell::douriload(). channels having that flag set are searching for nsiapplicationcache object prior inspecting normal http cache. nsiapplicationcacheservice::chooseapplicationcache is given the url the channel is about to load. it synchronously returns an nsiapplicationcache object representing the ...
...ub. it also lists some interesting github repositories containing mozilla project code. mozilla quirks mode behavior the following is a rough list of the differences that exist between mozilla's standards mode and quirks mode behavior. mozilla style system the style system is the module of mozilla's code responsible for the loading and parsing of css style sheets, and the computation of computed values for all css properties. the handling of those computed values is the responsibility of other parts of the code. mozilla style system documentation see also the style techtalk for more complete although less detailed documentation. mozilla svg project si...
about:debugging (before Firefox 68) - Firefox Developer Tools
ed and devtools.debugger.remote-enabled preferences. both preferences must be true to enable add-on debugging. checking the box sets both preferences to true, and unchecking it sets them both to false. you can also modify the preferences directly in about:config, or by checking "enable browser chrome and add-on debugging toolboxes" and "enable remote debugging" in the developer tools settings. loading a temporary add-on with the "load temporary add-on" button you can load any sort of restartless add-on temporarily, from a directory on disk. just click the button, navigate to the directory containing the add-on's file, and select any file in that directory. the temporary add-on will be displayed under the "temporary extensions" header. you don't have to package or sign the add-on. the add-on ...
...oaded or the popup is shown. if you change files that stay loaded the whole time, like background scripts, then you can pick up changes you've made by disabling and then re-enabling the add-on in the about:addons page. if you change files that are only parsed at install time, like the manifest.json file, you'll need to restart firefox, then load the add-on again. note that before firefox 48, loading the add-on again by pressing "load temporary add-on" without restarting firefox does not work. firefox 48 onwards from firefox 48 onwards: as before: if you change files that are loaded on demand, like content scripts or popups, then changes you make are picked up automatically, and you'll see them the next time the content script is loaded or the popup is shown. there's a better way to...
...onwards from firefox 48 onwards: as before: if you change files that are loaded on demand, like content scripts or popups, then changes you make are picked up automatically, and you'll see them the next time the content script is loaded or the popup is shown. there's a better way to handle the other cases: click the "reload" button next to the "debug" button. this does what it says: reloading any persistent scripts, such as background scripts parsing the manifest.json file again, so changes to permissions, content_scripts, browser_action or any other keys will take effect. note that in firefox 49 onwards, the reload button is only enabled for temporary add-ons. it will be disabled for all other add-ons. tabs in firefox 49 onwards, a tabs page is available in about:debuggin...
Document - Web APIs
Web › API › Document
mode gets/sets the ability to edit the whole document. document.dirread only gets/sets directionality (rtl/ltr) of the document. document.domain gets/sets the domain of the current document. document.lastmodifiedread only returns the date on which the document was last modified. document.locationread only returns the uri of the current document. document.readystateread only returns loading status of the document. document.referrerread only returns the uri of the page that linked to this page. document.title sets or gets the title of the current document. document.urlread only returns the document location as a string. properties included from documentorshadowroot the document interface includes the following properties defined on the documentorshadowroot mixin. note that...
...andlers.onloadeddata is an eventhandler representing the code to be called when the loadeddata event is raised. globaleventhandlers.onloadedmetadata is an eventhandler representing the code to be called when the loadedmetadata event is raised. globaleventhandlers.onloadend is an eventhandler representing the code to be called when the loadend event is raised (when progress has stopped on the loading of a resource.) globaleventhandlers.onloadstart is an eventhandler representing the code to be called when the loadstart event is raised (when progress has begun on the loading of a resource.) globaleventhandlers.onlostpointercapture is an eventhandler representing the code to be called when the lostpointercapture event type is raised. globaleventhandlers.onmousedown is an eventhandler repr...
...the onkeydown property. keypress fired when a key that produces a character value is pressed down. also available via the onkeypress property. keyup fired when a key is released. also available via the onkeyup property. load & unload events domcontentloaded fired when the document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. readystatechange fired when the readystate attribute of a document has changed. also available via the onreadystatechange property. pointer events gotpointercapture fired when when an element captures a pointer using setpointercapture(). also available via the ongotpointercapture property. lostpointercapture fired when a captured pointer is released. also available via the onlostpoi...
Using Fetch - Web APIs
o send credentials if the request url is on the same origin as the calling script, add credentials: 'same-origin'. // the calling script is on the origin 'https://example.com' fetch('https://example.com', { credentials: 'same-origin' }); to instead ensure browsers don’t include credentials in the request, use credentials: 'omit'. fetch('https://example.com', { credentials: 'omit' }) uploading json data use fetch() to post json-encoded data. const data = { username: 'example' }; fetch('https://example.com/profile', { method: 'post', // or 'put' headers: { 'content-type': 'application/json', }, body: json.stringify(data), }) .then(response => response.json()) .then(data => { console.log('success:', data); }) .catch((error) => { console.error('error:', error); }); up...
... json data use fetch() to post json-encoded data. const data = { username: 'example' }; fetch('https://example.com/profile', { method: 'post', // or 'put' headers: { 'content-type': 'application/json', }, body: json.stringify(data), }) .then(response => response.json()) .then(data => { console.log('success:', data); }) .catch((error) => { console.error('error:', error); }); uploading a file files can be uploaded using an html <input type="file" /> input element, formdata() and fetch(). const formdata = new formdata(); const filefield = document.queryselector('input[type="file"]'); formdata.append('username', 'abc123'); formdata.append('avatar', filefield.files[0]); fetch('https://example.com/profile/avatar', { method: 'put', body: formdata }) .then(response => respons...
... const formdata = new formdata(); const photos = document.queryselector('input[type="file"][multiple]'); formdata.append('title', 'my vegas vacation'); for (let i = 0; i < photos.files.length; i++) { formdata.append('photos', photos.files[i]); } fetch('https://example.com/...
HTMLImageElement.complete - Web APIs
the image is considered completely loaded if any of the following are true: neither the src nor the srcset attribute is specified. the srcset attribute is absent and the src attribute, while specified, is the empty string (""). the image resource has been fully fetched and has been queued for rendering/compositing. ...
...ttribute is specified. the srcset attribute is absent and the src attribute, while specified, is the empty string (""). the image resource has been fully fetched and has been queued for rendering/compositing. the image element has previously determined that the image is fully available and ready for use. the image is "broken;" that is, the image failed to load due to an error or because image loading is disabled. it's worth noting that due to the image potentially being received asynchronously, the value of complete may change while your script is running. examples consider a photo library app that provides the ability to open images into a lightbox mode for improved viewing as well as editing of the image. these photos may be very large, so you don't want to wait for them to load, so you...
... running. examples consider a photo library app that provides the ability to open images into a lightbox mode for improved viewing as well as editing of the image. these photos may be very large, so you don't want to wait for them to load, so your code uses async/await to load the images in the background. but imagine that you have other code that needs to only run when the image has completed loading, such as a command that performs red-eye removal on the image in the lightbox. while ideally this command wouldn't even be executed if the image hasn't fully loaded, for improved reliability you want to check to ensure this is the case. so the fixredeyecommand() function, which is called by the button that triggers red-eye removal, checks the value of the lightbox image's complete property befor...
Navigator.sendBeacon() - Web APIs
n values the sendbeacon() method returns true if the user agent successfully queued the data for transfer. otherwise, it returns false. description this method is for analytics and diagnostics that send data to a server before the document is unloaded, where sending the data any sooner may miss some possible data collection. for example, which link the user clicked before navigating away and unloading the page. ensuring that data has been sent during the unloading of a document has traditionally been difficult, because user agents typically ignore asynchronous xmlhttprequests made in an unload handler. historically, this was addressed with some of the following workarounds to delay the page unload long enough to send data to some url: submitting the data with a blocking synchronous xmlhtt...
...o delay the page unload long enough to send data to some url: submitting the data with a blocking synchronous xmlhttprequest call in unload or beforeunload event handlers. creating an <img> element and setting its src in the unload handler. most user agents will delay the unload to load the image. creating a no-op loop for several seconds in the unload handler. all of these methods block unloading the document, which slows down the next navigation. there is nothing the next page can do to avoid this, so the new page seems slow, even though it's the previous page's fault. the following example shows theoretical analytics code that attempts to submit data to a server with a synchronous xmlhttprequest in an unload handler. this results in the next page load to be delayed. window.addeventlis...
...` means synchronous xhr.send(analyticsdata); }); this is what sendbeacon() replaces. with the sendbeacon() method, the data is transmitted asynchronously when the user agent has an opportunity to do so, without delaying unload or the next navigation. this solves all of the problems with submission of analytics data: the data is sent reliably it's sent asynchronously it doesn't impact the loading of the next page in addition, the code is simpler to write than any of the older techniques! the following example shows a theoretical analytics code pattern that submits data to a server using the sendbeacon() method. window.addeventlistener("unload", function logdata() { navigator.sendbeacon("/log", analyticsdata); }); the beacon sends an http request via the post method, with all relev...
Window - Web APIs
Web › API › Window
t document by the specified number of pages. window.scrollto() scrolls to a particular set of coordinates in the document. window.setimmediate() executes a function after the browser has finished other heavy tasks window.setresizable() toggles a user's ability to resize a window. window.sizetocontent() sizes the window according to its content. window.stop() this method stops window loading. window.updatecommands() updates the state of commands of the current chrome window (ui). methods implemented from elsewhere eventtarget.addeventlistener() register an event handler to a specific event type on the window. eventtarget.dispatchevent() used to trigger an event. windoworworkerglobalscope.atob() decodes a string of data which has been encoded using base-64 encoding. win...
...en requested by a call to the window.mozrequestanimationframe() method. window.onpaint an event handler property for paint events on the window. window.onrejectionhandled an event handler for handled promise rejection events. window.onuserproximity an event handler property for user proximity events. event handlers implemented from elsewhere globaleventhandlers.onabort called when the loading of a resource has been aborted, such as by a user canceling the load while it is still in progress windoweventhandlers.onafterprint called when the print dialog box is closed. see afterprint event. windoweventhandlers.onbeforeprint called when the print dialog box is opened. see beforeprint event. windoweventhandlers.onbeforeunload an event handler property for before-unload events on the w...
...history entry changes. also available using the onpopstate event handler property. load & unload events beforeunload fired when the window, the document and its resources are about to be unloaded. also available via the onbeforeunload property. domcontentloaded fired when the document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. load fired when the whole page has loaded, including all dependent resources such as stylesheets images. also available via the onload property. unload fired when the document or a child resource is being unloaded. also available via the onunload property. manifest events appinstalled fired when the browser has successfully installed a page as an application. also available via the ...
ARIA: feed role - Accessibility
<section role="feed" aria-busy="false"> ... ...
...technologies that governs scroll interactions so that assistive technology users can read articles, jump forward and backward by article, and reliably trigger new articles to load while in reading mode. examples include an rss feed, news feeds, social media feeds like facebook, instagram or twitter, or even a list of related products on an ecommerce page. these streams can be limited or infinite, loading more content as the user scrolls. implementing the feed pattern allows a screen reader to reliably read and trigger the loading of feed content while in reading mode. a feed is a container element whose children are <article>s or have role article. each article within a feed should be focusable, with tabindex of 0 or -1. an article should be scrolled into view when it, or a descendant element, r...
...ciently discern which articles they want to read. the feed pattern enables reliable assistive technology reading mode interaction by establishing the following interoperability agreement between the web page and assistive technologies: in the context of a feed, the web page code is responsible for: appropriate visual scrolling of the content based on which article contains dom focus. loading or removing feed articles based on which article contains dom focus. in the context of a feed, assistive technologies with a reading mode are responsible for: indicating which article contains the reading cursor by ensuring the article element or one of its descendants has dom focus. providing reading mode keys that move dom focus to the next and previous articles. providing rea...
Getting Started - Developer guides
servers. it can send and receive information in various formats, including json, xml, html, and text files. ajax’s most appealing characteristic is its "asynchronous" nature, which means it can communicate with the server, exchange data, and update the page without having to refresh the page. the two major features of ajax allow you to do the following: make requests to the server without reloading the page receive and work with data from the server step 1 – how to make an http request in order to make an http request to the server with javascript, you need an instance of an object with the necessary functionality. this is where xmlhttprequest comes in. its predecessor originated in internet explorer as an activex object called xmlhttp. then, mozilla, safari, and other browsers follow...
...that means that the full server response was received and it's ok for you to continue processing it. if (httprequest.readystate === xmlhttprequest.done) { // everything is good, the response was received. } else { // not ready yet. } the full list of the readystate values is documented at xmlhttprequest.readystate and is as follows: 0 (uninitialized) or (request not initialized) 1 (loading) or (server connection established) 2 (loaded) or (request received) 3 (interactive) or (processing request) 4 (complete) or (request finished and response is ready) next, check the http response status codes of the http response. the possible codes are listed at the w3c. in the following example, we differentiate between a successful and unsuccessful ajax call by checking for a 200 ok respo...
...test.php file should contain the following: $name = (isset($_post['username'])) ? $_post['username'] : 'no name'; $computedstring = "hi, " . $name . "!"; $array = ['username' => $name, 'computedstring' => $computedstring]; echo json_encode($array); for more on dom methods, be sure to check out document object model (dom). simple timed xhr example another simple example follows — here we are loading a text file via xhr, the structure of which is assumed to be like this: time: 312.05 time: 312.07 time: 312.10 time: 312.12 time: 312.14 time: 312.15 once the text file is loaded, we split() the items into an array at each newline character (\n — basically where each line break is in the text file), and then print the complete list of timestamps, and the last timestamp, onto the page. this i...
Media events - Developer guides
d), and the load() method is called to reload it. encrypted the user agent has encountered initialization data in the media data. ended sent when playback completes. error sent when an error occurs. the element's error attribute contains more information. see htmlmediaelement.error for details. loadeddata the first frame of the media has finished loading. loadedmetadata the media's metadata has finished loading; all attributes now contain as much useful information as they're going to. loadstart sent when loading of the media begins. mozaudioavailable sent when an audio buffer is provided to the audio layer for processing; the buffer contains raw audio samples that may or may not already have been played by the...
...layback state is no longer paused, as a result of the play method, or the autoplay attribute. playing sent when the media has enough data to start playing, after the play event, but also when recovering from being stalled, when looping media restarts, and after seeked, if it was playing before seeking. progress sent periodically to inform interested parties of progress downloading the media. information about the current amount of the media that has been downloaded is available in the media element's buffered attribute. ratechange sent when the playback speed changes. seeked sent when a seek operation completes. seeking sent when a seek operation begins. stalled sent when the user agent is trying to fetch media data, but data...
...at has been downloaded is available in the media element's buffered attribute. ratechange sent when the playback speed changes. seeked sent when a seek operation completes. seeking sent when a seek operation begins. stalled sent when the user agent is trying to fetch media data, but data is unexpectedly not forthcoming. suspend sent when loading of the media is suspended; this may happen either because the download has completed or because it has been paused for any other reason. timeupdate the time indicated by the element's currenttime attribute has changed. volumechange sent when the audio volume changes (both when the volume is set and when the muted attribute is changed). waiting sent when the req...
<img>: The Image Embed element - HTML: Hypertext Markup Language
Web › HTML › Element › img
tiff none built-in; add-ons required webp web picture format image/webp .webp chrome, edge, firefox, opera the abbreviation for each format links to a longer description of the format, its capabilities, and detailed browser compatibility information; including which versions introduced support and specific special features that may have been introduced later. image loading errors if an error occurs while loading or rendering an image, and an onerror event handler has been set on the error event, that event handler will get called. this can happen in a number of situations, including: the src attribute is empty ("") or null. the src url is the same as the url of the page the user is currently on. the image is corrupted in some way that prevents it from being l...
...this attribute. explainer, examples ismap this boolean attribute indicates that the image is part of a server-side map. if so, the coordinates where the user clicked on the image are sent to the server. note: this attribute is allowed only if the <img> element is a descendant of an <a> element with a valid href attribute. this gives users without pointing devices a fallback destination. loading indicates how the browser should load the image: eager: loads the image immediately, regardless of whether or not the image is currently within the visible viewport (this is the default value). lazy: defers loading the image until it reaches a calculated distance from the viewport, as defined by the browser. the intent is to avoid the network and storage bandwidth needed to handle the imag...
...hin the visible viewport (this is the default value). lazy: defers loading the image until it reaches a calculated distance from the viewport, as defined by the browser. the intent is to avoid the network and storage bandwidth needed to handle the image until it's reasonably certain that it will be needed. this generally improves the performance of the content in most typical use cases. note: loading is only deferred when javascript is enabled. this is an anti-tracking measure, because if a user agent supported lazy loading when scripting is disabled, it would still be possible for a site to track a user's approximate scroll position throughout a session, by strategically placing images in a page's markup such that a server can track how many images are requested and when. referrerpol...
Link types - HTML: Hypertext Markup Language
part of the document or to the document as a whole. only the data on the page can indicate this. note: although recognized, the synonym copyright is incorrect and must be avoided. <a>, <area>, <form>, <link> none. manifest indicates that the linked file is a web app manifest. <link> <a>, <area>, <form> modulepreload initiates early (and high-priority) loading of module scripts. <link> <a>, <area>, <form> next indicates that the hyperlink leads to the next resource of the sequence the current page is in. note: other link types related to linking resources in the same sequence are first, prev, last. <a>, <area>, <form>, <link> none. nofollow indicates that the linked document is not endorsed by the author of ...
... used to make such a call is defined in the pingback 1.0 specification. note: if the x-pingback: http header is also present, it supersedes the <link> element with this link type. <link> <a>, <area>, <form> preconnect provides a hint to the browser suggesting that it open a connection to the linked web site in advance, without disclosing any private information or downloading any content, so that when the link is followed the linked content can be fetched more quickly. <link> <a>, <area>, <form> prefetch suggests that the browser fetch the linked resource in advance, as it is likely to be requested by the user. starting with firefox 44, the value of the crossorigin attribute is taken into consideration, making it possible to make anonymous prefetches...
...e value of the crossorigin attribute is taken into consideration, making it possible to make anonymous prefetches. note: the link prefetch faq has details on which links can be prefetched and on alternative methods. <link> <a>, <area>, <form> preload tells the browser to download a resource because this resource will be needed later during the current navigation. see preloading content with rel="preload" for more details. <link> <a>, <area>, <form> prerender suggests that the browser fetch the linked resource in advance, and that it also render the prefetched content offscreen so it can be quickly presented to the user once needed. <link> <a>, <area>, <form> prev indicates that the hyperlink leads to the preceding resource of the se...
Using the application cache - HTML: Hypertext Markup Language
bar the first time a user loads an application that uses the application cache. the notification bar displays a message such as: this website (example.com) is asking to store data on your computer for offline use. [allow] [never for this site] [not now] the term "offline(-enabled) applications" sometimes refers specifically to applications that the user has allowed to use offline capabilities. loading documents the use of an application cache modifies the normal process of loading a document: if an application cache exists, the browser loads the document and its associated resources directly from the cache, without accessing the network. this speeds up the document load time. the browser then checks to see if the cache manifest has been updated on the server. if the cache manifest has be...
...m the cache, without accessing the network. this speeds up the document load time. the browser then checks to see if the cache manifest has been updated on the server. if the cache manifest has been updated, the browser downloads a new version of the manifest and the resources listed in the manifest. this is done in the background and does not affect performance significantly. the process for loading documents and updating the application cache is specified in greater detail below: when the browser visits a document that includes the manifest attribute, if no application cache exists, the browser loads the document and then fetches all the entries listed in the manifest file, creating the first version of the application cache. subsequent visits to that document cause the browser to load ...
...dicates the current condition of the cache. caches that share the same manifest uri share the same cache state, which can be one of the following: uncached a special value that indicates that an application cache object is not fully initialized. idle the application cache is not currently in the process of being updated. checking the manifest is being fetched and checked for updates. downloading resources are being downloaded to be added to the cache, due to a changed resource manifest. updateready there is a new version of the application cache available. there is a corresponding updateready event, which is fired instead of the cached event when a new update has been downloaded but not yet activated using the swapcache() method. obsolete the application cache group is now obsolete.
Content-Security-Policy - HTTP
regulate nested browsing contexts and workers, you should use the frame-src and worker-src directives, respectively. connect-src restricts the urls which can be loaded using script interfaces default-src serves as a fallback for the other fetch directives. font-src specifies valid sources for fonts loaded using @font-face. frame-src specifies valid sources for nested browsing contexts loading using elements such as <frame> and <iframe>. img-src specifies valid sources of images and favicons. manifest-src specifies valid sources of application manifest files. media-src specifies valid sources for loading media using the <audio> , <video> and <track> elements. object-src specifies valid sources for the <object>, <embed>, and <applet> elements. elements controlled by object-src ...
...so adding forward compatibility when browsers get report-to support, you can specify both report-uri and report-to: content-security-policy: ...; report-uri https://endpoint.example.com; report-to groupname in browsers that support report-to, the report-uri directive will be ignored. report-to fires a securitypolicyviolationevent. other directives block-all-mixed-content prevents loading any assets using http when the page is loaded using https. referrer used to specify information in the referer (sic) header for links away from a page. use the referrer-policy header instead. require-sri-for requires the use of sri for scripts or styles on the page. require-trusted-types-for enforces trusted types at the dom xss injection sinks. trusted-types used to specify an al...
..., which means that there will be no connection allowed and, as the strictest policy, connect-src 'none' is enforced. ...
JavaScript modules - JavaScript
time, and there are a number of javascript libraries and frameworks that enable module usage (for example, other commonjs and amd-based module systems like requirejs, and more recently webpack and babel). the good news is that modern browsers have started to support module functionality natively, and this is what this article is all about. this can only be a good thing — browsers can optimize loading of modules, making it more efficient than having to use a library and do all of that extra client-side processing and extra round trips. browser support use of native javascript modules is dependent on the import and export statements; these are supported in browsers as follows: import desktopmobileserverchromeedgefirefoxinternet exploreroperasafariandroid webviewchrome for androidfirefox for...
... file:// url), you'll run into cors errors due to javascript module security requirements. you need to do your testing through a server. also, note that you might get different behavior from sections of script defined inside modules as opposed to in standard scripts. this is because modules use strict mode automatically. there is no need to use the defer attribute (see <script> attributes) when loading a module script; modules are deferred automatically. modules are only executed once, even if they have been referenced in multiple <script> tags. last but not least, let's make this clear — module features are imported into the scope of a single script — they aren't available in the global scope. therefore, you will only be able to access imported features in the script they are imported in...
...o write any useful related code inside the same file. so now in the main.js file, we can get access to all three module classes by replacing import { square } from './modules/square.js'; import { circle } from './modules/circle.js'; import { triangle } from './modules/triangle.js'; with the following single line: import { square, circle, triangle } from './modules/shapes.js'; dynamic module loading the newest part of the javascript modules functionality to be available in browsers is dynamic module loading. this allows you to dynamically load modules only when they are needed, rather than having to load everything up front. this has some obvious performance advantages; let's read on and see how it works. this new functionality allows you to call import() as a function, passing it the path...
Populating the page: how browsers work - Web Performance
hread can complete all the work we throw at it and still always be available to handle user interactions. web performance can be improved by understanding the single-threaded nature of the browser and minimizing the main thread's responsibilities, where possible and appropriate, to ensure rendering is smooth and responses to interactions are immediate. navigation navigation is the first step in loading a web page. it occurs whenever a user requests a page by entering a url into the address bar, clicking a link, submitting a form, as well as other actions. one of the goals of web performance is to minimize the amount of time a navigation takes to complete. in ideal conditions, this usually doesn't take too long, but latency and bandwidth are foes which can cause delays. dns lookup the first s...
...been downloaded. the optimizations the preload scanner provides reduce blockages. <link rel="stylesheet" src="styles.css"/> <script src="myscript.js" async></script> <img src="myimage.jpg" alt="image description"/> <script src="anotherscript.js" async></script> in this example, while the main thread is parsing the html and css, the preload scanner will find the scripts and image, and start downloading them as well. to ensure the script doesn't block the process, add the async attribute, or the defer attribute if javascript parsing and execution order is not important. waiting to obtain css doesn't block html parsing or downloading, but it does block javascript, because javascript is often used to query css properties’ impact on elements. building the cssom the second step in the critical ...
...to parse css, construct the cssom tree, and recursively calculate computed styles. 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). javascript is interpreted, compiled, parsed and executed. the scripts are parsed into abstract syntax trees. some browser engines take the abstract syntax tree and pass it into an interpreter, outputting bytecode which is executed on the main thread. this is known as javascript compilation. building the accessibility tree the browser also builds an accessibility...
Recommended Web Performance Timings: How long is too long? - Web Performance
load goal the 'under a second' is often touted as optimal for load, but what does that mean? a second should be considered a rule in the maximum amount of time to indicate to a user that the request for new content was made and will load, such as the browser displaying the page title and the background color of the page displaying. the first asset retrieved from a request is usually an html document, which then makes calls for additional assets. ...
...d the background color of the page displaying. the first asset retrieved from a request is usually an html document, which then makes calls for additional assets. as noted in the description of the critical rendering path, when received, browsers immediately start processing the html, rendering the content as it is received rather than waiting for additional assets to load. yes, one second for loading is a goal, but it's something few sites achieve. expectations differ. a 'hello world' on the corporate network would be expected to load in milliseconds, but a user downloading a cat video on a five-year-old device over an edge network in northern siberia would likely find a 20-second download speedy. if you wait three or four seconds without communicating to the user that a load is happening and...
...otential visitors, and those visitors will take a long time to come back if they ever do. in optimizing for performance, do set an ambitious first load goal, such as 5 seconds over the mobile 3g network and 1.5 seconds on an office t1 line, with even more ambitious page load goals for subsequent page loads, leveraging service workers and caching. there are different suggested times for initially loading the page versus loading additional assets, responding to user interaction, and ensuring smooth animations: idling goal browsers are single threaded (though background threads are supported for web workers). this means that user interaction, painting, and script execution are all on the same thread. if the thread is busy doing complex javascript execution, the main thread will not be available t...
Progressive web app structure - Progressive web apps (PWAs)
hat benefits it brings. architecture of an app there are two main, different approaches to rendering a website — on the server or on the client. they both have their advantages and disadvantages, and you can mix the two approaches to some degree. server-side rendering (ssr) means a website is rendered on the server, so it offers quicker first load, but navigating between pages requires downloading new html content. it works great across browsers, but it suffers in terms of time navigating between pages and therefore general perceived performance — loading a page requires a new round trip to the server. client-side rendering (csr) allows the website to be updated in the browser almost instantly when navigating to different pages, but requires more of an initial download hit and extra ren...
...rs. the most popular approach is the "app shell" concept, which mixes ssr and csr in exactly the way described above, and in addition follows the "offline first" methodology which we will explain in detail in upcoming articles and use in our example application. there is also a new approach involving the streams api, which we'll mention briefly. app shell the app shell concept is concerned with loading a minimal user interface as soon as possible and then caching it so it is available offline for subsequent visits before then loading all the contents of the app. that way, the next time someone visits the app from the device, the ui loads from the cache immediately and any new content is requested from the server (if it isn’t available in the cache already). this structure is fast, and also f...
...it also allows the website to be accessible offline if the network connection is not available. we can control what is requested from the server and what is retrieved from the cache with a service worker, which will be explained in detail in the next article — for now let's focus on the structure itself. ...
WebAssembly Concepts - WebAssembly
is powerful enough to solve most problems people have on the web today. we have run into performance problems, however, when trying to use javascript for more intensive use cases like 3d games, virtual and augmented reality, computer vision, image/video editing, and a number of other domains that demand native performance (see webassembly use cases for more ideas). additionally, the cost of downloading, parsing, and compiling very large javascript applications can be prohibitive. mobile and other resource-constrained platforms can further amplify these performance bottlenecks. webassembly is a different language from javascript, but it is not intended as a replacement. instead, it is designed to complement and work alongside javascript, allowing web developers to take advantage of both languag...
...functions. in the future, webassembly modules will be loadable just like es2015 modules (using <script type='module'>), meaning that javascript will be able to fetch, compile, and import a webassembly module as easily as an es2015 module. how do i use webassembly in my app? above we talked about the raw primitives that webassembly adds to the web platform: a binary format for code and apis for loading and running this binary code. now let’s talk about how we can use these primitives in practice. the webassembly ecosystem is at a nascent stage; more tools will undoubtedly emerge going forward. right now, there are four main entry points: porting a c/c++ application with emscripten. writing or generating webassembly directly at the assembly level. writing a rust application and targeting...
...re a number of online wasm assembler choices, such as: wasmfiddle wasmfiddle++ wasmexplorer these are great resources for people who are trying to figure out where to start, but they lack some of the tooling and optimizations of emscripten. the emscripten tool is able to take just about any c/c++ source code and compile it into a .wasm module, plus the necessary javascript "glue" code for loading and running the module, and an html document to display the results of the code. in a nutshell, the process works as follows: emscripten first feeds the c/c++ into clang+llvm — a mature open-source c/c++ compiler toolchain, shipped as part of xcode on osx for example. emscripten transforms the compiled result of clang+llvm into a .wasm binary. by itself, webassembly cannot currently dir...
Content Scripts - Archive of obsolete content
ntent. in many ways these are like content scripts, but they're not the focus of this article. to learn about how to interact with the content for a given user interface module, please see the module-specific documentation: panel, sidebar, frame. almost all the examples presented in this guide are available as complete, but minimal, add-ons in the addon-sdk-content-scripts repository on github. loading content scripts you can load a single script by assigning a string to either the contentscript or the contentscriptfile option. the contentscript option treats the string itself as a script: // main.js var pagemod = require("sdk/page-mod"); var contentscriptvalue = 'document.body.innerhtml = ' + ' "<h1>page matches ruleset</h1>";'; pagemod.pagemod({ include: "*.moz...
...s inserted into the dom. at this point the dom content hasn't been loaded yet, so the script won't be able to interact with it. "ready": load the scripts after the dom for the page has been loaded: that is, at the point the domcontentloaded event fires. at this point, content scripts are able to interact with the dom content, but externally-referenced stylesheets and images may not have finished loading. "end": load the scripts after all content (dom, js, css, images) for the page has been loaded, at the time the window.onload event fires. the default value is "end". note that tab.attach() doesn't accept contentscriptwhen, because it's generally called after the page has loaded. passing configuration options the contentscriptoptions is a json object that is exposed to content scripts as a ...
Working with Events - Archive of obsolete content
by registering a listener function to an event emitter an add-on can receive notifications of these events. we talk about content scripts in more detail in the working with content scripts guide. additionally, if you're using content scripts to interact with web content, you can define your own events and use them to communicate between the main add-on code and the content scripts. ...
...t with web content, you can define your own events and use them to communicate between the main add-on code and the content scripts. in this case one end of the conversation emits the events, and the other end listens to them. so there are two main ways you will interact with the eventemitter framework: listening to built-in events emitted by objects in the sdk, such as tabs opening, pages loading, mouse clicks sending and receiving user-defined events between content scripts and add-on code this guide only covers the first of these; the second is explained in the working with content scripts guide. adding listeners you can add a listener to an event emitter by calling its on(type, listener) method. it takes two parameters: type: the type of event we are interested in, i...
frame/hidden-frame - Archive of obsolete content
rectly seen or accessed by users, like page-worker. it is also useful in the construction of apis that load web content for intermittent display, such as panel. usage the module exports a constructor function, hiddenframe, and two other functions, add and remove. hiddenframe constructs a new hidden frame. add registers a hidden frame, preparing it to load content. remove unregisters a frame, unloading any content that was loaded in it. 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("dom...
.... you must specify an onready callback and refrain from using the hidden frame until the callback gets called, because hidden frames are not always ready to load content the moment they are added. functions add(hiddenframe) register a hidden frame, preparing it to load content. parameters hiddenframe : hiddenframe the frame to add remove(hiddenframe) unregister a hidden frame, unloading any content that was loaded in it. parameters hiddenframe : hiddenframe the frame to remove hiddenframe hiddenframe objects represent hidden frames. properties element the host application frame in which the page is loaded. events ready this event is emitted when the dom for a hidden frame content is ready. it is equivalent to the domcontentloaded event for the content page in a hidden...
window/utils - Archive of obsolete content
var browserwindow = utils.getmostrecentbrowserwindow(); var window = browserwindow.content; // `window` object for the current webpage utils.gettoplevelwindow(window) == browserwindow // => true parameters window : nsidomwindow returns nsidomwindow getwindowdocshell(window) returns the nsidocshell for the tabbrowser element. parameters window : nsidomwindow returns nsidocshell getwindowloadingcontext(window) returns the nsiloadcontext. parameters window : nsidomwindow returns nsiloadcontext open(uri, options) this function is used to open top level (application) windows. it takes the uri of the window document as its first argument and an optional hash of options as its second argument. var { open } = require('sdk/window/utils'); var window = open('data:text/html,hello window')...
... 15, chrome: true }. for the set of features you can set, see the window.opendialog documentation. optional, defaults to: 'chrome,all,dialog=no'. args object extra argument(s) to be attached to the new window as the window.arguments property. returns nsidomwindow windows() returns an array of all currently opened windows. note that these windows may still be loading. in order to see private windows in this list, your add-on must have opted into private browsing and you must include the includeprivate key in the list of options: var allwindows = window_utils.windows(null, {includeprivate:true}); parameters type : string string identifying the type of window to return. this is passed directly into nsiwindowmediator.getenumerator(), so its possible values...
Display a Popup - Archive of obsolete content
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...
...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: handlecl...
Examples and demos from articles - Archive of obsolete content
rent objects and then to create a constructor for such class of objects in order to standardize and simplify the instantiation of them. here is a possible and minimalist example of such abstraction, which for this reason we named minidaemon. [article] image preview before upload [html] the filereader.prototype.readasdataurl() method is useful, for example, to get a preview of an image before uploading it. [article] note: the filereader() constructor was not supported by internet explorer for versions before 10. for a full compatibility code, see also our crossbrowser possible solution for image preview. determine if an element has been totally scrolled [html] this example shows how to determine whether a user has completely scrolled an element or not. [article] css pure-css dropdown ...
...translate relative paths to absolute paths. a shortcut to massively modify the dom this example shows how to create a framework able to modify many properties of dom objects at the same time. filter the digitation into a form field, capture the digitation of a hidden word this example shows the use of the onkeypress event during a digitation into a form field. ajax – submitting forms and uploading files this paragraph shows how to submit forms in pure-ajax. multipage ajax navigation example this article provides a working (minimalist) example of a pure-ajax web site composed only of three pages. do something if current document has changed since last visit here is a possible example of how to show an alert message when current document changes. do something if an external page has ch...
On page load - Archive of obsolete content
progress listeners implement the nsiwebprogresslistener interface. ...
...progress listeners implement the nsiwebprogresslistener interface. ...
Common Pitfalls - Archive of obsolete content
there are some common pitfalls that should be avoided when writing either extensions or core mozilla code. these are the sort of things that super-review should be catching for code that goes into the tree; avoiding these to start with saves super-reviewers a lot of effort. the first couple of items deal with loading content from a uri. it's important to create the uri correctly, and then check that it's secure to load. this will shield you from loading <tt>javascript:</tt> or <tt>chrome:</tt> uris when you shouldn't. 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"] .getser...
...n 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. in that case you may not be able to use the i/o service because that service calls the newuri method on the appropriate protocol handler, which may be your own handler. how to do security checks for uri loads before loading a uri, one of two security checks needs to be performed: if the uri is a string that will be loaded via passing the string to nsiwebnavigation::loaduri, the one must call checkloaduristrwithprincipal and pass the principal that the uri originates from as the first argument and the uri string as the second argument. in all other cases, one should call checkloaduriwithprincipal and pass the prin...
Chapter 4: Using XPCOM—Implementing advanced processes - Archive of obsolete content
fname) using methods from xul elements xpcom gives you access to sophisticated functions in xul elements. for example, using the loaduri() method on the browser element introduced in chapter 3 can open a page specified using http_referer, as shown in listing 21; listing 22 shows how to open a page using the loaduriwithflags() method, with data transmitted via the post method. ...
...t method. ...
Appendix A: Add-on Performance - Archive of obsolete content
about it. there’s still one more thing you can do. do as little as possible in your load handler. ask yourself: is there anything i can’t run 100 ms or even 500 ms later? if there is, just use an nsitimer or the settimeout function to delay running this code . the firefox window will be able to load sooner and your startup code will run almost instantaneously afterward, in parallel with the loading of the homepage or the saved tab session. the browser will now load faster, and your code will still load at startup for all practical purposes. the code is simple enough: // this is the function that is called in the load event handler. init : function() { let that = this; // run this later and let the window load. window.settimeout(function() { that.postinit(); }, 500); }, postinit: fu...
...a very common filter is the url of the page, since most add-ons are limited to one or a few domains. use regular expressions if you need to. make sure your comparison code is as efficient as possible. finally, make sure all of your page load code is as efficient as possible. this can be tricky for some add-ons, like ad or script blockers that need to check a whitelist or blacklist. nevertheless, loading pages is pretty important in firefox, and users expect it to be fast. try your best to keep it that way. other recommendations always clean up after yourself. event listeners, observers and other handlers normally have both an add and a remove function. don't forget to remove what you don't need anymore! even if you need something during the whole existence of the window, you should clean eve...
Setting Up a Development Environment - Archive of obsolete content
in your system, since our examples come with all the necessary files to build and install the resulting xpi using this tool. it will save you some packaging time. or you can create an equivalent system using batch, ant or whatever you prefer. ultimately you can just compress the contents of the src directory using any zip or archive tool and get a similar result. build system let's start by downloading the project used to build the second version of hello world, from the exercise in the last section. hello world 2 project. unzip the file anywhere you want. inside the helloworld2 directory, you'll see two directories: bin and src. the bin directory should be empty. 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...
...ox versions as you want, and mix profiles and versions. on windows and linux it's easy to create shortcuts for every profile you create, using the commands described at http://kb.mozillazine.org/command_line_arguments . for mac os x developers, there is also a way to set up "shortcuts". you can do this by opening the automator application, choosing run shell script and then entering the profile-loading script in the textbox: /applications/firefox.app/contents/macos/firefox-bin -no-remote -p myprofile > /dev/null & you can change "/dev/null" to a file location, in case you want to see dump output from firefox, or other extensions. the last & prevents automator from waiting for your firefox session to finish. save this as an application, not a workflow. and you probably want to have these o...
Security best practices in extensions - Archive of obsolete content
nonprivileged) content, the latter being in the form of web pages. these web pages can come from a server, or come from local html files bundled with the extension. for pages coming from the server, you need to take steps to ensure that the content can not call back into the web browser and run malicious code. the main way to do this is by creating an iframe or browser element in the sidebar, and loading your content there. give the element a type="content" attribute, which essentially sandboxes the code there and blocks callback rights into chrome. using eval() in an extension using the built-in javascript eval function is frowned upon in the context of extensions. while there are some legitimate use-cases, most of the time there are safer alternatives. this blog post offers some excellent rea...
...on in the context of extensions. while there are some legitimate use-cases, most of the time there are safer alternatives. this blog post offers some excellent reasons not to use eval(). sandboxed http connections the main purpose of sandboxed http connections is to interact with a web service, without interfering with the cookies set in the browser by that service/site. for example, if you are loading pictures or other data from a photo sharing site, you can sandbox your connections to that site so that the normal browsing of that site by the user in the main firefox browser is not affected. for a real world use case, take a look at this blog post. handling of logins and passwords there are various ways of storing data in firefox, but for user logins and passwords, you should use the login m...
Session store API - Archive of obsolete content
e, false); simply replace the contents of the function myextensionhandlerestore() with whatever you need to do when the tab is restored. in this example, nsiconsoleservice is used to display a message to the console. this event is sent just before a tab is restored. an event of type sstabrestored fires each time a tab has finished restoring. it's worth noting that this event is sent even if tab loading at startup is deferred until the user selects the tab. firefox 3 note in firefox 3 and later, if you need to detect when a tab is about to be closed so that you can update data associated with the tab before it is closed, you can watch for the "sstabclosing" event, which is sent to the tab. restoring without restarting firefox 3.6 note this section applies to firefox 3.6 and later. fire...
...following steps are taken for each tab being restored: either an existing tab is reused or a new tab is created. in the latter case, a tabopen event is sent. the tab's persistent xul attributes (those saved due to calls to persisttabattribute()) and permissions are restored. the sstabrestoring event is sent. the tab is told to load the url it should be displaying. when the page is finished loading, text fields and scroll state are restored. finally, the sstabrestored event is sent. if you want to set permissions or otherwise manipulate a restored tab before the page is loaded into it, you should watch sstabrestoring. if you want to do something after the page is loaded, you should watch sstabrestored. both events are always sent for each tab being restored. you can determine which tab ...
CSS3 - Archive of obsolete content
irection, flex-flow, flex-item-align, flex-line-pack, flex-order, flex-pack, and flex-wrap. css cascading and inheritance level 3 candidate recommendation adds: the initial, unset values for properties. the css all property. the scoping mechanism. clarifies: interaction of media-dependent @import statements and style sheet loading requirements. css writing modes module level 3 proposed recommendation defines the writing modes of both horizontal and vertical scripts and clarifies how the css direction and unicode-bidi properties interact with the new css text-orientation property, and extends them where needed. css counter styles level 3 candidate recommendation ...
... module level 1 working draft css positioned layout module level 3 working draft css regions module level 1 working draft defines a new mechanism allowing content to flow across, eventually non-contiguous, multiple areas called regions. css object model (cssom) working draft css font loading module level 3 working draft css scoping module level 1 working draft css inline layout working draft css images module level 4 working draft extends: the image() functional notation to describe the directionality of the image (rtl or ltr), allowing for bidi-sensitive images. th...
progress - Archive of obsolete content
general info specification offline interface progressevent bubbles no cancelable no target applicationcache default action none properties property type description target eventtarget (dom element) the event target (the topmost target in the dom tree). read only. type string the type of event. read only. canbubble boolean does the event normally bubble? read only. cancelable boolean is it possible to cancel the event? read only. lengthcomputable boolean specifies whether or not the total size of the transfer is known. ...
...) the number of bytes transferred since the beginning of the operation. this doesn't include headers and other overhead, but only the content itself. read only. total unsigned long (long) the total number of bytes of content that will be transferred during the operation. if the total size is unknown, this value is zero. read only. related events checking noupdate downloading progress cached updateready obsolete error ...
Inner-browsing extending the browser navigation paradigm - Archive of obsolete content
odels possible. one such model is inner-browsing, which is our name for a model in which all navigation occurs within a single page, as in a typical application interface. the single-page context and abstraction of data from the presentation can give your web applications new continuity, precision and control. this model is also interesting because is optimized to access contextual data instead reloading full web pages. this article discusses the concept of inner-browsing and possible approaches for its implementation. it also provides two implementation examples using the model. the first one looks like a traditional dhtml ticker application and uses hidden iframes and javascript to provide updates inside the webpage's ticker headlines section. this sample was made using iframes to illustrate a ...
...ta binder will be able to get the data from the iframe's page and set the data into the main page's context. data binder component the data binder is responsible for setting the data into the main page. however the data binder should know exactly when the data is available in the iframe. there are two basic approaches to do this. one is to keep checking the iframe until the document has completed loading. another approach is to request an html page in the iframe and inside this page (requested data), set the onload event to callback a function notifying the parent document (originator). this sample is using the second approach. to demonstrate how the callback mechanism is implemented, imagine the following html page loaded into the iframe as a result of a request (retrievedata method requested th...
Source code directories overview - Archive of obsolete content
ated in the mozilla classic code base. dbm contains c code for managing, reading and writing hash tables. it is used for the auto-completion feature on the url edit box (stored in netscape.hst in mozilla classic) and for the cached pages index (stored in fat.db in mozilla classic). this code originated at uc berkeley. directory contains the ldap sdk. docshell contains c interfaces and code for loading and displaying a single web page (e.g. scroll). the [#seamonkey-embedding embedding] code wraps this code with higher level browser functions like forward, back and history. dom contains c interfaces and code for implementing and tracking dom (document object model) objects in javascript. it forms the c substructure which creates, destroys and manipulates built-in and user-defined objects accord...
...y, this is where the mozilla program starts and manages other components to accomplish tasks. this code contains very little platform dependent code; it relies on other components to provide platform independent interfaces to platform specific functionality. xpinstall contains the c interfaces and code for implementing the smartupdate feature from mozilla classic. xpinstall provides code for downloading files, uncompressing them and installing them in a platform independent way. xulrunner contains code for xul runner. firefox firefox is contained in the browser directory app contains contains code to build the firefox executable. base contains the xul and branding code. components contains firefox specific components like history, bookmarks, preferences, migration, sidebar.. configcont...
Menu - Archive of obsolete content
Archive › Mozilla › Jetpack › UI › Menu
ck.menu.context.page.on("a, img").set("a link or image"); add an item to the image context menu, but only for images contained in hyperlinks: jetpack.menu.context.page.on("a > img").set("an image inside a link"); add a "recent tweets" submenu to the jetpack menu. (assume we've defined a getrecenttweets(), which invokes a callback with an array of strings.) when the menu is shown, it displays a "loading..." item. if the menu remains open when getrecenttweets() receives data from the network and calls done(), the "loading..." item is replaced with the tweets, one item per tweet: this example will not work on os x due to a platform bug in firefox. replace jetpack.menu with jetpack.menu.context.page to see the effect on the content context menu. see bug 526382 for more information. jetpack.men...
... "loading..." item is replaced with the tweets, one item per tweet: this example will not work on os x due to a platform bug in firefox. replace jetpack.menu with jetpack.menu.context.page to see the effect on the content context menu. see bug 526382 for more information. jetpack.menu.add({ label: "recent tweets", menu: new jetpack.menu({ beforeshow: function (menu) { menu.set("loading..."); getrecenttweets(function done(tweets) menu.set(tweets)); } }) }); when the user selects some text on a page, the context menu normally displays a simple item that searches for it. replace that item with a menu that lets the user search either google or wikipedia: jetpack.menu.context.page.replace("search", function (context) { return { label: "search for " + jetpack.selec...
Modularization techniques - Archive of obsolete content
used on factories that are linked into the executable. the second takes a class id and the path to a dynamically loadable library. this mechanism can be used both inside an executable at run-time and externally using the apersist flag to tell the repository to store the class id/library relationship in its permenant store. about nsiids and nscids to simplify the process of dynamically finding, loading and binding interfaces, all classes and interfaces are assigned unique ids. the ids are unique 128 bit numbers that are based on uuids. for those who like gory details, their structure is this: struct nsid { pruint32 m0; pruint16 m1, m2; pruint8 m3[8]; }; frequently you see them represented as strings, like this: {221ffe10-ae3c-11d1-b66c-00805f8a2676} to initialize an id struct you de...
...rly identical to that of getsamplefactory() in our previous example. you only need to verify that the class id passed in is the correct one for the factory you implement. if your dll contains multiple factories, you'll need to add conditional code to determine which one to return. nscanunload() is an optional, but useful function. if implemented, it allows the nsrepository to free up memory by unloading dlls it is no longer using when freelibraries() is called. the implementation takes into consideration two things when deciding whether or not a dll can be unloaded: whether any of its factories are currently in use, and whether anyone has locked the server. if nscanunload() is not implemented, the dll will not be unloaded. the following example turns nssample.cpp into a file that can be compile...
Running Tamarin acceptance tests - Archive of obsolete content
st suite requires the following steps: set the avm environment variable to the path of the avmplus executable (avmshell). note: the name of the avmshell executable varies among the build systems; use the name of the avm shell produced from the build process you used, above. set the builtinabc environment variable to the path of the generated/builtin.abc. you may build the .abc files build by downloading the latest asc.jar. the latest asc.jar can be downloaded from from ftp://ftp.mozilla.org/pub/js/tamarin...latest/asc.jar. also the source to asc.jar may be downloaded and rebuilt from http://opensource.adobe.com/wiki/dis...exsdk/flex+sdk. set the asc environment variable, as described above. set the shellabc environment variable to the path of the generated/shell_toplevel.abc. $ cd tamarin-redux...
...needs to point to android_shell.py which is a proxy for running the tests on the phone. the /android-public/android-vars.sh script has commented-out examples of the environment settings for running tests on the android avm shell. to recap the other environment settings: - set the builtinabc environment variable to the path of the generated/builtin.abc. - you may build the .abc files build by downloading the latest asc.jar. the latest asc.jar can be downloaded from from ftp://ftp.mozilla.org/pub/js/tamarin...latest/asc.jar. also the source to asc.jar may be downloaded and rebuilt from http://opensource.adobe.com/wiki/display/flexsdk/flex+sdk. - set the asc environment variable, as described above. - set the shellabc environment variable to the path of the generated/shell_toplevel.abc. adb 'adb' ...
Using gdb on wimpy computers - Archive of obsolete content
the debugger uses a lot of memory. how do i fix it? if your computer has less than 256 mb of memory, your computer will become unhappy as gdb loads mozilla's shared libraries. the solution to this is to delay loading shared libraries until they are actually needed. however, you need to make sure that the base libraries like libc and pthreads are loaded before you tell gdb to stop loading shared libraries. if you don't allow those libraries to be loaded then gdb will not be able to properly debug threads on linux. mozilla uses pthreads for its networking library so you need to be able to work in a threaded environment. the best way to do this is to set a breakpoint in main, let the program run until main and then turn off automatic library loading. from there you can allow the program to continue...
...db) set auto-solib-add 0 (gdb) c continuing. nsnativecomponentloader: autoregistering begins. [...] it's easy to define a function for gdb to do this for you automatically. you can add this function to the .gdbinit file in your home directory: def prun tbreak main run set auto-solib-add 0 end how do i load shared libraries? if you have turned off automatic shared library loading, you will have to load them when you need them. gdb has a command to load libraries while the program is running. this is the sharedlibrary command. it can be shortened to shar when used in gdb. the argument to the command is a regular expression for the libraries to be loaded. here's what it looks like in the 4.18 version of the debugger: ^c program received signal sigint, interrupt. 0x404ccdeb ...
IO - Archive of obsolete content
Archive › Mozilla › XUL › FileGuide › IO
file and stream guide: [ nsiscriptableio | accessing files | getting file information | reading from files | writing to files | moving, copying and deleting files | uploading and downloading files | working with directories ] important note: the pages from the file and stream guide use the io object (nsiscriptableio), which was not available in any released version of the platform (pending some fixes). there are alternative xpcom apis you can use, your help in updating this pages to use the supported api is very much welcome! other documentation on files and i/o not using the unavailable nsiscriptableio apis: code snippets: file i/o, open and save dialogs, reading textual data, writing textual data, list of file-related error codes. files and streams this section describes how to access and ...
...ar file = io.getfile("profile", "subdirname"); for more information about using directories, see working with directories. 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. upload and download files upload files to learn how to upload and post files to a web site, see uploading and downloading files. download files to learn how to download and save a file from a web site to disk, see downloading files. ...
ContextMenus - Archive of obsolete content
ode property was used; this is now deprecated. in this example, the triggernode property is checked for a popup attached to a browser to determine whether an image is clicked: <script> function showhideitems(aevent) { // aevent.target is the popup for which the popupshowing event fired. ...
...owing="showhideitems(event)"> <menuitem label="copy"/> <menuitem id="enlarge" label="enlarge image"/> <menuitem id="details" label="image details"/> </menupopup> <browser src="http://www.mozilla.org" context="contentareacontextmenu"/> when the popupshowing event is fired, the showhideitems function is called. the triggernode is retrieved and examined to see if it is an image. the nsiimageloadingcontent interface is implemented by all types of images. this is useful instead of comparing the tag, as several different tags support images. the test also checks to ensure that the element has a uri set. finally, the hidden state of two menuitems are adjusted based on whether the context is an image or not. the result is that context clicking on images will show a menu with three items, but wi...
tabbrowser - Archive of obsolete content
y contains the nsiwebnavigation object for the document. most of its methods are callable directly on the element itself, such as goback and goforward. it also contains the load constants used by reloadwithflags and loaduriwithflags. webprogress type: nsiwebprogress this read-only property contains an nsiwebprogress object which is used to monitor the progress of a document loading. methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(),...
...eturn type: no return value sets the specified tab's favicon to the image specified by auri. see geticon to get the current icon. showonlythesetabs( atabs ) return type: no return value makes all tabs in the atabs array visible, and all other tabs hidden. stop() return type: no return value equivalent to pressing the stop button, this method stops the currently loading document. unpintab( tabelement ) return type: no return value unpins the specified tab element, making it no longer an app tab. related code snippets: tabbed browser ...
XULRunner Hall of Fame - Archive of obsolete content
opment tool. build instructions pencil the pencil project's unique mission is to build a free and opensource tool for making diagrams and gui prototyping that everyone can use. source qiqqa research manager, reference manager, and pdf manager. xulrunner is embedded to provide automatic search against journal archives, automatic acquisition of bibtex information, and automatic downloading of pdfs. slimerjs slimerjs is a xulrunner application that can be launched with firefox, allowing to execute an external javascript script which can manipulate web content. its goal is to provide a tool like phantomjs, with the same api, except that it runs gecko instead of webkit, and it is not headless (but you can still use xvfb to have a headless slimerjs). sqlite manager ...
... lines (game). latest release: 1.2 november 2008 - source cocoapsyc.app a psyc im/chat client for mac os x (also available as a firefox extension). latest release 0.5 febuary 2010 - source daim (fr) / daim (english) superb tool for image analysis build on top of a professional imagelib. echofon for windows a twitter client. emusic remote the emusic remote makes downloading from emusic a snap. latest release: 1.0.0.2 march 2009 - source findthatfont! font managing tool for windows and linux, that helps you find the font you're looking for. latest release december 2007 flickr uploadr 3.0 upload your photos to flickr. source google adwords editor adwords editor is google's free, downloadable account management application for your computer. lat...
calICalendarView - Archive of obsolete content
rview does not contain any additem or refresh methods. therefore, it makes sense for an implementation of calicalendarview to add a caliobserver to the its displaycalendar in order to be notified of additions, modifications, and deletions of items it may be displaying. note that in most cases, this attribute will be set by the consumers of calicalendarview very early in an application/extension's loading process. controller the controller for a calicalendarview is an implementation of calicalendarviewcontroller and provides an integral link with the code in which a calicalendarview may be used. this link allows the calicalendarview to have a way of creating, modifying, and deleting events based on user interaction with the dom nodes it controls, often without requiring any other user interacti...
...therefore, a calicalendarview will not provide its own controller, but rather rely on other code to set this attribute. implementations should therefore be wary to check whether a controller has been assigned to the view, before calling any of the methods it implements.note that in most cases, this attribute will be set by the consumers of calicalendarview very early in an application/extension's loading process. startdate returns a calidatetime corresponding to the first date shown by the view enddate returns a calidatetime corresponding to the last date shown by the view. note that this date is typically not immediately useful for querying for the events and tasks shown in the calicalendarview. typically, one more day must be added to it, in order to make it exclusive. supportsdisjointd...
nsIContentPolicy - Archive of obsolete content
63 introduced gecko 1.0 inherits from: nsicontentpolicybase last changed in gecko 42 (firefox 42 / thunderbird 42 / seamonkey 2.39) you can observe content that is being loaded into your browser by implementing nsicontentpolicy. ...
...gecko 1.8 subdocument 5 obsolete since gecko 1.8 control_tag 6 obsolete since gecko 1.8 raw_url 7 obsolete since gecko 1.8 document 8 obsolete since gecko 1.8 methods shouldload() called to let your content policy implementation decide whether or not the resource at a given location should be loaded. this method is called before loading the resource specified by acontentlocation to determine whether or not to start loading the requested resource. shouldload() can be called while the dom and layout of the document involved is in an inconsistent state. this means that implementers of this method must not do any of the following: modify the dom in any way (e.g., setting attributes is a no-no). query any dom properties that dep...
Popup Window Controls - Archive of obsolete content
detecting suppressed popups windows if a user ...
...operation of your web site you can notify the user and ask them to add your site to the list of sites which are allowed to use unsolicited popup windows. you can also provide a hyperlink which can be used to open a popup window even in the event that the user has suppressed unsolicited popups on your site. 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. example the example tag links to devedge-temp.mozilla.org this example illustrates detecting suppressed popup windows as well as an approach for...
Game distribution - Game development
de players with the updated code almost instantly. direct link distribution and instant play you don't have to tell people to search for your game in an app store with html5 games. you can just send them a direct url to access the game, which they can then click to play the game right away without the need to use third party plugins or download and install a large package. bear in mind that downloading the game might still take a bit of time depending on the size of the game and your network speed. in any case, it's a lot easier to promote the game if you can drive traffic directly where you want it and don't have to jump through lots of hoops to play. desktop vs mobile the vast majority of the traffic we are interested in — people playing html5 games — comes from mobile devices so that's...
... take most of the market share, and think carefully about whether this suits your strategy. to do the desktop thing properly you should support all three operating systems: windows, mac os and linux. the biggest desktop store for games is definitely steam — indie developers can get on steam via the steam direct program. remember that you have to deal with the cross-platform issues yourself by uploading separate versions for different platforms. after you've covered steam, there's plenty of buzz around initiatives like humble bundle where the most popular indie games get presented to a broader audience. it's more like an excellent promotional opportunity than a way to earn a lot of money, however, as the prices paid for the games in a bundle are usually quite low. packaging games the web is t...
Building up a basic demo with the PlayCanvas engine - Game development
that's quite an impressive list of features — let's see some in action. we will try putting together a simple demo first — a cube rendered on the screen. if you have already worked through our building up a basic demo with three.js article (or you are familiar with other 3d libraries) you'll notice that playcanvas works on similar concepts: camera, light and objects. ...
...plication and positioned to be 7 units away from the center of the scene on the z axis. this allows us to make some space to visualize the objects that we will create later on. note: the distance values (e.g. for the camera z position) are unitless, and can basically be anything you deem suitable for your scene — milimeters, meters, feet, or miles — it's up to you. try saving the file and loading it in your browser. you should now see a gray window. congratulations! geometry now the scene is properly rendering we can start adding 3d shapes to it. to speed up development playcanvas provides a bunch of predefined primitives that you can use to create shapes instantly in a single line of code. there are cubes, spheres, cylinders and more complicated shapes available. drawing everything for...
Animations and tweens - Game development
esheet from an external source and displaying the sprites sequentially. as an example, we will make the ball wobble when it hits something. first of all, grab the spritesheet from github and save it in your /img directory. ...
... instead of loading a single image of the ball we can load the whole spritesheet — a collection of different images. we will show the sprites sequentially to create the illusion of animation. the spritesheet() method's two extra paremeters determine the width and height of each single frame in the given spritesheet file, indicating to the program how to chop it up to get the individual frames. ...
Code splitting - MDN Web Docs Glossary: Definitions of Web-related terms
code splitting is the splitting of code into various bundles or components which can then be loaded on demand or in parallel. as an application grows in complexity or is simply maintained, css and javascripts files or bundles grow in byte size, especially as the number and size of included third-party libraries increases. to prevent the requirement of downloading ginormous files, scripts can be split into multiple smaller files. then features required at page load can be downloaded immediately with additional scripts being lazy loaded after the page or application is interactive, thus improving performance. while the total amount of code is the same (and perhaps even a few bytes larger), the amount of code needed during initial load can be reduced. code splitting is a feature supported...
...ter the page or application is interactive, thus improving performance. while the total amount of code is the same (and perhaps even a few bytes larger), the amount of code needed during initial load can be reduced. code splitting is a feature supported by bundlers like webpack and browserify which can create multiple bundles that can be dynamically loaded at runtime. see also bundling lazy loading http/2 tree shaking ...
Lazy load - MDN Web Docs Glossary: Definitions of Web-related terms
lazy loading is a strategy that delays the loading of some assets (e.g., images) until they are needed by the user based on the user's activity and navigation pattern; typically, these assets are only loaded when they are scrolled into view. if correctly implemented, this delay in asset loading is seamless to the user experience and might help improve initial load performance, including time to interactive, as fewer assets are required for the page to start working. ...
...ey are needed by the user based on the user's activity and navigation pattern; typically, these assets are only loaded when they are scrolled into view. ...
Perceived performance - MDN Web Docs Glossary: Definitions of Web-related terms
human perception, not an objective metric like time to interactive. in terms of web performance, perceived performance is how fast a user interaction feels rather than how fast an interaction actually is, be that a button press or a page load. perceived performance is not how fast your site is; it's how fast your users think it is. ...
...ured by when your site is done loading but when it has loaded enough for users to believe it has loaded and is interactive. in terms of conversion rates, perceived performance is more important than the actual load and response times. speed index is a common metric for measuring perceived performance, though it's not perfect. other features, such as good ux design, including animations, and lazy loading, can make your site appear more responsive, even if the download and response times remain the same. actual performance is a measurement from when a request is made, through the downloading, parsing and execution of all resources, and the final paint. while increased performance generally increases perceived performance, there are some techniques that can be used to increase perceived performanc...
WAI-ARIA basics - Learn web development
ccessed using a screenreader, from textual content to alternative text attached to images. traditional static websites with largely text content are therefore easy to make accessible for people with visual impairments. the problem is that modern web apps are often not just static text — they tend to have a lot of dynamically updating content, i.e. content that updates without the entire page reloading via a mechanism like xmlhttprequest, fetch, or dom apis. these are sometimes referred to as live regions. let's look at a quick example — see aria-no-live.html (also see it running live). in this example we have a simple random quote box: <section> <h1>random quote</h1> <blockquote> <p></p> </blockquote> </section> our javascript loads a json file via xmlhttprequest containing a se...
... to the user as soon as possible. we'd like you to take a copy of aria-no-live.html and quotes.json, and update your <section> tag as follows: <section aria-live="assertive"> this will cause a screenreader to read out the content as it is updated. note: most browsers will throw a security exception if you try to do an xmlhttprequest call from a file:// url, e.g. if you just load the file by loading it directly into the browser (via double clicking, etc.). to get it to run, you will need to upload it to a web server, for example using github, or a local web server like python's simplehttpserver. there is an additional consideration here — only the bit of text that updates is read out. it might be nice if we always read out the heading too, so the user can remember what is being read out.
Web fonts - Learn web development
ing the required code now you'll need to generate the required code (and font formats). for each font, follow these steps: make sure you have satisfied any licensing requirement, if you are going to use this in a commercial and/or web project. go to the fontsquirrel webfont generator. upload your two font files using the upload fonts button. check the checkbox labeled "yes, the fonts i'm uploading are legally eligible for web embedding." click download your kit. after the generator has finished processing, you should get a zip file to download — save it in the same directory as your html and css. implementing the code in your demo at this point, unzip the webfont kit you just generated. inside the unzipped directory you'll see three useful items: multiple versions of each font: (...
...ss simple by roger johansson shows what to do in more detail. note: you can also specify particular font-variant and font-stretch values for your web fonts. in newer browsers, you can also specify a unicode-range value, which is a specific range of characters you want to use out of the web font — in supporting browsers, only the specified characters will be downloaded, saving unnecessary downloading. creating custom font stacks with unicode-range by drew mclellan provides some useful ideas on how to make use of this. variable fonts there is a newer font technology available in browsers called variable fonts — these are fonts that allow many different variations of a typeface to be incorporated into a single file, rather than having a separate font file for every width, weight, or style.
How do you make sure your website works properly? - Learn web development
the network tool reported a "404". it turns out that we made a typo in our html code: unicorn_pics.png rather than unicorn_pic.png. so correct the typo in your code editor by changing the image's src attribute: save, push to the server, and reload the page in your browser: there you go! let's look at the http statuses again: 200 for / and for unicorn_pic.png means that we succeeded in reloading the page and the image. 304 for basic.css means that this file has not changed since the last request, so the browser can use the file in its cache rather than receiving a fresh copy. so we fixed the error and learned a few http statuses along the way! frequent errors the most frequent errors that we find are these: typos in the address we wanted to type http://demozilla.examplehostingprov...
...rors the most frequent errors that we find are these: typos in the address we wanted to type http://demozilla.examplehostingprovider.net/ but typed too fast and forgot an “l”: the address cannot be found. indeed. 404 errors many times the error just results just from a typo, but sometimes maybe you either forgot to upload a resource or you lost your network connection while you were uploading your resources. first check the spelling and accuracy of the file path, and if there's still a problem, upload your files again. that will likely fix the problem. javascript errors someone (possibly you) added a script to the page and made a mistake. this will not prevent the page from loading but you will feel something went wrong. open the console (tools ➤ web developer ➤ web console) an...
How do I use GitHub Pages? - Learn web development
es to go in. click plus (+) in the top right of the github homepage, then choose new repository. on this page, in the repository name box, enter a name for your code repository, for example my-repository. also fill in a description to say what your repository is going to contain. 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. you should see two lines of code listed in this section. copy the whole of the first line, paste it into the command line, and press enter. the command should look something like this: git remote add origin https://github.com/chrisdavidmills/my-repository.git ...
... repository from the command line. you should see two lines of code listed in this section. copy the whole of the first line, paste it into the command line, and press enter. the command should look something like this: git remote add origin https://github.com/chrisdavidmills/my-repository.git next, type the following two commands, pressing enter after each one. these prepare the code for uploading to github, and ask git to manage these files. git add --all git commit -m 'adding my files to my repository' finally, push the code up to github by going to the github web page you're on and entering into the terminal the second of the two commands we saw the …or push an existing repository from the command line section: git push -u origin master now you need to turn github pages on f...
HTML forms in legacy browsers - Learn web development
(network issues, script conflicts, etc.). but for javascript, if you work with unobstructive javascript in mind, if polyfills are missing, it's no big deal. the best way to polyfill missing api is by using the modernizr library and its spin-off project: yepnope. modernizr is a library that allows you to test the availability of functionality in order to act accordingly. yepnope is a conditional loading library. here is an example: modernizr.load({ // this tests if your browser supports the html5 form validation api test : modernizr.formvalidation, // if the browser does not support it, the following polyfill is loaded nope : form-validation-api-polyfill.js, // in any case, your core app file that depends on that api is loaded both : app.js, // once both files are loaded, this...
...n () { app.init(); } }); the modernizr team conveniently maintains a list of great polyfills. just pick what you need. note: modernizr has other awesome features to help you in dealing with unobstructive javascript and graceful degradation techniques. please read the modernizr documentation. pay attention to performance even though scripts like modernizr are very aware of performance, loading a 200 kilobyte polyfill can affect the performance of your application. this is especially critical with legacy browsers; many of them have a very slow javascript engine that can make the execution of all your polyfills painful for the user. performance is a subject on its own, but legacy browsers are very sensitive to it: basically, they are slow and the more polyfills they need, the more javasc...
Sending forms through JavaScript - Learn web development
let's first talk about why this requires a different approach. ...
...s to read the file reader.addeventlistener( "load", function () { file.binary = reader.result; } ); // at page load, if a file is already selected, read it. if( file.dom.files[0] ) { reader.readasbinarystring( file.dom.files[0] ); } // if not, read the file once the user selects it. ...
Use JavaScript within a webpage - Learn web development
ter events (like mouse events or touch events), duplicate the functionality with keyboard events. test your site using a keyboard only. don't set nor even guess time limits. it takes extra time to navigate with the keyboard or hear content read out. you can hardly ever predict just how long it will take for users or browsers to complete an process (especially asynchronous actions such as loading resources). keep animations subtle and brief with no flashing. flashing is annoying and can cause seizures. additionally, if an animation lasts more than a couple seconds, give the user a way to cancel it. let users initiate interactions. that means, don't update content, redirect, or refresh automatically. don't use carousels or display popups without warning. have a plan b for users without ...
...animation lasts more than a couple seconds, give the user a way to cancel it. let users initiate interactions. that means, don't update content, redirect, or refresh automatically. don't use carousels or display popups without warning. have a plan b for users without javascript. people may have javascript turned off to improve speed and security, and users often face network issues that prevent loading scripts. moreover, third-party scripts (ads, tracking scripts, browser extensions) might break your scripts. at a minimum, leave a short message with <noscript> like this: <noscript>to use this site, please enable javascript.</noscript> ideally, replicate the javascript functionality with html and server-side scripting when possible. if you're only looking for simple visual effects, c...
What’s in the head? Metadata in HTML - Learn web development
anced feature, and you won't be expected to have knowledge of this to progress through the course. the main purpose here is to let you know what such things are, in case you come across them while browsing other websites' source code. note: if your site uses a content security policy (csp) to enhance its security, the policy applies to the favicon. if you encounter problems with the favicon not loading, verify that the content-security-policy header's img-src directive is not preventing access to it. applying css and javascript to html just about all websites you'll use in the modern day will employ css to make them look cool, and javascript to power interactive functionality, such as video players, maps, games, and more. these are most commonly applied to a web page using the <link> element...
...the javascript you want to load, and defer, which basically instructs the browser to load the javascript at the same time as the page's html. this is useful as it makes sure that the html is all loaded before the javascript runs, so that you don't get errors resulting from javascript trying to access an html element that doesn't exist on the page yet. there are actually a number of ways to handle loading javascript on your page, but this is the most foolproof one to use for modern browsers (for others, read script loading strategies). <script src="my-js-file.js" defer></script> note: the <script> element may look like an empty element, but it's not, and so needs a closing tag. instead of pointing to an external script file, you can also choose to put your script inside the <script> elem...
Adding vector graphics to the Web - Learn web development
o, please read images in html. <img src="equilateral.svg" alt="triangle with all three sides equal" height="87" width="100" /> pros quick, familiar image syntax with built-in text equivalent available in the alt attribute. you can make the image into a hyperlink easily by nesting the <img> inside an <a> element. the svg file can be cached by the browser, resulting in faster loading times for any page that uses the image loaded in the future. cons you cannot manipulate the image with javascript. if you want to control the svg content with css, you must include inline css styles in your svg code. (external stylesheets invoked from the svg file take no effect.) you cannot restyle the image with css pseudoclasses (like :focus). troubleshooting and cross-browser support...
...vg inline, or inlining svg. make sure your svg code snippet begins and ends with the <svg></svg> tags (don't include anything outside those.) here's a very simple example of what you might paste into your document: <svg width="300" height="200"> <rect width="100%" height="100%" fill="green" /> </svg> pros putting your svg inline saves an http request, and therefore can reduce a bit your loading time. you can assign classes and ids to svg elements and style them with css, either within the svg or wherever you put the css style rules for your html document. in fact, you can use any svg presentation attribute as a css property. inlining svg is the only approach that lets you use css interactions (like :focus) and css animations on your svg image (even in your regular stylesheet.) you ca...
From object to iframe — other embedding technologies - Learn web development
hat doesn't support <iframe>s these days. sandbox this attribute, which works in slightly more modern browsers than the rest of the <iframe> features (e.g. ie 10 and above) requests heightened security settings; we'll say more about this in the next section. note: in order to improve speed, it's a good idea to set the iframe's src attribute with javascript after the main content is done with loading. this makes your page usable sooner and decreases your official page load time (an important seo metric.) security concerns above we mentioned security concerns — let's go into this in a bit more detail now. we are not expecting you to understand all of this content perfectly the first time; we just want to make you aware of this concern, and provide a reference to come back to as you get mo...
...re, and there are also best practices to consider — we'll cover some of these below. clickjacking is one kind of common iframe attack where hackers embed an invisible iframe into your document (or embed your document into their own malicious website) and use it to capture users' interactions. this is a common way to mislead users or steal sensitive data. a quick example first though — try loading the previous example we showed above into your browser — you can find it live on github (see the source code too.) you won't actually see anything displayed on the page, and if you look at the console in the browser developer tools, you'll see a message telling you why. in firefox, you'll get told load denied by x-frame-options: /docs/glossary does not permit framing. this is because the develo...
Responsive images - Learn web development
al size (a raster image is a set number of pixels wide and a set number of pixels tall, as we saw when we looked at vector graphics). this is called the resolution switching problem. conversely, it is unnecessary to display a large image on a screen significantly smaller than the size it was meant for. doing so can waste bandwidth; in particular, mobile users don't want to waste bandwidth by downloading a large image intended for desktop, when a small image would do for their device. ideally, you would have multiple resolutions available and serve the appropriate size depending upon the device accessing the data on the website. to make things more complicated, some devices have high resolution screens that need larger images than you might expect to display nicely. this is essentially the same ...
...x devtools's network monitor tab. older browsers that don't support these features will just ignore them. instead, those browsers will go ahead and load the image referenced in the src attribute as normal. note: in the <head> of the example linked above, you'll find the line <meta name="viewport" content="width=device-width">: this forces mobile browsers to adopt their real viewport width for loading web pages (some mobile browsers lie about their viewport width, and instead load pages at a larger viewport width then shrink the loaded page down, which is not very helpful for responsive images or design). resolution switching: same size, different resolutions if you're supporting multiple display resolutions, but everyone sees your image at the same real-world size on the screen, you can al...
Client-side storage - Learn web development
test your html page in a browser. you can see our finished version running live here. note: there is another, slightly more complex example to explore at using the web storage api. note: in the line <script src="index.js" defer></script> of the source for our finished version, the defer attribute specifies that the contents of the <script> element will not execute until the page has finished loading. storing complex data — indexeddb the indexeddb api (sometimes abbreviated idb) is a complete database system available in the browser in which you can store complex related data, the types of which aren't limited to simple values like strings or numbers. you can store videos, images, and pretty much anything else in an indexeddb instance. however, this does come at a cost: indexeddb is muc...
... a few places, so we've declared it globally here to make things easier. next, add the following to the bottom of your code: window.onload = function() { }; we will write all of our subsequent code inside this window.onload event handler function, called when the window's load event fires, to make sure we don't try to use indexeddb functionality before the app has completely finished loading (it could fail if we don't). inside the window.onload handler, add the following: // open our database; it is created if it doesn't already exist // (see onupgradeneeded below) let request = window.indexeddb.open('notes_db', 1); this line creates a request to open version 1 of a database called notes_db. if this doesn't already exist, it will be created for you by subsequent code. you...
Fetching data from the server - Learn web development
the concept and look at technologies that make it possible, such as xmlhttprequest and the fetch api. prerequisites: javascript basics (see first steps, building blocks, javascript objects), the basics of client-side apis objective: to learn how to fetch data from the server and use it to update the contents of a web page. what is the problem here? originally page loading on the web was simple — you'd send a request for a website to a server, and as long as nothing went wrong, the assets that made the web page would be downloaded and displayed on your computer. the trouble with this model is that whenever you want to update any part of the page, for example, to display a new set of products or load a new page, you've got to load the entire page again. this is...
...th. this may not be such a big issue on a desktop on a broadband connection, but it's a major issue on mobile devices and in developing countries that don't have ubiquitous fast internet service. to speed things up even further, some sites also store assets and data on the user's computer when they are first requested, meaning that on subsequent visits they use the local versions instead of downloading fresh copies when the page is first loaded. the content is only reloaded from the server when it has been updated. a basic ajax request let's look at how such a request is handled, using both xmlhttprequest and fetch. for these examples, we'll request data out of a few different text files and use them to populate a content area. this series of files will act as our fake database; in a real ...
HTML performance features - Learn web development
basic computer literacy, basic software installed, and basic knowledge of client-side web technologies. objective: to learn about the impact of html elements and attributes on web performance optimization. ...
... how do users perceive performance? ...
Web performance - Learn web development
for working through them; you should definitely start with the first one. the "why" of web performance this article discusses why web performance is important for accessibility, user experience and your business goals. what is web performance? you know web performance is important, but what is constitutes web performance? this article introduces the components of performance, from web page loading and rendering, including how your content makes it into your users browser to be viewed, to what groups of people we need to consider when thinking about performance, how do users perceive performance? more important than how fast your website is in milliseconds, is how fast your users perceive your site to be. these perceptions are impacted by actual page load time, idling, responsiveness to u...
...ple we need to consider when thinking about performance, how do users perceive performance? more important than how fast your website is in milliseconds, is how fast your users perceive your site to be. these perceptions are impacted by actual page load time, idling, responsiveness to user interaction, and the smoothness of scrolling and other animations. in this article, we discuss the various loading metrics, animation, and responsiveness metrics, along with best practices to improve user perception, if not the actual timings. measuring performance now that you understand a few performance metrics, we take a deeper dive into performance tools, metrics, and apis and how we can make performance part of the web development workflow. multimedia: images the lowest hanging fruit of web perfo...
Ember resources and troubleshooting - Learn web development
fairly light in their responsibilities, delegating to components and services where possible. what is the purpose of routes? a route represents part of the url when a user navigates from place to place in the app. a route has only a couple responsibilities: load the minimally required data to render the route (or view-sub-tree). gate access to the route and redirect if needed. handle loading and error states from the minimally required data. a route only has 3 lifecycle hooks, all of which are optional: beforemodel — gate access to the route. model — where data is loaded. aftermodel — verify access. last, a route has the ability to handle common events resulting from configuring the model: loading — what to do when the model hook is loading. error — what t...
...ta. a route only has 3 lifecycle hooks, all of which are optional: beforemodel — gate access to the route. model — where data is loaded. aftermodel — verify access. last, a route has the ability to handle common events resulting from configuring the model: loading — what to do when the model hook is loading. error — what to do when an error is thrown from model. both loading and error can render default templates as well as customized templates defined elsewhere in the application, unifying loading/error states. more information on everything a route can do is found in the api documentation. previous overview: client-side javascript frameworks next in this module introduction to client-side frameworks framework main features react getting starte...
Message manager overview
since javascript modules are singletons they will only be executed once per process even when they are loaded in multiple frame scripts. the jsm can then use the child process message ...
...since javascript modules are singletons they will only be executed once per process even when they are loaded in multiple frame scripts. the jsm can then use the child process message manager to exchange messages with the parent process message manager. this can be useful fo...
mozbrowsersecuritychange
curity state. this may mean that the request is being loaded as part of a page in which some content was received over an insecure channel. secure: indicates that the data corresponding to the request was received over a secure channel. insecure: indicates that the data corresponding to the request was received over an insecure channel. trackingstate a domstring representing the current loading state of tracking content. possible values are: loaded_tracking_content: indicates that the tracking content has been loaded. blocked_tracking_content: indicates that the tracking content has been blocked from loading. mixedstate a domstring representing the current loading state of mixed active content. possible values are: loaded_mixed_active_content: indicates that the mixed ac...
... extendedvalidation a boolean indicating if the current ssl certificate is an extended validation certificate (true) or not (false). trackingcontent a boolean indicating if tracking content is present on the current page (true) or not (false). ...
Gecko SDK
ing the xpidl compiler/linker and the latest npapi.h. get the sdk updates there is no need to download or rebuild the gecko sdk corresponding to security updates of mozilla (e.g., mozilla 1.7.3) since the headers and glue libs in the gecko sdk are usually not changed as a result of security updates. you do have to get and distribute the newest gecko components (gklayout.dll etc.), though. downloading for gecko versions before 2.0, you should choose the gecko sdk version for the earliest version of mozilla you wish to target. for gecko versions 2.0 and higher, you must recompile your component for each release as cross-version compatibility is no longer supported. in addition to the below versions, you can find other versions (including beta) here: xulrunner releases (files include "sdk" in...
...tions, and nspr functions (under include/) import libraries or shared libraries (under lib/) static utility libraries (under lib/) various tools (under bin/) for more information about safely linking xpcom components using the xpcom "glue" library, see xpcom glue. using the mozilla build system with the sdk it's possible to use the mozilla build system with the sdk. this can be done by downloading the source code for firefox and using the --with-libxul-sdk option to configure. resources static xpidl.exe (non-official) if you are looking for a static linked xpidl.exe, you can download here. mac intel gecko 1.8 sdk the official mac 1.8 sdk is a ppc version. this is an unofficial intel build. ...
How Mozilla determines MIME Types
ons to register additional mappings. the key of the category entry is the extension without leading dot, the value is the mime type. the extension must be lowercase. if no ext-to-type-mapping category is found, the externalhelperappservice returns application/x-extension-ext, where ext is the extension of the file. helper applications a somewhat related issue are the helper applications. when loading an uri with a type that mozilla can not handle, a helper app dialog shows up, and the displayed information comes from these sources: ask the os for a handler of the given <extension, mime type> pair. note that the extension here comes from the content-disposition header if present, and from the url itself otherwise. this is where the listed "default application" comes from. the "data source"...
...his fails, the data source is searched via the extension (content-disposition as above). ...
AddonInstall
s may be null if the add-on is coming from the internet and has yet to be downloaded. progress integer the progress of any necessary downloads. maxprogress integer the expected size of any necessary downloads or -1 if unknown. certificate nsix509cert if the add-on to be installed is signed this is the certificate of the signer. only available after downloading is complete. certname string if the add-on to be installed is signed this is the simple display name of the signer. existingaddon addon the addon that this install will update. may be null if it isn't updating anything installed. this is guaranteed to be correct after downloading is complete but may be set earlier. addon addon the full addon that this ...
... methods install() starts or continues the install process. ...
AddonManager
being found), null is passed back instead. addonlistcallback() a callback that is passed an array of addons void addonlistcallback( in addon addons[] ) parameters addons the array of addons passed back from the asynchronous request constants addoninstall states constant description state_available an install that is waiting to be started. state_downloading an install that is in the process of being downloaded. state_checking an install that is checking for updated information. state_downloaded an install that has finished downloading and is ready to install. state_download_failed an install that failed to download. state_installing an install that is in the process of being installed. stat...
...rmed automatically in the background. update_when_addon_installed an update check performed when a new add-on has been installed. update status values constant description update_status_no_error no error was encountered. update_status_timeout the update check timed out. update_status_download_error there was an error while downloading the update information. update_status_parse_error the update information was malformed in some way. update_status_unknown_format the update was not in any known format. update_status_security_error the update information was not correctly signed or there was an ssl error. auto update values constant description autoupdate_disable ...
Downloads.jsm
the downloads.jsm javascript code module provides a single entry point to interact with the downloading capabilities of the platform, including starting new downloads, controlling ongoing downloads, and retrieving download-related configuration. 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. priva...
... function does not cause the list of public downloads to be reloaded from the previous session. the summary will behave as if no downloads are present until the getlist() method is called. promise<downloadsummary> getsummary(atype); parameters atype this can be downloads.public, downloads.private, or downloads.all. promise resolves to the requested downloadsummary object. examples downloading to a local file this example downloads an html file without showing progress, handling errors programmatically. components.utils.import("resource://gre/modules/downloads.jsm"); components.utils.import("resource://gre/modules/osfile.jsm") components.utils.import("resource://gre/modules/task.jsm"); task.spawn(function () { yield downloads.fetch("http://www.mozilla.org/", ...
WebRequest.jsm
onbeforesendheaders. see bug 1176092. handlerbehaviorchanged() is not supported. requestid is not included in the argument passed to the listener. ...
... e.url); } filtering this example logs urls for requests under "https://developer.mozilla.org/": let {webrequest} = cu.import("resource://gre/modules/webrequest.jsm", {}); cu.import("resource://gre/modules/matchpattern.jsm"); let pattern = new matchpattern("https:/developer.mozilla.org/*"); webrequest.onbeforerequest.addlistener(logurl, {urls: pattern}); function logurl(e) { console.log("loading: " + e.url); } this listener will be invoked for requests matching any of the three patterns, where the resource type is "stylesheet" or "image": let {webrequest} = cu.import("resource://gre/modules/webrequest.jsm", {}); cu.import("resource://gre/modules/matchpattern.jsm"); let pattern = new matchpattern(["https://mozorg.cdn.mozilla.net/*", "https://mdn.mozillad...
Localization and Plurals
on input it would be good to keep this list updated with all the words that need plural forms. people using the extension can then copy/paste this input. ...
...for getting the correct plural forms is provided by a javascript module, pluralform.jsm. this module provides a couple methods for localizing to the browser's current locale as well as getting methods to localize to a desired plural rule. the latter ability of specifying a plural rule is useful for extensions because the extension doesn't necessarily have to be localized to the browser's locale. loading pluralform.jsm loading the pluralform module from javascript is simple with components.utils.import. just put the following line somewhere that will be evaluated before you want to use pluralform. at the top of your javascript file is fine. components.utils.import("resource://gre/modules/pluralform.jsm"); methods: get these methods make use of the browser's current locale specified by chrome:...
Mozilla Style System
the handling of those computed values is the responsibility of other parts of the code. architecture the style system is split in half rather neatly. in one half (the backend) are the sources of specified style data, and in the other half (the frontend) is the code that turns the specified values into computed values. ...
... this: if (aframe->getstyledisplay()->mopacity < 1.0f) return pr_true; or like this: const nsstyleposition *stylepos = aframe->getstyleposition(); if (stylepos->mwidth.getunit() == estyleunit_coord) { nscoord w = stylepos->mwidth.getcoordvalue(); ... } else if (stylepos->mwidth.getunit() == estyleunit_percent) { ... rule tree style data computation css style sheet backend loading parsing data structures cascading html mapped attribute backend css style attribute backend handling of dynamic changes see also mozilla style system documentation (2002) style system tech talk (2002) ...
Investigating leaks using DMD heap scan mode
t why the cycle collector could not collect the window, using the find_roots.py script from the heapgraph repository. the command to invoke this looks like this: python $heapgraph/find_roots.py $cclog $winaddr this may take a few seconds. it will eventually produce some output. you'll want to save a copy of this output for later. ...
...d suspicious. the first thing i did to try to confirm that this was the source of the leak was pass the address of this object into the cycle collector analysis log, find_roots.py, that we used at an earlier step. that gave a result that contained this: 0x7f0882fe3230 [fragmentorelement (xhtml) script [...] --[mnodeinfo]--> 0x7f0897431f00 [nodeinfo (xhtml) script] [...] --[mloadingasyncrequests]--> 0x7f0892f29630 [scriptloadrequest] this confirms that this block is actually a scriptloadrequest. secondly, notice that the load request is being held alive by the very same script element that is causing the window leak! this strongly suggests that there is a cycle of strong references between the script element and the load request. i then added the missing field to the traver...
Gecko Profiler FAQ
tting used to profiling and analyzing real pages more. :-) what's the best way to profile startup performance? install the gecko profiler add-on. quit the browser. start the browser with the environment variable moz_profiler_startup=1 set. as soon as startup is done, collect a profile. what's the best way to do repeatable tests? ie: i want to measure perf of loading the same page with different stylo configurations. probably by using talos, especially if you want to measure and not profile. you can make your own talos pageload test which has just the one page that you’re interested in in its manifest. what actually means the percentage of the running time? the percentage of samples with stacks under this sta...
...at's the bulk of our users)? [mstange] in my opinion, as long as you double-check that the problems you find are actually present on windows, it doesn’t matter much what platform you find them on. [ehsan] that being said, we do see a lot of windows-specific issues that you will not find on other platforms, for example sometimes code calls into a windows api that requires loading a dll the first time you call it that takes 10s of milliseconds to finish, etc. unless if you profile on windows you will never find those specific issues. and when you get to the platform specific parts of the browser stack (such as graphics, media, etc.) then profiling on windows would be certainly a lot more valuable than on other platforms. should i profile known to ...
Profiling with the Firefox Profiler
e expected size of the output is around 100 of mb. to add symbols to your build, you need to call ./scripts/profile-symbolicate.py available in b2g repository. $ gecko_objdir=<objdir> product_out=<objdir> target_tools_prefix= \ ./scripts/profile-symbolicate.py -o run.symb.cleo run.cleo clone cleopatra and start the server with ./run_webserver.sh. access cleopatra from your web browser by loading the page localhost:8000, and upload run.symb.cleo to render the profile with most of the symbol information. native stack vs. label stack the profiler periodically samples the stack of the selected threads in firefox and collects a stack trace. this stack trace is the combined stack of three different stacks: the native stack, the javascript stack, and the label stack. native stack the nativ...
...s like auto_profiler_label_dynamic. because of the non-zero overhead of the instrumentation, the sample label shouldn't be placed inside hot loops. a profile reporting that a large portion is spent in "unknown" code indicates that the area being executed doesn't have any sample labels. as we focus on using this tool and add additional sample labels coverage should improve. sharing, saving and loading profiles after capturing and viewing a profile you will see "share..." and "save as file..." buttons in the top-right of the window. sharing will upload your profile to profiler.firefox.com and make it public. more information on sharing profiles is available. profiling a hung process it is possible to get profiles from hung firefox processes using lldb1. after the process has hung, attach ...
about:memory
enerated data contains privacy-sensitive details such as the full list of the web pages you have open in other tabs. if you do not wish to share this information, you can select the "anonymize" checkbox before clicking on "measure and save..." or "measure...". this will cause the privacy-sensitive data to be stripped out, but it may also make it harder for others to investigate the memory usage. loading memory reports from file the easiest way to load memory reports from file is to use the "load..." button. you can also use the "load and diff..." button to get the difference between two memory report files. single memory report files can also be loaded automatically when about:memory is loaded by appending a file query string, for example: about:memory?file=/home/username/reports.json.gz th...
...le the easiest way to load memory reports from file is to use the "load..." button. you can also use the "load and diff..." button to get the difference between two memory report files. single memory report files can also be loaded automatically when about:memory is loaded by appending a file query string, for example: about:memory?file=/home/username/reports.json.gz this is most useful when loading memory reports files obtained from a firefox os device. memory reports are saved to file as gzipped json. these files can be loaded as is, but they can also be loaded after unzipping. interpreting memory reports almost everything you see in about:memory has an explanatory tool-tip. hover over any button to see a description of what it does. hover over any measurement to see a description of wh...
An overview of NSS Internals
pecting, and use the correct template for parsing, based on the context of your software's interaction. data described as pem is a base64 encoded presentation of der, usually wrapped between human readable begin/end lines. nss prefers the binary presentation, but is often capable to use base64 or ascii presentations, especially when importing data from files. a recent development adds support for loading external pem files that contain private keys, in a software library called nss-pem, which is separately available, but should eventually become a core part of nss. looking at the code level, nss deals with blocks of raw data all the time. the common structure to store such an untyped block is secitem, which contains a size and an untyped c pointer variable. when dealing with memory, nss mak...
...layer and an ssl library layer. the mozilla applications define a third layer where application specific processing is performed. you can find more details in the nspr reference documents. nss occassionally has to create outbound network connections, in addition to the connections requested by the application. examples are retrieving ocsp (online certificate status protocol) information or downloading a crl (certificate revocation list). however, nss doesn't have an implementation to work with network proxies. if you must support proxies in your application, you are able to register your own implementation of an http request callback interface, and nss can use your application code that supports proxies. when using hashing, encryption, and decryption functions, it is possible to stream data...
NSS tools : certutil
d. -e check a certificate's signature during the process of validating a certificate. --email email-address specify the email address of a certificate to list. used with the -l command option. --extgeneric oid:critical-flag:filename[,oid:critical-flag:filename]... add one or multiple extensions that certutil cannot encode yet, by loading their encodings from external files. · oid (example): 1.2.3.4 · critical-flag: critical or not-critical · filename: full path to a file containing an encoded extension -f password-file specify a file that will automatically supply the password to include in a certificate or to access a certificate database. this i...
...nt can search a specific token or all tokens. * if there are multiple key types available, then the -k key-type argument can search a specific type of key, like rsa, dsa, or ecc. listing security modules the devices that can be used to store certificates -- both internal databases and external devices like smart cards -- are recognized and used by loading security modules. the -u command option lists all of the security modules listed in the secmod.db database. the path to the directory (-d) is required. $ certutil -u -d sql:/home/my/sharednssdb slot: nss user private key and certificate services token: nss certificate db slot: nss internal cryptographic services token: nss generic crypto services adding ce...
Network Security Services
curity-enabled client and server applications. applications built with nss can support ssl v3, tls, pkcs #5, pkcs #7, pkcs #11, pkcs #12, s/mime, x.509 v3 certificates, and other security standards. for detailed information on standards supported, see overview of nss. for a list of frequently asked questions, see the faq. nss is available under the mozilla public license. for information on downloading nss releases as tar files, see download pki source. if you're a developer and would like to contribute to nss, you might want to read the documents highlevel overview of internal details of nss and getting started with nss. documentation background information overview of nss provides a brief summary of nss and its capabilities. nss faq answers basic...
...ite archived version. describes how to run the standard nss tests. nss performance reports archived version. links to performance reports for nss 3.2 and later releases. encryption technologies available in nss 3.11 archived version. lists the cryptographic algorithms used by nss 3.11. nss 3.1 loadable root certificates archived version. describes the scheme for loading root ca certificates. cert7.db archived version. general format of the cert7.db database. pkcs #11 information documentation on pkcs #11 modules implementing pkcs #11 for nss the strings nss uses to load pkcs #11 modules pkcs #11 faq using the jar installation manager to install a pkcs #11 cryptographic module pkcs #11 conformance testing - ...
Scripting Java
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. however, there are a few instances where that is not enough: many apis in java work by providing interfaces that clients must ...
... the method is closer to the argument types than the other: js> o.g(3,4) js:"<stdin>", line 2: the choice of java method overload.g matching javascript argument types (number,number) is ambiguous; candidate methods are: class java.lang.string g(java.lang.string,int) class java.lang.string g(int,java.lang.string) see java method overloading and liveconnect 3 for a more precise definition of overloading semantics. 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. however, there are a few instances where that is not enough: many apis in java work by providing interfaces that clients must implement. one example of this is the thread class: its constru...
Index
form, fun. 224 js_decompilescript jsapi reference, reference, référence(2), spidermonkey js_decompilescript returns the source code of script. if script is a function, it calls js_decompilefunction. otherwise, it returns the original source code of the script. if the script is not cached, it tries to load the source from file, and returns nullptr if an error happened while loading. 225 js_decompilescriptobject jsapi reference, needscontent, spidermonkey fixme: please provide a description for this function. 226 js_deepfreezeobject jsapi reference, reference, référence(2), spidermonkey js_deepfreezeobject freezes obj, and all objects it refers to, recursively. this will not recurse through non-extensible objects, on the assumption...
... automatically by the spidermonkey js command-line interpreter when you start the program. 525 spidermonkey build documentation build documentation, guide, spidermonkey use these instructions to build the latest spidermonkey source code. 526 rebranding spidermonkey (1.8.5) build documentation, spidermonkey after installing the build pre-requisites and downloading the spidermonkey source tarball issue the following commands at the terminal: 527 spidermonkey internals guide, javascript, needsupdate, spidermonkey at heart, spidermonkey is a fast interpreter that runs an untyped bytecode and operates on values of type js::value—type-tagged values that represent the full range of javascript values. in addition to the interpreter, spiderm...
Setting up an update server
be sure that you use the one that matches your machine's configuration. ...
...since the transfer is entirely local this should finish quickly, and a "restart to update" button should appear. click it to restart and apply the update. ...
Gecko events
is supported: yes event_document_attributes_changed the document wide attributes of the document object have changed. is supported: no event_document_content_changed the contents of the d...
... is supported: yes event_document_attributes_changed the document wide attributes of the document object have changed. ...
Feed content access API
xtconstruct represents text values in a feed; includes functions that let you fetch the text as plain text or html. nsiscriptableunescapehtml a utility class that unescapes html strings. example: reading a feed from the web it's actually quite easy to read and parse a feed. use an xmlhttprequest to load the feed, then pass its string to an nsifeedprocessor to parse the feed. ...
...however, you could also parse it from a file using parsefromstream(), or directly from an url using parseasync(). the actual processing of the parsed feed is done by a method called handleresult() on the feedtestresultlistener object. that code looks like this: feedtestresultlistener.prototype = { han...
XPCOM changes in Gecko 2.0
changed, or one or more extensions was added, removed, enabled, or disabled, it was necessary to throw away all existing component registrations, then restart the application (what we call the "extension manager restart") during its startup process. this was necessary in order to ensure that any components that should no longer be available are disposed of properly, and to re-register everything, loading any new components that may be needed. in theory, this is invisible to the user, but it's a costly process, since every component needs to be loaded and executed, then unloaded, then reloaded again during the restart. on top of that, with the ongoing work to make firefox multithreaded, content processes either need to register components on a per-process basis, or somehow share a component cache ...
...component cache on startup, we read the application's component registrations out of its manifest file and load those components. this gets enough of xpcom loaded and running that we can then load the extension manager and perform the necessary installing, uninstalling, and updating of any installed extensions. once that's done, the extensions can then be loaded by simply reading their manifests, loading their components, and continuing the startup process, all without having to restart the browser. electrolysis content processes can simply read the component registrations during startup. xpcnativewrapper changes you can't disable xpcnativewrappers from your manifest specifying xpcnativewrappers=no in your manifest (that is, xpcnativewrapper automation) is no longer supported. this was always int...
Components.utils.import
uced in firefox 3 and is used for sharing code between different scopes easily. for example, you can import xpcomutils.jsm to avoid copy/pasting long xpcom component registration boilerplate in your component files. see using javascript code modules for more details. note: prior to gecko 2.0, javascript code modules could only be loaded using file: or resource: urls. gecko 2.0 adds support for loading modules from chrome: urls, even those inside jar archives. syntax components.utils.import(url [, scope]); // or, if you use a tool such as jslint which reports compiler errors for the above, components.utils["import"](url [, scope]); parameters url a string of the url of the script to be loaded. the url must point to a file on the disk, possibly in a jar. scope an optional object to i...
...value is discouraged since it grants access to the module's internal properties which are not part of its public api. import throws if it encounters an error (like a syntax error) in the file it reads. example components.utils.import("resource://gre/modules/xpcomutils.jsm", this); difference from mozijssubscriptloader the differences from mozijssubscriptloader: the behavior when importing/loading the same code from different locations: the subscript loader evaluates the specified code each time it is invoked, with the caller's global object. components.utils.import evaluates the code of each module only once, in its own scope. for example: var scope1 = {}, scope2 = {}; components.utils.import("resource://gre/modules/json.jsm", scope1); components.utils.import("resource://gre/module...
imgILoader
pports last changed in gecko 8.0 (firefox 8.0 / thunderbird 8.0 / seamonkey 2.5) implemented by @mozilla.org/image/loader;1 as a service: var imgiloader = components.classes["@mozilla.org/image/loader;1"] .getservice(components.interfaces.imgiloader); method overview imgirequest loadimage(in nsiuri auri, in nsiuri ainitialdocumenturl, in nsiuri areferreruri, in nsiprincipal aloadingprincipal, in nsiloadgroup aloadgroup, in imgidecoderobserver aobserver, in nsisupports acx, in nsloadflags aloadflags, in nsisupports cachekey, in imgirequest arequest, in nsichannelpolicy channelpolicy); imgirequest loadimagewithchannel(in nsichannel achannel, in imgidecoderobserver aobserver, in nsisupports cx, out nsistreamlistener alistener); boolean supportimagewithmimetype(in string mim...
...n nsisupports cx, out nsistreamlistener alistener); boolean supportimagewithmimetype(in string mimetype); constants constant value description load_cors_anonymous 1 << 16 load_cors_use_credentials 1 << 17 methods loadimage() start the load and decode of an image. imgirequest loadimage( in nsiuri auri, in nsiuri ainitialdocumenturl, in nsiuri areferreruri, in nsiprincipal aloadingprincipal, in nsiloadgroup aloadgroup, in imgidecoderobserver aobserver, in nsisupports acx, in nsloadflags aloadflags, in nsisupports cachekey, in imgirequest arequest, in nsichannelpolicy channelpolicy ); parameters auri the uri to load. ainitialdocumenturl areferreruri the 'referring' uri. aloadingprincipal the principal of the loading document. aloadgroup loadgroup to put the...
nsICategoryManager
var entry = item.queryinterface(components.interfaces.nsisupportscstring) entries.push(entry.tostring()); } entries.sort(); var entriesstring = entries.join("\n"); dump(entriesstring + "\n"); disable currently loaded plugins by type this snippet here shows how to disable plugins that are currently loaded for the file type of pdf. the second portion of this snippet disables plugins from loading in the future, it does not user the category manager but it is included for completness of the example. var content_type = 'application/pdf'; // update the category manager in case the plugins are already loaded. let categorymanager = cc['@mozilla.org/categorymanager;1']; categorymanager.getservice(ci.nsicategorymanager).deletecategoryentry('gecko-content-viewers', content_type, false); // upd...
...gory manager but it is included for completness of the example. var content_type = 'application/pdf'; // update the category manager in case the plugins are already loaded. ...
nsIContentViewer
the history entry that the content viewer was stored in. the entry must have the docshells for all of the child documents stored in its child shell list. ...
...requestwindowclose() boolean requestwindowclose(); parameters none. return value missing description exceptions thrown missing exception missing description resetclosewindow() works in tandem with permitunload(), if the caller decides not to close() the window it indicated it will, it is the caller's responsibility to reset that with this method. ...
nsIDOMOfflineResourceList
onchecking nsidomeventlistener an event listener to be called when fetching the application cache manifest and checking for updates. onerror nsidomeventlistener an event listener to be called when an error occurs during the caching process. onnoupdate nsidomeventlistener an event listener to be called when there is no update to download. ondownloading nsidomeventlistener an event listener to be called when resources are being downloaded into the cache. onprogress nsidomeventlistener an event listener to be called periodically throughout the download process. onupdateready nsidomeventlistener an event listener to be called when a resource update is ready; this event is not currently used since versioned appli...
...s of the application cache. constants application cache state constants constant value description uncached 0 the object isn't associated with an application cache. idle 1 the application cache is not in the process of being updated. checking 2 the application cache manifest is being fetched and checked for updates. downloading 3 resources are being downloaded to be added to the cache. updateready 4 there is a new version of the application cache available. obsolete 5 the application cache group is now obsolete. methods mozadd() adds an item to the dynamically managed entries. the resource will be fetched and added to the application cache. void mozadd( in domstring uri ...
nsIDownloadManager
the system's downloads folder by default. 2: files are downloaded to the local path specified by the browser.download.dir preference. if this preference is invalid, the download directory falls back to the default. read only. constants constant value description download_notstarted -1 the download has not been started yet. download_downloading 0 the download is in the process of being downloaded. download_finished 1 download completed including any processing of the target file. download_failed 2 the download failed due to error. download_canceled 3 the user canceled the download. download_paused 4 the download is currently paused. download_queued 5 the do...
... downloaded. download_finished 1 download completed including any processing of the target file. download_failed 2 the download failed due to error. download_canceled 3 the user canceled the download. download_paused 4 the download is currently paused. download_queued 5 the download is in the queue but is not presently downloading. download_blocked_parental 6 the download has been blocked, either by parental controls or the virus scanner determining that a file is infected and cannot be cleaned. download_scanning 7 the download is being scanned by a virus checking utility. download_dirty 8 a virus was detected in the download. the target will most likely no longer exist. ...
nsIFrameLoader
1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) note: this interface works in tandem with the nsicontentview interface to manage frames across processes if electrolysis is in use to support per-frame processes. ...
...forwarding. capture whether or not to capture these events. activateremoteframe() activates the remote frame. void activateremoteframe(); parameters none. exceptions thrown throws an exception with non-remote frames. destroy() destroys the frame loader and everything inside it. this will clear the weak owner content reference. void destroy(); parameters none. loadframe() starts loading the frame. this method figures out what to load from the owner content in the frame loader. void loadframe(); parameters none. loaduri() loads the specified uri in this frame. behaves identically to loadframe(), except that this method lets you specify the uri to load. void loaduri( in nsiuri auri ); parameters auri the uri to load into the frame. sendcrossprocesskeyevent() crea...
nsIGlobalHistory3
ransition to places. method overview void adddocumentredirect(in nsichannel aoldchannel, in nsichannel anewchannel, in print32 aflags, in boolean atoplevel); unsigned long geturigeckoflags(in nsiuri auri); void seturigeckoflags(in nsiuri auri, in unsigned long aflags); methods adddocumentredirect() notifies the history system that the page loading via aoldchannel redirected to anewchannel. implementations should generally add the uri for aoldchannel to history for link coloring, but are advised not to expose it in the history user interface. this function is preferred if nsiglobalhistory3 is available. otherwise, nsiglobalhistory2.adduri() should be called with redirect=true. this function is preferred to nsiglobalhistory2.adduri() because...
...el ); parameters aoldchannel anewchannel aflags flags to add. these are defined by the history that is implementing this interface. atoplevel whether the uri is loaded in a top-level window. if false, the load is in a subframe. geturigeckoflags() get the gecko flags for this uri. these flags are used by gecko as hints to optimize page loading. not all histories have them; this need not be supported (just return ns_error_not_implemented. these flags are opaque and should not be interpreted by the history engine. unsigned long geturigeckoflags( in nsiuri auri ); parameters auri the nsiuri to get flags for. flags are defined by the history that is implementing this interface. return value the gecko flags for the uri. s...
nsIProtocolProxyService
c query is required. when this flag is passed to resolve, resolve may throw the exception ns_base_stream_would_block to indicate that it failed due to this flag being present. methods resolve() deprecated since gecko 18 this method has been removed in firefox 18. use resolveasync instead previous doc this method returns a nsiproxyinfo instance that identifies a proxy to be used for loading the given uri. otherwise, this method returns null indicating that a direct connection should be used. if this proxy is unavailable, getfailoverforproxy() may be called to determine the correct secondary proxy to be used. if the protocol handler for the given uri supports nsiproxiedprotocolhandler, then the nsiproxyinfo instance returned from resolve may be passed to the nsiproxiedprotocolhan...
...tional bits that do not correspond to a resolve_ flag are reserved for future use. return value an nsiproxyinfo object or null for a direct connection. note: if pac is configured, and the pac file has not yet been loaded, then this method will return a nsiproxyinfo instance with a type of "unknown" to indicate to the consumer that asyncresolve should be used to wait for the pac file to finish loading. otherwise, the consumer may choose to treat the result as type "direct" if desired. see nsiproxiedprotocolhandler.newproxiedchannel(). asyncresolve() this method is an asychronous version of the resolve method. unlike resolve, this method is guaranteed not to block the calling thread waiting for dns queries to complete. this method is intended as a substitute for resolve when the result is no...
nsISHistory
vel documents currently available in session history. read only. index long the index of the current document in session history. read only. maxlength long used to get/set the maximum number of toplevel documents, session history can hold for each instance. requestedindex long the index of the last document that started to load that is not yet finished loading. when the document finishes loading the value -1 is returned. read only. shistoryenumerator nsisimpleenumerator called to obtain a enumerator for all the documents stored in session history. the enumerator object thus returned by this method can be traversed using nsisimpleenumerator. to access individual history entries of the enumerator, perform the following steps: ...
...tory should be modified to the parameter index. exceptions thrown ns_ok history entry for the index is obtained successfully. ns_error_failure error in obtaining history entry for the given index. purgehistory() called to purge older documents from history. documents can be removed from session history for various reasons. for example to control memory usage of the browser, to prevent users from loading documents from history, to erase evidence of prior page loads and so on. void purgehistory( in long numentries ); parameters numentries the number of toplevel documents to be purged from history. during purge operation, the latest documents are maintained and older numentries documents are removed from history. exceptions thrown ns_error_failure numentries is invalid or out ...
nsIUpdate
this object also contains information about the update that the front end and other application services can use to learn more about what is going on. 1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview nsiupdatepatch getpatchat(in unsigned long...
...ther to show the update prompt which requires user confirmation when an update is found during a background update check. this overrides the default setting to download the update in the background. showsurvey boolean whether to show the survey link in the update prompt. the url must also be present in the app.update.surveyurl preference. state astring the state of the selected patch: "downloading" the update is being downloaded. "pending" the update is ready to be applied. "applying" the update is in the process of being applied. "succeeded" the update has been installed successfully. "download-failed" the update failed to be downloaded. "failed" installing the update failed. read only. statustext astring an optional message associated with the update. type astring the type of patch ...
nsIUploadChannel
the upload stream may only be set prior to the invocation of asyncopen on the channel. inherits from: nsisupports last changed in gecko 1.7 method overview void setuploadstream(in nsiinputstream astream, in acstring acontenttype, in long acontentlength); attributes attribute type description uploadstream nsiinputstream get the stream (to be) uploaded by this channel. read only. methods setuploadstream() sets a stream to be uploaded by this channel. ...
...s channel. most implementations of this interface require that the stream: implement threadsafe addref and release implement nsiinputstream.readsegments() implement nsiseekablestream.seek(). history here is that we need to support both streams that already have headers (for example, content-type and content-length) information prepended to the stream (by plugins) as well as clients (composer, uploading application) that want to upload data streams without any knowledge of protocol specifications. for this reason, we have a special meaning for the acontenttype parameter. void setuploadstream( in nsiinputstream astream, in acstring acontenttype, in long acontentlength ); parameters astream the stream to be uploaded by this channel. acontenttype if acontenttype is empty, the protocol will ...
nsIWebProgress
nsiwebprogress instances may be arranged in a parent-child configuration, corresponding to the parent-child configuration of their respective dom windows. however, in some cases a nsiwebprogress instance may not have an associated dom window. the parent-child relationship of nsiwebprogress instances is not made explicit by this interface, but the relationship may exist in some implementations. ...
...ew void addprogresslistener(in nsiwebprogresslistener alistener, in unsigned long anotifymask); void removeprogresslistener(in nsiwebprogresslistener alistener); attributes attribute type description domwindow nsidomwindow the dom window associated with this nsiwebprogress instance. read only. exceptions thrown ns_error_failure indicates that there is no associated dom window. isloadingdocument prbool indicates whether or not a document is currently being loaded in the context of this nsiwebprogress instance. read only. constants the following flags may be combined to form the anotifymask parameter for the addprogresslistener() method. they limit the set of events that are delivered to an nsiwebprogresslistener instance. these flags indicate the state transistions to observe,...
nsIWindowMediator
er() register a listener for window status changes. void addlistener( in nsiwindowmediatorlistener alistener ); parameters alistener the listener to register. example: of window listener object and how to register then unregister. this example below waits for listens to when a window opens, and then after that window opens it adds event listener to listen to when the window completes loading, after that it fires a function. important: this will attach the functionality to future opened windows, so if you copy paste this code to scratchpad, then after running this script, you need to open a new window by pressing ctrl + n and then in the new window, selecting tabs will fire the alert. var {cc: classes, ci: interfaces} = components; var windowlistener = { onopenwindow: function (...
...ll attach the functionality to future opened windows, so if you copy paste this code to scratchpad, then after running this script, you need to open a new window by pressing ctrl + n and then in the new window, selecting tabs will fire the alert. ...
Events
essagesloaded the active messages in the folder have been loaded oncreatedview a folder view has been created, but not yet shown. if custom column handlers need to do something, this is likely the event you are looking for. ondestroyingview the current folder view is being destroyed. ...
...ted, but not yet shown. if custom column handlers need to do something, this is likely the event you are looking for. ondestroyingview the current folder view is being destroyed. ...
nsIMsgCloudFileProvider
passed to the onstoprequest functions of the nsirequestobserver's used by the asynchronous methods of nsimsgcloudfileprovider. constant value description offlineerr 0x80550014 returned when it appears that there is no active network connection. autherr 0x8055001e returned when authorizing has failed. ...
...gcloudfileprovider. constant value description offlineerr 0x80550014 returned when it appears that there is no active network connection. autherr 0x8055001e returned when authorizing has failed. uploaderr 0x8055311a returned when uploading has failed for an unknown reason. uploadwouldexceedquota 0x8055311b returned when uploading has failed because the user has exceeded their storage quota. uploadexceedsfilelimit 0x8055311c returned when uploading has failed because the file being uploaded is larger than the file size limit. uploadcanceled 0x8055311d returned when uploading has stopped because it was cancelled by the user. methods init() initializes an nsimsgcloudfileprovider to be a...
Using the Mozilla symbol server
us, or by typing the .sympath command. if you would like to get symbols from microsoft's symbol server as well, you should list that first (note: you can replace c:\symcache\ with any writable directory on your computer, if you'd prefer a different location for downloaded symbols): srv*c:\symcache\*https://msdl.microsoft.com/download/symbols;srv*c:\symcache\*https://symbols.mozilla.org/ downloading symbols using symchk.exe you can also download the symbols using symchk.exe, part of microsoft's debugging tools for windows. the command should look like this (again, you can replace c:\symcache\ with any writable directory on your computer, if you'd prefer a different location for downloaded symbols): c:\program files\mozilla firefox>c:\progra~1\debugg~1\symchk.exe /r c:\progra~1\mozill~1\* /...
...r to: symchk: fullsoft.dll failed - image is split correctly, but fullsoft.dbg is missing symchk: qfaservices.dll failed - qfaservices.pdb mismatched or not found symchk: talkback.exe failed - built without debugging information. symchk: helper.exe failed - built without debugging information. symchk: failed files = 4 symchk: passed + ignored files = 179 downloading symbols on linux / mac os x if you are on linux and running gdb 7.9 or newer, you can use this gdb python script to automatically fetch symbols. you will need to source this script before loading symbols (the part where it spends a few seconds loading each .so when you attach gdb). if you want to reload symbols, you can try: nosharedlibrary sharedlibrary lib on older gdb and mac os x there is ...
ctypes.open
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. this native file can be placed in any folder of an addon and then loaded from js-ctypes. they can also be loaded from the system library path. loading the native file if your addon is restartless, you must set it to be unpacked. see: http://stackoverflow.com/questions/19382201/how-to-load-dll-from-sdk-addon-data-folder it is important to note that custom native files cannot be loaded through chrome:// or resource:// uris. they must be accessed through a local file path (file://) or a jar path (jar:). if the addon is an unpacked addon, such a...
...dll-from-sdk-addon-data-folder it is important to note that custom native files cannot be loaded through chrome:// or resource:// uris. they must be accessed through a local file path (file://) or a jar path (jar:). if the addon is an unpacked addon, such as bootstrap or add-on sdk addons, the jar path must be used. therefore, the path has to be converted and then the converted path is used for loading with ctypes.open. if the native file is located at chrome://youraddon/content/mysubfolder/mycfunctionsforunix.so then it is converted to a file uri like this: components.utils.import("resource://gre/modules/services.jsm"); var cr = components.classes['@mozilla.org/chrome/chrome-registry;1'].getservice(components.interfaces.nsichromeregistry); var chromeuri_mylib = services.io.newuri('chrome://...
Plug-in Basics - Plugins
runtime model plug-ins are dynamic code modules that are associated with one or more mime types. when the browser starts, it enumerates the available plug-ins (this step varies according to platform), reads resources from each plug-in file to determine the mime types for that plug-in, and registers each plug-in library for its mime types. the following stages outline the life of a plug-in from loading to deletion: when gecko encounters data of a mime type registered for a plug-in (either embedded in an html page or in a separate file), it dynamically loads the plug-in code into memory, if it hasn't been loaded already, and it creates a new instance of the plug-in. gecko calls the plug-in api function np_initialize when the plug-in code is first loaded. by convention, all of the plug-in sp...
... for users that do not already have the necessary plug-in. this nesting is quite common in the use of object elements, and lets you avoid code forking for different browsers. nesting rules for html elements the rules for descending into nested object and embed elements are as follows: the browser looks at the mime type of the top element. if it knows how to deal with that mime type (i.e., by loading a plug-in that's been registered for it), then it does so. if the browser cannot handle the mime type, it looks in the element for a pointer to a plug-in that can be used to handle that mime type. the browser downloads the requested plug-in. if the mime type is unknown and there is no reference to a plug-in that can be used, the browser descends into the child element, where these rules for han...
about:debugging - Firefox Developer Tools
rs, and other workers there are three sections on this page that deal with service workers, shared workers, and other workers. whether internal extensions appear in the list on this page depends on the setting of the devtools.aboutdebugging.showhiddenaddons preference. if you need to see these extensions, navigate to about:config and make sure that the preference is set to true. ...
... the major advantages of this method, compared with installing an add-on from an xpi, are: you don't have to rebuild an xpi and reinstall when you change the add-on's code; you can load an add-on without signing it and without needing to disable signing. ...
Beacon API - Web APIs
a blocking request (for example xmlhttprequest). example use cases of the beacon api are logging activity and sending analytics data to the server. example code of the interfaces described in this document is included in using the beacon api. why use beacon? the beacon interface addresses the needs of analytics and diagnostics code that typically attempts to send data to a web server before unloading the document. sending the data any sooner may result in a missed opportunity to gather data. however, ensuring that the data is sent during the unloading of a document is something that has traditionally been difficult for developers. user agents will typically ignore asynchronous xmlhttprequests made in an unload handler. to solve this problem, analytics and diagnostics code will typically make...
...oading of a document is something that has traditionally been difficult for developers. user agents will typically ignore asynchronous xmlhttprequests made in an unload handler. to solve this problem, analytics and diagnostics code will typically make a synchronous xmlhttprequest in an unload or beforeunload handler to submit the data. the synchronous xmlhttprequest forces the browser to delay unloading the document, and makes the next navigation appear to be slower. there is nothing the next page can do to avoid this perception of poor page load performance. there are other techniques used to ensure that data is submitted. one such technique is to delay the unload to submit data by creating an image element and setting its src attribute within the unload handler. as most user agents will delay...
Optimizing canvas - Web APIs
suffer. this article provides suggestions for optimizing your use of the canvas element to ensure that your graphics perform well. performance tips the following is a collection of tips to improve canvas performance. pre-render similar primitives or repeating objects on an offscreen canvas if you find yourself repeating some of the same drawing operations on each animation frame, consider offloading them to an offscreen canvas. you can then render the offscreen image to your primary canvas as often as needed, without unnecessarily repeating the steps needed to generate it in the first place. mycanvas.offscreencanvas = document.createelement('canvas'); mycanvas.offscreencanvas.width = mycanvas.width; mycanvas.offscreencanvas.height = mycanvas.height; mycanvas.getcontext('2d').drawimage(myca...
... 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. to avoid this, make sure to round all co-ordinates used in calls to drawimage() using math.floor(), for example. don’t scale images in drawimage cache various sizes of your images on an offscreen canvas when loading as opposed to constantly scaling them in drawimage(). use multiple layered canvases for complex scenes in your application, you may find that some objects need to move or change frequently, while others remain relatively static. a possible optimization in this situation is to layer your items using multiple <canvas> elements. for example, let's say you have a game with a ui on top, the gamepla...
Document.fonts - Web APIs
Web › API › Document › fonts
the fonts property of the document interface returns the fontfaceset interface of the document. syntax let fontfaceset = document.fonts; value the returned value is the fontfaceset interface of the document. the fontfaceset interface is useful for loading new fonts, checking the status of previously loaded fonts etc. examples doing operation after all fonts are loaded document.fonts.ready.then(function() { // any operation that needs to be done only after all the fonts // have finished loading can go here. }); specifications specification status comment css font loading module level 3the definition of 'fontfaceset' in that specification. working draft initial definition browser compatibility the compatibility table on this page is generated...
...to change preferences in firefox, visit about:config.ie no support noopera full support 47safari full support 10webview android full support 60chrome android ...
Document.readyState - Web APIs
the document.readystate property describes the loading state of the document. when the value of this property changes, a readystatechange event fires on the document object. syntax var string = document.readystate; values the readystate of a document can be one of following: loading the document is still loading. interactive the document has finished loading and the document has been parsed but sub-resources such as images, stylesheets and frames are still loading. complete the document and all sub-resources have finished loading. the state indicates that the load event is about to fire. examples different states of readiness switch (document.readystate) { case "loading": // the document is still loading. break; case "interactive": // the document has finished l...
... var span = document.createelement("span"); span.textcontent = "a <span> element."; document.body.appendchild(span); break; case "complete": // the page is fully loaded. ...
FileReader.readyState - Web APIs
the filereader readystate property provides the current state of the reading operation a filereader is in. a filereader exists in one of the following states: value state description 0 empty reader has been created. none of the read methods called yet. 1 loading a read method has been called. 2 done the operation is complete. empty the filereader has been created, but no readas method was called yet. loading a readas method was invoked. a file or blob is being read, and no error has occurred yet. done the read operation is complete. this could mean that: the entire file or blob has been read into memory, a file read error occurred, or abort() was called and the read was cancelled. example var reader = new filereader();...
...d. a file or blob is being read, and no error has occurred yet. done the read operation is complete. this could mean that: the entire file or blob has been read into memory, a file read error occurred, or abort() was called and the read was cancelled. example var reader = new filereader(); console.log('empty', reader.readystate); // readystate will be 0 reader.readastext(blob); console.log('loading', reader.readystate); // readystate will be 1 reader.onloadend = function () { console.log('done', reader.readystate); // readystate will be 2 }; value a number which is one of the three possible state constants define for the filereader api. specifications specification status comment file apithe definition of 'readystate' in that specification. working dra...
FontFace.display - Web APIs
Web › API › FontFace › display
the lengths of the first two periods depend on the value of the property and the user agent. (see below.) block period the browser invisibly prepares a fallback font. if the font face loads during this time, it's used to display the text and display is complete. ...
...econds for the swap period, though these values may vary from browser to browser. 'optional': gives the font face a short block period and no swap period. the spec recommends 100 ms or less, though this may vary from browser to browser. 'swap': gives the font face a 0 second block period and an infinite swap period. specifications specification status comment css font loading module level 3the definition of 'display' in that specification. working draft initial definition. css fonts module level 4the definition of 'font-display' in that specification. working draft defines the values for the display property. (they are the same as for font-display.) browser compatibility the compatibility table on this page is generated from structured da...
FontFace - Web APIs
Web › API › FontFace
ent to the font-family descriptor. fontface.featuresettings a cssomstring that retrieves or sets infrequently used font features that are not available from a font's variant properties. it is equivalent to the font-feature-settings descriptor. fontface.loaded read only returns a promise that resolves with the current fontface object when the font specified in the object's constructor is done loading or rejects with a syntaxerror. fontface.status read only returns an enumerated value indicating the status of the font, one of "unloaded", "loading", "loaded", or "error". fontface.stretch a cssomstring that retrieves or sets how the font stretches. it is equivalent to the font-stretch descriptor. fontface.style a cssomstring that retrieves or sets the style of the font. it is equivalent ...
...ght of the font. it is equivalent to the font-weight descriptor. methods this interface doesn't inherit any method. fontface.load() loads a font based on current object's constructor-passed requirements, including a location or source buffer, and returns a promise that resolves with the current fontface object. specifications specification status comment css font loading module level 3the definition of 'fontface' in that specification. working draft initial definition ...
FontFaceSetLoadEvent - Web APIs
working draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. ...
... working draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
GlobalEventHandlers.onload - Web APIs
there are also dom events like domcontentloaded and domframecontentloaded (which can be handled using eventtarget.addeventlistener()) which are fired after the do...
...nsole.log("load event detected!"); } window.onload = load; </script> // es2015 <script> const load = () => { console.log("load event detected!"); } window.onload = load; </script> </head> <body> <p>the load event fires when the document has finished loading!</p> </body> </html> notes the load event fires at the end of the document loading process. at this point, all of the objects in the document are in the dom, and all the images, scripts, links and sub-frames have finished loading. there are also dom events like domcontentloaded and domframecontentloaded (which can be handled using eventtarget.addeventlistener()) which are fired after the dom for the page has been constructed, but do not wait for other resources to finish loadi...
HTMLImageElement.alt - Web APIs
perhaps the most important reason to use the alt tag is to support accessibility, as the alt text may be used by screen readers and other assistive technologies to help differently-abled users make full use of your content. ...
... perhaps the most important reason to use the alt tag is to support accessibility, as the alt text may be used by screen readers and other assistive technologies to help differently-abled users make full use of your content. ...
HTMLImageElement.crossOrigin - Web APIs
in from which the document was loaded. use-credentials requests by the htmlimageelement will use the cors mode and the include credentials mode; all image requests by the element will use cors, regardless of what domain the fetch is from. if crossorigin is an empty string (""), the anonymous mode is selected. 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.q...
.... 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. it's a very interesting paragraph. you are captivated by this paragraph. keep reading this paragraph. okay, now you can stop reading this paragraph. thanks for reading me.</p> </div> cs...
HTMLImageElement.decode() - Web APIs
this, in turn, prevents the rendering of the next frame after adding the image to the dom from causing a delay while the image loads. syntax var promise = htmlimageelement.decode(); parameters none. ...
... frame after adding the image to the dom from causing a delay while the image loads. syntax var promise = htmlimageelement.decode(); parameters none. return value a promise which is resolved once the image data is ready to be used. exceptions encodingerror a domexception indicating that an error occurred while decoding the image. usage notes one potential use case for decode(): when loading very large images (for example, in an online photo album), you can present a low resolution thumbnail image initially and then replace that image with the full-resolution image by instantiating a new htmlimageelement, setting its source to the full-resolution image's url, then using decode() to get a promise which is resolved once the full-resolution image is ready for use. at that time, you can ...
HTMLMediaElement.networkState - Web APIs
ng of media over the network. syntax var networkstate = audioorvideo.networkstate; value an unsigned short. possible values are: constant value description network_empty 0 there is no data yet. also, readystate is have_nothing. network_idle 1 htmlmediaelement is active and has selected a resource, but is not using the network. network_loading 2 the browser is downloading htmlmediaelement data. network_no_source 3 no htmlmediaelement src found. examples this example will listen for the audio element to begin playing and then check if it is still loading data. <audio id="example" preload="auto"> <source src="sound.ogg" type="audio/ogg" /> </audio> var obj = document.getelementbyid('example'); obj.addev...
...rce 3 no htmlmediaelement src found. examples this example will listen for the audio element to begin playing and then check if it is still loading data. <audio id="example" preload="auto"> <source src="sound.ogg" type="audio/ogg" /> </audio> var obj = document.getelementbyid('example'); obj.addeventlistener('playing', function() { if (obj.networkstate === 2) { // still loading... } }); specifications specification status comment html living standardthe definition of 'htmlmediaelement.networkstate' in that specification. living standard html5the definition of 'htmlmediaelement.networkstate' in that specification. recommendation ...
HTMLMediaElement: suspend event - Web APIs
the suspend event is fired when media data loading has been suspended. bubbles no cancelable no interface event target element default action none event handler property globaleventhandlers.onsuspend specification html5 media examples these examples add an event listener for the htmlmediaelement's suspend event, then post a message when that event handler has reacted to the event firing. ...
...ler property globaleventhandlers.onsuspend specification html5 media examples these examples add an event listener for the htmlmediaelement's suspend event, then post a message when that event handler has reacted to the event firing. using addeventlistener(): const video = document.queryselector('video'); video.addeventlistener('suspend', (event) => { console.log('data loading has been suspended.'); }); using the onsuspend event handler property: const video = document.queryselector('video'); video.onsuspend = (event) => { console.log('data loading has been suspended.'); }; specifications specification status html living standardthe definition of 'suspend media event' in that specification. living standard html5the definition of ...
HTMLMediaElement - Web APIs
r example, when the media has already been loaded (or partially loaded), and the htmlmediaelement.load() method is called to reload it. ended fired when playback stops when end of the media (<audio> or <video>) is reached or because no further data is available. error fired when the resource could not be loaded due to an error. loadeddata fired when the first frame of the media has finished loading. loadedmetadata fired when the metadata has been loaded loadstart fired when the browser has started to load a resource. pause fired when a request to pause play is handled and the activity has entered its paused state, most commonly occurring when the media's htmlmediaelement.pause() method is called. play fired when the paused property is changed from true to false, as a result of the h...
... been paused or delayed due to lack of data progress fired periodically as the browser loads a resource. ratechange fired when the playback rate has changed. seeked fired when a seek operation completes seeking fired when a seek operation begins stalled fired when the user agent is trying to fetch media data, but data is unexpectedly not forthcoming. suspend fired when the media data loading has been suspended. timeupdate fired when the time indicated by the currenttime attribute has been updated volumechange fired when the volume has changed. waiting fired when playback has stopped because of a temporary lack of data specifications specification status comment encrypted media extensionsthe definition of 'encrypted media extensions' in that specif...
HTMLTrackElement - Web APIs
tribute, indicating that the track is to be enabled if the user's preferences do not indicate that another track would be more appropriate. htmltrackelement.readystate read only returns an unsigned short that show the readiness state of the track: constant value description none 0 indicates that the text track's cues have not been obtained. loading 1 indicates that the text track is loading and there have been no fatal errors encountered so far. further cues might still be added to the track by the parser. loaded 2 indicates that the text track has been loaded with no fatal errors. error 3 indicates that the text track was enabled, but when the user agent attempted to obtain it, this failed in...
...n a <track> element, in addition to any that may be fired at its parent, htmlelement. cuechange sent when the underlying texttrack has changed the currently-presented cues. this event is always sent to the texttrack but is also sent to the htmltrackelement if one is associated with the track. you may also use the oncuechange event handler to establish a handler for this event. usage notes loading of the track's text resource the webvtt or ttml data describing the actual cues for the text track isn't loaded if the track's mode is initially in the disabled state. if you need to be able to perform any processing on the track after the <track> is set up, you should instead ensure that the track's mode is either hidden (if you don't want it to start out being presented to the user) or showing...
IDBDatabase - Web APIs
e that an upgrade is needed (idbdatabase). for a complete working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); // these two event handlers act on the idbdatabase object, // when the database is opened successfully, or not 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. this is used a lot later on db = dbopenrequest.result; // run the displaydata() function to populate the task // list with all the to-do list data already in the idb displaydata(); }; // this event ...
...e 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 dbopenrequest.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 using // idbdatabase.createobjectstore 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.crea...
IDBObjectStore.createIndex() - Web APIs
a higher version number is loaded. createindex() is used to create new indexes on the object store. for a full working example, see our to-do notifications app (view example live.) var db; // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); // two event handlers for opening the database. 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. // 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 handler fires ...
...ydata(); }; // this handler fires when a new database is created and indicates // either that one has not been created before, or a new version // was submitted with window.indexeddb.open(). (see above.) // it is only implemented in recent browsers. ...
IDBObjectStore.deleteIndex() - Web APIs
fter which we delete the unneeded old indexes with deleteindex(). for a full working example, see our to-do notifications app (view example live.) var db; // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); // these two event handlers act on the database being opened successfully, or not 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. 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 wher...
...is 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 ...
IDBOpenDBRequest.onblocked - Web APIs
en after the versionchange event was sent. note: this feature is available in web workers. syntax idbopendbrequest.onblocked = function(event) { ... }; example var db; // let us open our database var request = indexeddb.open("todolist", 4); // these two event handlers act on the database being opened // successfully, or not request.onerror = function(event) { note.innerhtml += '<li>error loading database.</li>'; }; request.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. // 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 eve...
...nt 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" }); ... }; request.onblocked = function() { console.log("your database version can't be upgraded because the app is open somewhere else."); } specifications specification status comment indexed database api 2.0the definitio...
IDBOpenDBRequest.onupgradeneeded - Web APIs
ndow.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. request.onupgradeneeded = function(event) { db = request.result; db.onerror = function(errorevent) { note.innerhtml += '<li>error loading database.</li>'; }; if (event.oldversion < 1) { // version 1 is the first version of the database. 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 b...
...); } if (event.oldversion < 3) { // version 3 introduces a new object store for magazines with two indexes. var magazines = db.createobjectstore("magazines"); var publisherindex = magazines.createindex("by_publisher", "publisher"); var frequencyindex = magazines.createindex("by_frequency", "frequency"); } }; request.onerror = function(event) { note.innerhtml += '<li>error loading database.</li>'; }; request.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; db = request.result; populateanddisplaydata(); }; specifications specification status comment indexed database api 2.0the definition of 'onupgradeneeded' in that specification. recommendation indexed database api draftthe definition of '...
IDBOpenDBRequest - Web APIs
sed to update the database structure if a database with a higher version number is loaded. for a full working example, see our to-do notifications app (view example live.) var db; // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); // these event handlers act on the database being opened. 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. 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 hand...
...vent 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 ...
Using IndexedDB - Web APIs
use they are asynchronous they will be aborted before they can execute. in fact, there is no way to guarantee that indexeddb transactions will complete, even with normal browser shutdown. see bug 870645. as a workaround for this normal shutdown notification, you might track your transactions and add a beforeunload event to warn the user if any transactions have not yet completed at the time of unloading. at least with the addition of the abort notifications and idbdatabase.onclose, you can know when this has happened. locale-aware sorting mozilla has implemented the ability to perform locale-aware sorting of indexeddb data in firefox 43+. by default, indexeddb didn’t handle internationalization of sorting strings at all, and everything was sorted as if it were english text. for example, b, ...
...ist"></ul>'); compat_envs.foreach(function(val, idx, array) { $('#compat-list').append('<li>' + val[0] + ': ' + val[1] + '</li>'); }); const db_name = 'mdn-demo-indexeddb-epublications'; const db_version = 1; // use a long long for this value (don't use a float) const db_store_name = 'publications'; var db; // used to keep track of which view is displayed to avoid uselessly reloading it var current_view_pub_key; function opendb() { console.log("opendb ..."); var req = indexeddb.open(db_name, db_version); req.onsuccess = function (evt) { // equal to: db = req.result; db = this.result; console.log("opendb done"); }; req.onerror = function (evt) { console.error("opendb:", evt.target.errorcode); }; req.onupgradeneeded = fu...
Intersection Observer API - Web APIs
ting visibility of an element, or the relative visibility of two elements in relation to each other, has been a difficult task for which solutions have been unreliable and prone to causing the browser and the sites the user is accessing to become sluggish. as the web has matured, the need for this kind of information has grown. intersection information is needed for many reasons, such as: lazy-loading of images or other content as a page is scrolled. implementing "infinite scrolling" web sites, where more and more content is loaded and rendered as you scroll, so that the user doesn't have to flip through pages. reporting of visibility of advertisements in order to calculate ad revenues. deciding whether or not to perform tasks or animation processes based on whether or not the user will see...
...this string will be replaced with the target's current visibility ratio, so that the element not only changes color but also becomes increasingly opaque as it becomes less obscured. decreasingcolor similarly, this is a string defining a color we'll apply when the visibility ratio is decreasing. we call window.addeventlistener() to start listening for the load event; once the page has finished loading, we get a reference to the element with the id "box" using queryselector(), then call the createobserver() method we'll create in a moment to handle building and installing the intersection observer. creating the intersection observer the createobserver() method is called once page load is complete to handle actually creating the new intersectionobserver and starting the process of observing th...
NavigationPreloadManager - Web APIs
the navigationpreloadmanager interface of the the service worker api provides methods for managing the preloading of resources with a service worker. methods navigationpreloadmanager.enable() enables navigation preloading and returns a promise that resolves. navigationpreloadmanager.disable() disables navigation preloading and returns a promise that resolves. navigationpreloadmanager.setheadervalue() sets the value of the service-worker-navigation-preload header and returns an empty promise. ...
...resolves. navigationpreloadmanager.setheadervalue() sets the value of the service-worker-navigation-preload header and returns an empty promise. navigationpreloadmanager.getstate() returns a promise that resolves to an object with properties indicating whether preload is enabled and the contents of the service-worker-navigation-preload. examples feature detecting and enabling navigation preloading addeventlistener('activate', event => { event.waituntil(async function() { if (self.registration.navigationpreload) { // enable navigation preloads! await self.registration.navigationpreload.enable(); } }()); }); using a preloaded response the following example shows the implementation of a fetch event that uses a preloaded response. addeventlistener('fetch', event ...
PaintWorklet - Web APIs
rits methods from worklet. paintworklet.registerpaint() registers a class programmatically generate an image where a css property expects a file. css.paintworklet.addmodule() the addmodule() method, inhertied from the worklet interface loads the module in the given javascript file and adds it to the current paintworklet. examples the following three examples go together to show creating, loading, and using a paintworklet. create a paintworklet the following shows an example worklet module. this should be in a separate js file. note that registerpaint() is called without a reference to paintworklet. class checkerboardpainter { paint(ctx, geom, properties) { // use `ctx` as if it was a normal canvas const colors = ['red', 'green', 'blue']; const size = 32; for(let y = ...
... <script> if ('paintworklet' in css) { css.paintworklet.addmodule('checkerboard.js'); } </script> use a paintworklet this example shows how to use a paintworklet in a stylesheet, including the simplest way to provide a fallback if paintworklet isn't supported. <style> textarea { background-image: url(checkerboa...
PerformanceTiming - Web APIs
this interface is deprecated in the navigation timing level 2 specification. please use the performancenavigationtiming interface instead. the performancetiming interface is a legacy interface kept for backwards compatibility and contains properties that offer performance timing information for various events which occur during the loading and use of the current page. you get a performancetiming object describing your page using the window.performance.timing property. properties the performancetiming interface doesn't inherit any properties. these properties each describe the time at which a particular point in the page loading process was reached. some correspond to dom events; others describe the time at which internal browser operations of interest took place. each time is provided as ...
... performancetiming.responsestart read only when the browser received the first byte of the response, from the server from a cache, or from a local resource. performancetiming.responseend read only when the browser received the last byte of the response, or when the connection is closed if this happened first, from the server, the cache, or from a local resource. performancetiming.domloading read only when the parser started its work, that is when its document.readystate changes to 'loading' and the corresponding readystatechange event is thrown. performancetiming.dominteractive read only when the parser finished its work on the main document, that is when its document.readystate changes to 'interactive' and the corresponding readystatechange event is thrown. performancet...
ProgressEvent - Web APIs
the progressevent interface represents events measuring progress of an underlying process, like an http request (for an xmlhttprequest, or the loading of the underlying resource of an <img>, <audio>, <video>, <style> or <link>). <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 11.666666666666666%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 70" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/event" target="_top"><rect x="1" y="1" width="75" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="38.5" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" a...
...if the total work to be done, and the amount of work already done, by the underlying process is calculable. in other words, it tells if the progress is measurable or not. progressevent.loaded read only is an unsigned long long representing the amount of work already performed by the underlying process. the ratio of work done can be calculated with the property and progressevent.total. when downloading a resource using http, this only represent the part of the content itself, not headers and other overhead. progressevent.total read only is an unsigned long long representing the total amount of work that the underlying process is in the progress of performing. when downloading a resource using http, this only represent the content itself, not headers and other overhead. methods also inh...
ServiceWorkerContainer.startMessages() - Web APIs
the startmessages() method of the serviceworkercontainer interface explicitly starts the flow of messages being dispatched from a service worker to pages under its control (e.g. sent via client.postmessage()). this can be used to react to sent messages earlier, even before that page's content has finished loading. explanation by default, all messages sent from a page's controlling service worker to the page (using client.postmessage()) are queued while the page is loading, and get dispatched once the page's html document has been loaded and parsed (i.e. after the domcontentloaded event fires). it's possible to start dispatching these messages earlier by calling serviceworkercontainer.startmessages(), for example if you've invoked a message handler using eventtarget.addeventlistener() before th...
... note: the messages start being sent automatically when setting the handler directly using serviceworkercontainer.onmessage. in this you don't need startmessages(). syntax serviceworkercontainer.startmessages(); parameters none. return value undefined. ...
USBDevice - Web APIs
Web › API › USBDevice
usb device and methods for controlling it. properties usbdevice.configuration read only a usbconfiguration object for the currently selected interface for a paired usb device. usbdevice.configurations read only an array of device-specific interfaces for controlling a paired usb device. usbdevice.deviceclass read only one of three properties that identify usb devices for the purpose of loading a usb driver that will work with that device. the other two properties are usbdevice.devicesubclass and usbdevice.deviceprotocol. usbdevice.deviceprotocol read only one of three properties that identify usb devices for the purpose of loading a usb driver that will work with that device. the other two properties are usbdevice.deviceclass and usbdevice.devicesubclass. usbdevice.devicesubclass r...
...the other two properties are usbdevice.deviceclass and usbdevice.deviceprotocol. usbdevice.deviceversionmajor read only the major version number of the device in a semantic versioning scheme. ...
Adding 2D content to a WebGL context - Web APIs
successfully created a webgl context, you can start rendering into it. a simple thing we can do is draw a simple square untextured plane, so let's start there, by building code to draw a square plane. the complete source code for this project is available on github. this project uses the glmatrix library to perform its matrix operations, so you will need to include that in your project. we're loading a copy from a cdn in our html's <head>. drawing the scene the most important thing to understand before we get started is that even though we're only rendering a square plane object in this example, we're still drawing in 3d space. it's just we're drawing a square and we're putting it directly in front of the camera perpendicular to the view direction. we need to define the shaders that will c...
...t, vertexcount); } } the first step is to clear the canvas to our background color; then we establish the camera's perspective. we set a field of view of 45°, with a width to height ratio that matches the display dimensions of our canvas. we also specify that we only want objects between 0.1 and 100 units from the camera to be rendered. then we establish the position of the square plane by loading the identity position and translating away from the camera by 6 units. after that, we bind the square's vertex buffer to the attribute the shader is using for avertexposition and we tell webgl how to pull the data out of it. finally we draw the object by calling the drawarrays() method. view the complete code | open this demo on a new page matrix utility operations matrix operations might se...
Taking still photos with WebRTC - Web APIs
bles are: width whatever size the incoming video is, we're going to scale the resulting image to be 320 pixels wide. height the output height of the image will be computed given the width and the aspect ratio of the stream. streaming indicates whether or not there is currently an active stream of video running. video this will be a reference to the <video> element after the page is done loading. canvas this will be a reference to the <canvas> element after the page is done loading. photo this will be a reference to the <img> element after the page is done loading. startbutton this will be a reference to the <button> element that's used to trigger capture. we'll get that after the page is done loading. the startup() function the startup() function is run when the page has finish...
...this function's job is to request access to the user's webcam, initialize the output <img> to a default state, and to establish the event listeners needed to receive each frame of video from the camera and react when the button is clicked to capture an image. ...
Rendering and the WebXR frame animation callback - Web APIs
shows some combination of the previous frame and possibly even the frame before that one. your mission, then, is to keep your code tight and lightweight enough that you don't overrrun the time available to you or otherwise cause dropped frames or excessively abuse the main thread. for these reasons, unless your renderer is fairly small and lightweight, with little to do, you should consider offloading everything you can to a worker so you can be computing the next frame while the browser handles other things. by simply having your computations and data ready before the frame is actually called for, you can make your site or app render much more efficiently, improving main thread performance and generally making the user experience better. fortunately, there are some tricks you can use to furt...
... to minimize how much time you spend in this function as much as possible, the more time you spend handling state changes, the less time you have to actually draw things. this technique works very well for a small number of objects, but because it has to re-bind all the data for each object twice (once for the left eye, and once for the right), you're spending a lot of time adjusting the state, uploading buffers and textures, and so forth. in the next section, we look at an altered approach that reduces these state changes substantially, providing a potentially much faster rendering approach, especially as your object count goes up. optimizing by rendering in object-first order an advantage of webxr's approach of using a single webgl framebuffer to contain both the left and right eye's views in...
Starting up and shutting down a WebXR session - Web APIs
the emulator to rename the xr interface to xrsystem, introduce support for squeeze (grip) input sources, and add support for the xrinputsource property profiles. context requirements a webxr compatible environment starts with a securely-loaded document. your document needs to either have been loaded from the local drive (such as by using an url such as http://localhost/...), or using https when loading the page. the javascript code must, likewise, have been loaded securely. if the document wasn't loaded securely, you won't get very far. the navigator.xr property doesn't even exist if the document wasn't loaded securely. this may also be the case if there simply is no compatible xr hardware available. either way, you need to be prepared for the lack of an xr property and either gracefully handl...
...nimation callback. on operational details obviously, this was a just an example. you don't need a worlddata object to store everything; you can store the information you need to maintain any way you want to. you may need different information or have different specific requirements that cause you to do things differently, or in a different order. similarly, the specific methodology you use for loading models and other information and setting up your webgl data—textures, vertex buffers, shaders, and so on—will vary a great deal depending on your needs, what if any frameworks you're using, and the like. important session maintenance events over the course of your webxr session, you may receive any of a number of events which indicate changes to the state of the session, or which let you k...
Using the Web Audio API - Web APIs
ntext; const audiocontext = new audiocontext(); so what's going on when we do this? a baseaudiocontext is created for us automatically and extended to an online audio context. we'll want this because we're looking to play live sound. note: if you just want to process audio data, for instance, buffer and stream it but not play it, you might want to look into creating an offlineaudiocontext. loading sound now, the audio context we've created needs some sound to play through it. there are a few ways to do this with the api. let's begin with a simple method — as we have a boombox, we most likely want to play a full song track. also, for accessibility, it's nice to expose that track in the dom. we'll expose the song on the page using an <audio> element. <audio src="mycooltrack.mp3"></audio>...
...e created needs some sound to play through it. there are a few ways to do this with the api. let's begin with a simple method — as we have a boombox, we most likely want to play a full song track. also, for accessibility, it's nice to expose that track in the dom. we'll expose the song on the page using an <audio> element. <audio src="mycooltrack.mp3"></audio> note: if the sound file you're loading is held on a different domain you will need to use the crossorigin attribute; see cross origin resource sharing (cors) for more information. to use all the nice things we get with the web audio api, we need to grab the source from this element and pipe it into the context we have created. lucky for us there's a method that allows us to do just that — audiocontext.createmediaelementsource: //...
Window: load event - Web APIs
Web › API › Window › load event
the load event is fired when the whole page has loaded, including all dependent resources such as stylesheets and images. this is in contrast to domcontentloaded, which is fired as soon as the page dom has been loaded, without waiting for resources to finish loading. bubbles no cancelable no interface event event handler property onload examples log a message when the page is fully loaded: window.addeventlistener('load', (event) => { console.log('page is fully loaded'); }); the same, but using the onload event handler property: window.onload = (event) => { console.log('page is fully loaded'); }; live example html <div class="controls"> <button id="reload" type="button">reload</button> </div> <div class="event-log"> <label>e...
...'load' events are fired at many elements too. and note there are many places in the specification that refer to things that can "delays the load event". ...
Window: pageshow event - Web APIs
bubbles no cancelable no interface pagetransitionevent event handler property onpageshow examples this example sets up event handlers for events listed in the array events. ...
...eshow": let ispersisted = event.persisted ? "persisted" : "not persisted"; console.log('event:', event.type, '-', ispersisted); break; default: console.log('event:', event.type); break; } }; events.foreach(eventname => window.addeventlistener(eventname, eventlogger) ); html <p>open the console and watch the output as you navigate to and from this page. try loading new pages into this tab, then navigating forward and backward through history, noting the events’ output to the log.</p> results specifications specification status comment html living standardthe definition of 'pageshow' in that specification. living standard initial specification. html5the definition of 'pageshow' in that specification. reco...
XDomainRequest.onprogress - Web APIs
syntax xdr.onprogress = funcref; parameters funcref a function to call when progress events occur. ...
... syntax xdr.onprogress = funcref; parameters funcref a function to call when progress events occur. ...
XMLDocument.load() - Web APIs
Web › API › XMLDocument › load
document.load() is a part of an old version of the w3c dom level 3 load & save module. can be used with document.async to indicate whether the request is synchronous or asynchronous (the default). as of at least gecko 1.9, this no longer supports cross-site loading of documents (use xmlhttprequest or fetch() instead). ...
...tedocument("", "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 ...
Sending and Receiving Binary Data - Web APIs
text, using a user-defined character set. this tells the browser not to parse it, and to let the bytes pass through unprocessed. var filestream = load_binary_resource(url); var abyte = filestream.charcodeat(x) & 0xff; // throw away high-order byte (f7) the example above fetches the byte at offset x within the loaded binary data. the valid range for x is from 0 to filestream.length-1. see downloading binary streams with xmlhttprequest for a detailed explanation. see also downloading files. sending binary data the send method of the xmlhttprequest has been extended to enable easy transmission of binary data by accepting an arraybuffer, blob, or file object. the following example creates a text file on-the-fly and uses the post method to send the "file" to the server. this example uses plain...
...lhttprequest; xhr.open("post", url, false); xhr.send(myarray); this is building a 512-byte array of 8-bit integers and sending it; you can use any binary data you'd like, of course. note: support for sending arraybuffer objects using xmlhttprequest was added to gecko 9.0 (firefox 9.0 / thunderbird 9.0 / seamonkey 2.6). add information about other browsers' support here. submitting forms and uploading files please, read this paragraph. firefox-specific examples this example transmits binary content asynchronously, using the post method, and firefox's non-standard sendasbinary(). var req = new xmlhttprequest(); req.open("post", url, true); // set headers and mime-type appropriately req.setrequestheader("content-length", 741); req.sendasbinary(abody); line 4 sets the content-length header ...
XMLHttpRequest.status - Web APIs
property returns the numerical http status code of the xmlhttprequest's response. before the request completes, the value of status is 0. browsers also report a status of 0 in case of xmlhttprequest errors. ...
...0 in case of xmlhttprequest errors. ...
XMLHttpRequest.statusText - Web APIs
is in unsent or opened state, the value of statustext will be an empty string. if the server response doesn't explicitly specify a status text, statustext will assume the default value "ok". ...
...lue "ok". ...
Implementing a Microsoft Active Accessibility (MSAA) Server - Accessibility
mation specific to your object model. for example, gecko support isimpledomnode to provide information about the dom node for an accessible object. a set of system messages that confer accessibility-related events such as focus changes, changes to document content and state changes in ui objects like checkboxes. to really learn about msaa, you need to download the entire msaa sdk. without downloading the sdk, you won't get the extremely useful tools, which help a great deal in the learning process. the accessible event watcher shows what accessible events are being generated by a given piece of software. the accessible explorer and inspect object tools show the tree of data nodes the accessible object is exposing through com, and what the screen boundaries of each object are. in addition, msd...
... not using a hash table to keep track of unique id's, store the child id's and objects for the last 50 or so events in a circular array. in practice, this is enough to keep accessibleobjectfromevent() happy. missing functionality in msaa problem and solutions: assistive technology vendors need some things which msaa does not provide, such as: no way of signifying that a document has finished loading. fire event_object_statechange for a window/client/pane object when it starts to load a new document. use state_busy to indicate that a new document is being loaded. when the loading has finished, fire another event_object_statechange event and clear the state_busy flag. no method to get clipped/unclipped bounds of a piece of text within a text object. this is needed by screen magnifiers. no scr...
HTML attribute reference - HTML: Hypertext Markup Language
defines the text direction. allowed values are ltr (left-to-right) or rtl (right-to-left) dirname <input>, <textarea> disabled <button>, <command>, <fieldset>, <input>, <keygen>, <optgroup>, <option>, <select>, <textarea> indicates whether the user can interact with the element. download <a>, <area> indicates that the hyperlink is to be used for downloading a resource. draggable global attribute defines whether the element can be dragged. dropzone global attribute indicates that the element accepts the dropping of content onto it. enctype <form> defines the content type of the form data when the method is post. enterkeyhint <textarea>, contenteditable the enterkeyhint specifies what actio...
... keytype <keygen> specifies the type of key generated. kind <track> specifies the kind of text track. label <optgroup>, <option>, <track> specifies a user-readable title of the element. lang global attribute defines the language used in the element. language <script> defines the script language used in the element. loading <img>, <iframe> indicates if the element should be loaded lazily (loading="lazy") or loaded immediately (loading="eager"). wip: whatwg pr #3752 list <input> identifies a list of pre-defined options to suggest to the user. loop <audio>, <bgsound>, <marquee>, <video> indicates whether the media should start playing from the start when it's finished. ...
HTML documentation index - HTML: Hypertext Markup Language
Web › HTML › Index
ties. the properties are carried in class attributes that can be added to any html element, while the data values re-use html element content and semantic attributes. microformats2 is an update to microformats that provides a simpler way of annotating html structured syntax & vocabularies than previous approaches of using rdfa and microdata which require learning new attributes. ...
...ng rdfa and microdata which require learning new attributes. 235 preloading content with rel="preload" guide, html, javascript, link, media, performance, web performance, as, preload, rel the preload value of the <link> element's rel attribute lets you declare fetch requests in the html's <head>, specifying resources that your page will need very soon, which you want to start loading early in the page lifecycle, before browsers' main rendering machinery kicks in. 236 quirks mode and standards mode gecko, guide, html, needsupdate, web development, web standards, xhtml in the old days of the web, pages were typically written in two versions: one for netscape navigator, and one for microsoft internet explorer. when the web standards were made at w3c, browser...
HTML: Hypertext Markup Language
Web › HTML
basic building block of the web. it defines the meaning and structure of web content. other technologies besides html are generally used to describe a web page's appearance/presentation (css) or functionality/behavior (javascript). "hypertext" refers to links that connect web pages to one another, either within a single website or between websites. links are a fundamental aspect of the web. 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. html uses "markup" to annotate text, images, and other content for display in a web browser. html markup includes special "elements" such as <head>, <title>, <body>, <header>, <footer>, <article>, <section>, <p>, <div>, <span>, <img>, <aside>, <audio>, <canvas>, <datal...
...r, allows images defined by the <img> element to be loaded from foreign origins and used in a <canvas> element as if they were being loaded from the current origin. cors settings attributes some html elements that provide support for cors, such as <img> or <video>, have a crossorigin attribute (crossorigin property), which lets you configure the cors requests for the element's fetched data. preloading content with rel="preload" the preload value of the <link> element's rel attribute allows you to write declarative fetch requests in your html <head>, specifying resources that your pages will need very soon after loading, which you therefore want to start preloading early in the lifecycle of a page load, before the browser's main rendering machinery kicks in. this ensures that they are made ava...
HTTP conditional requests - HTTP
http has a concept of conditional requests, where the result, and even the success of a request, can be changed by comparing the affected resources with the value of a validator. such requests can be useful to validate the content of a cache, and sparing a useless control, to verify the integrity of a document, like when resuming a download, or when preventing to lose updates when uploading or modifying a document on the server. principles http conditional requests are requests that are executed differently, depending on the value of specific headers. these headers define a precondition, and the result of the request will be different if the precondition is matched or not. the different behaviors are defined by the method of the request used, and by the set of headers used for a precondition:...
...k response, with the new version of the resource, like if the request wasn't conditional and the client uses this new resource (and caches it). besides the setting of the validators on the server side, this mechanism is transparent: all browsers manage a cache and send such conditional requests without any special work to be done by web developers. integrity of a partial download partial downloading of files is a functionality of http that allows to resume previous operations, saving bandwidth and time, by keeping the already obtained information: a server supporting partial downloads broadcasts this by sending the accept-ranges header. once this happens, the client can resume a download by sending a ranges header with the missing ranges: the principle is simple, but there is one poten...
Cache-Control - HTTP
the seconds value indicates how long the client will accept a stale response. see "keeping things fresh with stale-while-revalidate" for more information. stale-if-error=<seconds> indicates the client will accept a stale response if the check for a fresh one fails. the seconds value indicates how long the client will accept the stale response after the initial expiration. revalidation and reloading must-revalidate indicates that once a resource becomes stale, caches must not use their stale copy without successful validation on the origin server. proxy-revalidate like must-revalidate, but only for shared caches (e.g., proxies). ignored by private caches. immutable indicates that the response body will not change over time. the resource, if unexpired, is unchanged on the server and t...
...that are served by the application such as images, css files and javascript files, for example. in addition, see also the expires header. cache-control: public, max-age=604800, immutable requiring revalidation specifying no-cache or max-age=0 indicates that clients can cache a resource and must revalidate each time before using it. this means http request occurs each time, but it can skip downloading http body if the content is valid. cache-control: no-cache cache-control: no-cache, max-age=0 specifications specification status comment rfc 8246: http immutable responses ietf rfc rfc 7234: hypertext transfer protocol (http/1.1): caching ietf rfc rfc 5861: http cache-control extensions for stale content ietf rfc initial defin...
Strict-Transport-Security - HTTP
ty: max-age=<expire-time>; includesubdomains strict-transport-security: max-age=<expire-time>; preload directives max-age=<expire-time> the time, in seconds, that the browser should remember that a site is only to be accessed using https. includesubdomains optional if this optional parameter is specified, this rule applies to all of the site's subdomains as well. preload optional see preloading strict transport security for details. not part of the specification. description if a website accepts a connection through http and redirects to https, visitors may initially communicate with the non-encrypted version of the site before being redirected, if, for example, the visitor types http://www.foo.com/ or even just foo.com. this creates an opportunity for a man-in-the-middle attack. the...
...er the strict-transport-security header is delivered to the browser, it will update the expiration time for that site, so sites can refresh this information and prevent the timeout from expiring. should it be necessary to disable strict transport security, setting the max-age to 0 (over a https connection) will immediately expire the strict-transport-security header, allowing access via http. preloading strict transport security google maintains an hsts preload service. by following the guidelines and successfully submitting your domain, browsers will never connect to your domain using an insecure connection. while the service is hosted by google, all browsers have stated an intent to use (or actually started using) the preload list. however, it is not part of the hsts specification and should ...
X-XSS-Protection - HTTP
although these protections are largely unnecessary in modern browsers when sites implement a strong content-security-policy that disables the use of inline javascript ('unsafe-inline'), they can still provide protections for users of older web browsers that don't yet support csp. ...
...ss filtering. rather than sanitizing the page, the browser will prevent rendering of the page if an attack is detected. 1; report=<reporting-uri> (chromium only) enables xss filtering. if a cross-site scripting attack is detected, the browser will sanitize the page and report the violation. this uses the functionality of the csp report-uri directive to send a report. example block pages from loading when they detect reflected xss attacks: x-xss-protection: 1; mode=block php header("x-xss-protection: 1; mode=block"); apache (.htaccess) <ifmodule mod_headers.c> header set x-xss-protection "1; mode=block" </ifmodule> nginx add_header "x-xss-protection" "1; mode=block"; specifications not part of any specifications or drafts. ...
Redirections in HTTP - HTTP
warding, is a technique to give more than one url address to a page, a form, or a whole web site/application. http has a special kind of response, called a http redirect, for this operation. redirects accomplish numerous goals: temporary redirects during site maintenance or downtime permanent redirects to preserve existing links/bookmarks after changing the site's urls, progress pages when uploading a file, etc. principle in http, redirection is triggered by a server sending a special redirect response to a request. redirect responses have status codes that start with 3, and a location header holding the url to redirect to. when browsers receive a redirect, they immediately load the new url provided in the location header. besides the small performance hit of an additional round-trip, us...
...tribute should start with a number indicating how many seconds the browser should wait before redirecting to the given url. always set it to 0 for accessibility compliance. obviously, this method only works with html, and cannot be used for images or other types of content. javascript redirections redirections in javascript are performed by setting a url string to the window.location property, loading the new page: window.location = "https://example.com/"; like html redirections, this can't work on all resources, and obviously, this will only work on clients that execute javascript. on the other hand, there are more possibilities: for example, you can trigger the redirect only if some conditions are met. order of precedence with three ways to trigger redirections, several ways can be used ...
Promise.prototype.finally() - JavaScript
(() => {}) will be resolved with 2. similarly, unlike promise.reject(3).then(() => {}, () => {}) (which will be fulfilled with undefined), promise.reject(3).finally(() => {}) will be rejected with 3. note: a throw (or returning a rejected promise) in the finally callback will reject the new promise with the rejection reason specified when calling throw. ...
...for more details, refer to: https://discourse.mozilla.org/t/mdn-rfc-001-mdn-wiki-pages-shouldnt-be-a-distributor-of-polyfills/24500 specifications specification ecmascript (ecma-262)the definition of 'promise.prototype.finally' in that specification. ...
import - JavaScript
le.js'); } })(); dynamic imports the standard import syntax is static and will always result in all code in the imported module being evaluated at load time. in situations where you wish to load a module conditionally or on demand, you can use a dynamic import instead. the following are some reasons why you might need to use dynamic import: when importing statically significantly slows the loading of your code and there is a low likelihood that you will need the code you are importing, or you will not need it until a later time. when importing statically significantly increases your program's memory usage and there is a low likelihood that you will need the code you are importing. when the module you are importing does not exist at load time when the import specifier string needs to be ...
... constructed dynamically. (static import only supports static specifiers.) when the module being imported has side effects, and you do not want those side effects unless some condition is true. (it is recommended not to have any side effects in a module, but you sometimes cannot control this in your module dependencies.) use dynamic import only when necessary. the static form is preferable for loading initial dependencies, and can benefit more readily from static analysis tools and tree shaking. to dynamically import a module, the import keyword may be called as a function. when used this way, it returns a promise. import('/modules/my-module.js') .then((module) => { // do something with the module. }); this form also supports the await keyword. let module = await import('/modules/...
Handling media support issues in web content - Web media technologies
ion or alternate version that will be displayed until the full-quality version is available to be displayed. we'll look at both of these scenarios and how to implement them. poster frames for video progressive images images—whether embedded using <img> or <picture>—don't support a concept similar to poster frames. however, there are ways to present an image in low quality while it's still loading. this requires creating your images using progressive formats, such as progressive jpeg or interlaced png. once your image has been converted to progressive form, you can simply use it as usual. <img src="/images/stafff-photo-huge-progressive.jpg" alt="staff photo, taken in january of 1972"> when using a progressive image, the data is stored in such a way that the browser is able to rende...
... has been converted to progressive form, you can simply use it as usual. <img src="/images/stafff-photo-huge-progressive.jpg" alt="staff photo, taken in january of 1972"> when using a progressive image, the data is stored in such a way that the browser is able to render a low-quality representation of the image as soon as possible, then update the image as it loads—or after it's finished loading—to present it in full quality. note: progressive (or interlaced) images are inherently slightly larger than the non-progressive versions of the same images. whether the interlacing will benefit your users is up to you to determine. specifying multiple sources checking compatibility in javascript htmlmediaelement.canplaytype and mediasource.istypesupported... detecting playback errors ad...
Mapping the width and height attributes of media container elements to their aspect-ratio - Web media technologies
red in the way sizes are worked out on web documents when width and height attributes are set on them. this change means that the aspect ratio of the image is calculated by the browser early on and can then be used to correct the size needed to display the image before it has loaded, if css has been applied that causes problems with its display size. read on to find out more. jank problems when loading images in the olden days of web development, it was always seen as a good practice to add width and height attributes to your html <img> elements, so that when browsers first loaded the page, they could put a correctly-sized placeholder box in the layout for each image to appear in when it finally loads. without the width and height attributes, no placeholder space would be created, and when ...
...is is really useful for responsive layouts, but unfortunately it causes the jank problem to return — the above css overrides the width and height attribute information, meaning that if the image has not loaded for some reason, its height will be set to 0. when the image finally loads, the same jank will occur as the page layout is shifted to make space for it. a new way of sizing images before loading completes recognizing the problem, a wicg community group formed to propose an intrinsicsize attribute. folks from mozilla then expanded on this thinking, working on a proposal in the css box sizing level 4 draft to define an aspect-ratio property and propose the idea of using the width and height attributes to compute layout. fantasai & jen simmons collaborated with emilio, who worked on an exp...
Critical rendering path - Web Performance
out is determined, pixels are painted to the screen. optimizing the critical rendering path improves the time to first render. understanding and optimizing the critical rendering path is important to ensure reflows and repaints can happen at 60 frames per second, to ensure performant user interactions and avoid jank. understanding crp web performance includes the server requests and responses, loading, scripting, rendering, layout, and the painting of the pixels to the screen. a request for a web page or app starts with an html request. the server returns the html - response headers and data. the browser then begins parsing the html, converting the received bytes to the dom tree. the browser initiates requests every time it finds links to external resources, be they stylesheets, scripts, or e...
...they are loaded, and reducing the file sizes of those resources. performance tips include 1) minimizing the number of critical resources by deferring their download, marking them as async, or eliminating them altogether, 2) optimizing the number of requests required along with the file size of each request, and 3) optimizing the order in which critical resources are loaded by prioritizing the downloading critical assets, shorten the critical path length. ...
Optimizing startup performance - Web Performance
t files. try to send the minify version of the file to the browser and use compression like gzip or brotli. utilize resource hints (like preconnect or preload) whenever possible to indicate to the browser which files are more critical for your application. the more stuff you can do asynchronously, the better advantage your app can take of multicore processors. porting issues once the initial loading is done and the app's main code starts to run, it's possible your app may necessarily be single-threaded,especially if it's a port. the most important thing to do to try to help with the main code's startup process is to refactor the code into small pieces that can be done in chunks interspersed across multiple calls to your app's main loop, so that the main thread gets to handle input and the li...
...ur app's startup time. here are a few of them: download time keep in mind how long it will take the user to download your game's data. if your game is really big, really popular, or has to re-download content frequently, you should try to have as fast a hosting server as possible. you should also consider gzipping your data to make it as small as you can. gpu factors compiling shaders and uploading textures to the gpu can take time, especially for really intricate games. while this happens with native (non-web) games too, it can still be pretty annoying. avoid doing this without keeping the user apprised that the game is in fact still starting up. data size do your best to optimize the size of your game data; smaller level files will download and be processed faster than larger ones. sub...
Mobile first - Progressive web apps (PWAs)
the page and means that when the user has reached the end of a page, they have a signpost giving them an idea of where to go next. third, combining the two is also a good option — why not have a single button at the top of the page, which links to an anchor on the nav menu at bottom of the page? you could then also provide a link to get back up to the top of the article. conditional resource loading to actually implement responsive/adaptive designs, you will need to enlist a certain amount of conditional resource loading, again so that different devices can receive an optimal experience without having to shoulder the burden of many resources that they don't need. see below for more details. a simple example to demonstrate the concepts, i wanted to cover in this article, i created a very s...
...h of the content at 600px and centers it in the space available, then adds in a gradient and a nice background image for the wider layout. this is a key point - the background image is 126kb, and not ideal for narrow layouts. having it included in the "600 pixels or wider" media query means that narrow screen devices won't read that media query, so they will not waste their time and bandwidth downloading that image. note: firefox's responsive design view is a great way to get a quick idea of how your media queries are behaving themselves. try it out with tools > web developer > responsive design view. feature detection feature detection involves doing tests (usually in javascript) to determine whether a browser supports a certain feature, and then serving css or javascript to suit that situa...
Contributor's Guide - Archive of obsolete content
ined unit of code, which is usually stored in a file, and has a well defined interface. the use of modules greatly improves the maintainability of code, by splitting it up into independent components, and enforcing logical boundaries between them. unfortunately, javascript does not yet have native support for modules: it has to rely on the host application to provide it with functionality such as loading subscripts, and exporting/ importing names. we will show how to do each of these things using the built-in components object provided by xulrunner application such as firefox and thunderbird. private properties people have come up with several ways to emulate private properties using existing language features. this article discusses two common techniques: one using prefixes, the other closures...
page-mod - Archive of obsolete content
note that this is a very naive implementation, created only for demonstration purposes, and will not work properly in many real-world cases. attaching content scripts to tabs we've seen that the page-mod api attaches content scripts to documents based on their url. sometimes, though, we don't care about the url: we just want to e...
windows - Archive of obsolete content
de might not work with multiprocess firefox. globals functions open(options) open a new window. var windows = require("sdk/windows").browserwindows; // open a new window. windows.open("http://www.example.com"); // open a new window and set a listener for "open" event. windows.open({ url: "http://www.example.com", onopen: function(window) { // do stuff like listen for content // loading. } }); returns the window that was opened: var windows = require("sdk/windows").browserwindows; var example = windows.open("http://www.example.com"); require("sdk/ui/button/action").actionbutton({ id: "read", label: "read", icon: "./read.png", onclick: function() { example.close(); } }); this example uses the action button api, which is only available from firefox 29 onwards...
loader/sandbox - Archive of obsolete content
prove exception reporting: // evaluate code as if it was loaded from 'http://foo.com/bar.js' and // start from 2nd line. evaluate(scope, 'a ++', 'http://foo.com/bar.js', 2); version of javascript can be also specified via an optional argument: evaluate(scope, 'let b = 2;', 'bar.js', 1, '1.5'); // throws cause `let` is not defined in js 1.5. load scripts this module provides a limited api for loading scripts from local urls. data: urls are supported. load(scope, 'resource://path/to/my/script.js'); load(scope, 'file:///path/to/script.js'); load(scope, 'data:,var a = 5;'); globals functions sandbox(source) make a new sandbox that inherits principals from source. parameters source : string|window|null an object that determines the privileges that will be given to the sandbox. this argume...
ui/frame - Archive of obsolete content
is unloaded: for example, when the user closes a browser window, if that window has a toolbar containing this frame. after receiving this message, you ahould not attempt to communicate with the frame scripts. ready this event is emitted while a frame instance is being loaded, at the point where it becomes possible to interact with the frame although sub-resources may still be in the process of loading. it's the equivalent of the point where the frame's document.readystate becomes "interactive": var { frame } = require("sdk/ui/frame"); var frame = new frame({ url: "./frame.html" }); frame.on("ready", ping); function ping(e) { // message only this frame instance e.source.postmessage("pong", e.origin); } arguments event : this contains two properties: source, which defines a postme...
cfx to jpm - Archive of obsolete content
add-on's installed, enabled, or upgraded. with cfx, this defaults to "lib/main.js", although it can be set to a different file using the main field in package.json. in jpm, the entry point defaults to "index.js". so when switching over to jpm: either rename your "main.js" to "index.js" and move it from "lib" to the top level or add a main field to package.json with the value "lib/main.js". loading modules the jpm tool uses the same logic as node.js to determine how to resolve the argument to require(). in most respects this is the same as the old cfx logic. however there are a few differences, because old compatibility shims have been removed. requiring local modules suppose your add-on is structured into separate modules: my-addon lib main.js utils.js ...
Listen for Page Load - Archive of obsolete content
the following add-on listens to the tab's built-in ready event and just logs the url of each tab as the user loads it: require("sdk/tabs").on("ready", logurl); function logurl(tab) { console.log(tab.url); } you will find this console output in the browser console, not the web console. you don't get direct access to any content hosted in the tab. to access tab content you need to attach a script to the tab using tab.attach(). this add-on attaches a script to all open tabs. ...
Modifying Web Pages Based on URL - Archive of obsolete content
for example, you could rewrite my-script.js to use jquery. $("body").html("<h1>page matches ruleset</h1>"); then download jquery to add-on's data directory, and load the script and jquery together (making sure to load jquery first). // import the page-mod api var pagemod = requ...
Modifying the Page Hosted by a Tab - Archive of obsolete content
k/ui/button/action").actionbutton({ id: "style-tab", label: "style tab", icon: "./icon-16.png", onclick: function() { require("sdk/tabs").activetab.attach({ contentscriptfile: self.data.url("my-script.js") }); } }); you can load more than one script, and the scripts can interact directly with each other. so you can load jquery, and then your content script can use that. loading several content script files the data assigned to contentscriptfile can be a vector. scripts will be loaded in the same order as the vector. in the following example, we are loading two scripts, first.js & second.js. both scripts will be executed in the same context, so everything publicly defined in first.js will be accessible from second.js. // index.js var self = require("sdk/self"); var t...
Unit Testing - Archive of obsolete content
the sdk provides a framework to help create and run unit tests for your code. to demonstrate how it works we'll write some unit tests for a simple base64 encoding module. ...
Add-on SDK - Archive of obsolete content
e 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. tutorials getting started how to install the sdk and use the jpm tool to develop, test, and package add-ons. interact with the browser open web pages, listen for pages loading and list open pages. development techniques learn about common development techniques, such as unit testing, logging, creating reusable modules, localization, and mobile development. create user interface components create user interface components such as toolbar buttons, context menus, menu items, and dialogs. modify web pages modify pages matching a url pattern or dynamically modify...
Canvas code snippets - Archive of obsolete content
once the remote page has loaded, the remotepageloaded method fires. this method gets a reference to the iframe's window and draws this window to a canvas object. note that this only works if you are running the page from chrome. if you try running the ...
Forms related code snippets - Archive of obsolete content
see this example. autogrowing <textarea> this example shows how to make a textarea really autogrowing during a typing. insert some custom text in a <textarea> this example shows how to insert some html tags or smiles or any custom text in a textarea. image preview before upload the filereader.prototype.readasdataurl() method can be useful, for example, to get a preview of an image before uploading it.[article] this example shows how to use it in this way. note: the filereader() constructor was not supported by internet explorer for versions before 10. for a full compatibility code you can see our crossbrowser possible solution for image preview. filter the digitation into a form field this example shows the use of the onkeypress event during a digitation into a form field in order to ma...
HTML to DOM - Archive of obsolete content
iv tag like this: var dompars = htmlparser("<div id='userinfo'>john was a mediocre programmer, but people liked him <strong>anyway</strong>.</div>"); alert(dompars.getelementbyid('userinfo').innerhtml); to parse a complete html page, load it into an iframe whose type is content (not chrome). see using a hidden iframe element to parse html to a window's dom below. parsing complete html to dom loading an html document seems much simpler if it's loaded using the xmlhttprequest object. 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 = do...
Progress Listeners - Archive of obsolete content
progress listeners implement the nsiwebprogresslistener interface. note that if you just want to execute your code each time a page loads, you can use an an easier method, onpageload(). note that onpageload does not fire for back button clicks. in the examples below the progress listener is attached to the tabbrowser, which means you don't get any notifications for inactive tabs. firefox 3.5 includes a way to set up a listener for all tabs, selected and not: listening to events on all tabs. ...
Communication between HTML and your extension - Archive of obsolete content
custom event into the statechanged function that was handling the receipt of the ajax request. 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. // doc.location is a location object (see below for a link). // you can use it to make your code executed on certain pages only. if (doc && doc.addeventlistener) doc.addeventlistener("my-custom-event", myextension.customreceiv...
Migrating raw components to add-ons - Archive of obsolete content
support. as we roll this new behavior out, this document will be updated with additional information addressing scenarios we see developers encountering. 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. as you'll see, add-ons give you much more flexibility than simply loading a component, but in order to get started, all you'll need is your directory structure and install manifest. create a components/ directory in the root of your add-on's directory. add your js and binary components within that directory. they will be registered the first time firefox is run once your add-on is installed. automatic installation once you have an add-on packaged, users can install it...
Appendix: What you should know about open-source software licenses - Archive of obsolete content
ld be something like “if you pay me money” or “you can print up to 10,000 copies.” software licenses software is subject to copyright law. in order to use it (in the authorial sense), you need permission from the copyright holder. how software licenses work in order to duplicate, distribute, or modify software, you need a use permit. duplicating software would be burning cd-rs or downloading from the internet (copying from server to client). distributing software would be selling that cd-r or publishing the software on the internet. modifying software would be changing its functionality or adding new functions. duplication: copying a piece of software distribution: passing a piece of software to another person modification: modifying the software a typical software license will g...
Chapter 3: Introduction to XUL—How to build a more intuitive UI - Archive of obsolete content
s will be covered in chapter 4. opening a page if you specify a uri value for the src attribute in the browser element, that uri will be opened by default. if the src attribute's value changes, you can dynamically open a different web page or xul document. functions like back, forward, reload can all be called using the goback(), goforward(), and reload() methods. using the stop() method stops loading the page currently in the process of being opened. access restrictions with frames defined using html's frame and iframe elements, it is possible for a child frame to access its parent and ancestor frames by getting the parent and top properties of window objects. for an application that can open any web page, this could give a script on a web page access to an xul document's frame, creating a ...
Adding menus and submenus - Archive of obsolete content
used to accomplish this. if you have nothing to show on a menu, you should follow the standard used in firefox: show a single disabled item with an "(empty)" label. if filling your menu takes a noticeable amount of time, you should not make firefox (and your users) wait for it to fill up before displaying anything. it's best to show an item with a throbber image (see chrome://global/skin/icons/loading_16.png) so the user knows there's something going on, and asynchronously fill its contents. we'll look into some asynchronous techniques further ahead in the tutorial. adding elements to existing menus just as explained in the previous sections, the best place to overlay your extension menu is inside the tools menu. that is, unless there's a place inside the menu structure where your extension...
JavaScript Object Management - Archive of obsolete content
entbyid("xulschoolhello-string-bundle"); // you can make changes to the window dom here. } // more stuff }; window.addeventlistener( "load", function() { 〈namespace〉.browseroverlay.init(); }, false); there are some things you can't (or shouldn't) do inside load handlers, such as closing the window being loaded, or opening new windows, alerts or dialogs. the window has to finish loading before it can do any of these things. they are bad ui practices anyway and you should avoid them. if you really need to do something like this anyway, one way to do it is to have a timeout execute the code after a delay: init : function(aevent) { let that = this; this._stringbundle = document.getelementbyid("xs-hw-string-bundle"); window.settimeout( function() { window.alert(t...
XUL School Tutorial - Archive of obsolete content
the project is now published here following its sharing licenses. its contents have been modified from the original source as necessary. ...
Setting up an extension development environment - Archive of obsolete content
/github.com/noitidart/devprefs. maxversion needs to be set in install.rdf javascript.options.showinconsole = true. logs errors in chrome files to the error console. nglayout.debug.disable_xul_cache = true. disables the xul cache so that changes to windows and dialogs do not require a restart. this assumes you're using directories rather than jars. changes to xul overlays will still require reloading of the document overlaid. browser.dom.window.dump.enabled = true. enables the use of the dump() statement to print to the standard console. see window.dump for more info. you can use nsiconsoleservice instead of dump() from a privileged script. javascript.options.strict = true. enables strict javascript warnings in the error console. note that since many people have this setting turned off when...
Signing an XPI - Archive of obsolete content
ty. don't forget to delete the certificate from mozilla firefox once you've finished testing firefox 1.5: from the tools menu choose options->advanced->security->view certificates->authorities firefox 1.0: from the tools menu choose options->advanced->certificates->manage certificates->authorities press the import button. navigate to the folder containing x509.cert and choose it. in the downloading certificate dialog, tick trust this ca to identify software developers. and press the view button if you wish to examine the certificate more closely. press the ok button and you'll see your new certificate in the list of authorities. 2. attempt to install the signed extension either drag and drop or browse to and download the signed xpi. when the mozilla firefox software installation dialog a...
Promises - Archive of obsolete content
}); let data = xhr.response; // use the response to construct form data object for the // second request. let form = new formdata; form.append("id", data.id); form.append("content", data.content); // make the second request. xhr = yield request(updateurl, { data: form }); // use the response of the second request. notifyuser(xhr.responsetext); }); downloading remote files nearly all previous methods of downloading remote files have been superseded by the much simpler downloads.jsm module. the downloads object provides a promise-based api for downloading remote files, with full support for progress tracking, pause and resume, and, optionally, integration with the download manager ui. representative example usage components.utils.import("resource://g...
Adding preferences to an extension - Archive of obsolete content
ere.is.only.xul"> <setting pref="extensions.stockwatcher2.symbol" type="string" title="stock to watch" /> </vbox> adding the context menu adding the contextual menu is easy; all the work that needs doing is done in the stockwatcher2.xul file. the first step is to add the context attribute to the status bar panel: <statusbar id="status-bar"> <statusbarpanel id="stockwatcher2" label="loading..." context="stockmenu" onclick="stockwatcher.refreshinformation()" /> </statusbar> now when the user clicks on the status bar panel, the stock information refreshes, but when they right-click on it, a context menu pops up. defining the menu is also easy. all we need to do is add a popupset describing the menu to the statusbar, as follows: <popupset> <menupopup id="stockmenu...
cached - Archive of obsolete content
type description target eventtarget (dom element) the event target (the topmost target in the dom tree). read only. type string the type of event. read only. canbubble boolean does the event normally bubble? read only. cancelable boolean is it possible to cancel the event? read only. related events checking noupdate downloading progress cached updateready obsolete error ...
checking - Archive of obsolete content
type description target eventtarget (dom element) the event target (the topmost target in the dom tree). read only. type string the type of event. read only. canbubble boolean does the event normally bubble? read only. cancelable boolean is it possible to cancel the event? read only. related events checking noupdate downloading progress cached updateready obsolete error ...
error - Archive of obsolete content
the error event is fired when an error occurred while downloading the cache manifest or updating the content of the application. general info specification offline interface event bubbles no cancelable no target applicationcache default action none properties property type description target eventtarget (dom element) the event target (the topmost target in the dom tree). read only. type string the type of event. read only. canbubble boolean does the event normally bubble? read only. cancelable boolean is it possible to cancel the event? read only. related events checking noupdate downloading progress cached updateready obsolete error ...
noupdate - Archive of obsolete content
type description target eventtarget (dom element) the event target (the topmost target in the dom tree). read only. type string the type of event. read only. canbubble boolean does the event normally bubble? read only. cancelable boolean is it possible to cancel the event? read only. related events checking noupdate downloading progress cached updateready obsolete error ...
obsolete - Archive of obsolete content
type description target eventtarget (dom element) the event target (the topmost target in the dom tree). read only. type string the type of event. read only. canbubble boolean does the event normally bubble? read only. cancelable boolean is it possible to cancel the event? read only. related events checking noupdate downloading progress cached updateready obsolete error ...
updateready - Archive of obsolete content
type description target eventtarget (dom element) the event target (the topmost target in the dom tree). read only. type string the type of event. read only. canbubble boolean does the event normally bubble? read only. cancelable boolean is it possible to cancel the event? read only. related events checking noupdate downloading progress cached updateready obsolete error ...
Events - Archive of obsolete content
archived event pages domsubtreemodifiedmozaudioavailablemozbeforeresizemozorientationcachedchargingchangechargingtimechangecheckingdischargingtimechangedownloadingerrorlevelchangenoupdateobsoleteprogressupdateready ...
Localizing an extension - Archive of obsolete content
corresponding options.dtd file that looks like this: <!entity options_window_title "stockwatcher 2 preferences"> <!entity options_symbol.label "stock to watch: "> the "options_window_title" entity maps to the string "stockwatcher 2 preferences", which is used as the title of the preference window. the stockwatcher2.dtd file contains the mappings for the stockwatcher2.xul file: <!entity panel_loading "loading..."> <!entity menu_refresh_now.label "refresh now"> <!entity menu_apple.label "apple (aapl)"> <!entity menu_google.label "google (goog)"> <!entity menu_microsoft.label "microsoft (msft)"> <!entity menu_yahoo.label "yahoo (yhoo)"> update the xul files each xul file needs to reference its corresponding locale file. we also need to update the code to use the entities instead of the st...
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. this is meant to speed up the operation of mozilla, however in a fileserver based environment, this can be problematic: at several megabytes a pop, these files will take up a considerable amount of space, because each user has his own... loading these files from the server, and storing them back slows down the network, thus it may actually be faster without than with xul.mfl occasionnally gets corrupted, needing a manual intervention to wipe it out, before mozilla again works correctly. with quicklauncer (see above), mozilla's speed is actually quite adequate, even without xul.mfl for these reasons, it is desirable to disable the xul.mfl...
Adding the structure - Archive of obsolete content
barpanel-iconic" id="offline-status"/> <statusbarpanel class="statusbarpanel-iconic" id="security-button" onclick="browserpageinfo(null, 'securitytab')"/> </statusbar> the statusbar xul element defines a horizontal status bar where informative messages about an application's state can be displayed. it can contain both text messages (i.e. "done" in mozilla when a document finishes loading) and graphical messages (f.e. the lock icon in mozilla that shows whether or not a loaded document was encrypted with ssl). status bars comprise a series of panels, each one defined by a statusbarpanel xul element. each status bar panel displays a different kind of status information. graphical panels (like the one we are creating here that displays an icon) are given the statusbarpanel-iconic c...
Conclusion - Archive of obsolete content
mozilla will automatically detect that the file is an installer and ask you if you want to install the software. try installing the extension, restarting mozilla, and see if it works. 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
cument gets updated by the tinderbox server every time a build finishes. it displays a list of active tinderbox clients along with the result of their last build attempt. xmlhttprequest is easy to use in the simple case we have here. 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. xmlhttprequest will retrieve the document located at the given url and call the updatetinderboxstatus() function when it is done. notice that we defined the instance of xmlhttprequest as a global variable. this is because we need to refe...
Enabling the behavior - updating the status periodically - Archive of obsolete content
inderboxstatus, 60000); } window.settimeout(loadtinderboxstatus, 1000); window.settimeout schedules functions to run at some future time. we use it inside the loadtinderboxstatus function to make that function run a second (1,000 milliseconds) after startup and a minute (60,000 milliseconds) after each invocation. this allows users to get relatively frequent updates about tinderbox without overloading the tinderbox server or slowing down mozilla with requests. our code is now ready to run, but mozilla doesn't know about it yet. to enable its functionality, we have to add a reference to our javascript code into navigator.xul, just as we put a reference to our css code into that file back in specifying the appearance. put the javascript code into a file called tinderstatus.js in the same direct...
Editor Embedding Guide - Archive of obsolete content
simply call nsiwebbrowser->do_getinterface on the nsiwebbrowser to retrieve the nsieditingsession from it. from there you call editingsession->makewindoweditable(domwindow, editortype, pr_true). 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??!! nscomptr<nsieditingsession> editingsession; nsiwebbrowser->do_getinterface(getter_addrefs(editingsession)); if (editingsession) editingsession->makewindoweditable(domwindow, "html", pr_true); the valid editor types are: "text" (sim...
Using microformats - Archive of obsolete content
microformats allow web sites to provide semantic data to the browser in order to make it possible to present summaries of the information on a page without having to know how to parse the document itself. firefox 3 implements a global microformats object that provides access to microformats. this object and its api make finding and reading microformats easy to do. loading the microformats api the microformats object is created using the new javascript script loader added to firefox 3. to use the api, you need to first load the object: components.utils.import("resource://gre/modules/microformats.js"); once you've loaded the microformats api, you can manage microformats using the methods listed here; for information about parsing microformats, see parsing microformats in javascript. ...
Firefox - Archive of obsolete content
one sees them on irc or in bugs. it can be helpful to know exactly what these refer to. ...
JavaScript Client API - Archive of obsolete content
you may not imply, either directly or by omission, that your third party client is produced or endorsed by mozilla. by providing access to the firefox sync apis, mozilla is not granting you a license to any of our trademarks. before starting before you start learning the javascript api, you should spend some time on http://docs.services.mozilla.com/ reading about how the sync servi...
Creating a Help Content Pack - Archive of obsolete content
very basics of the syntax - elements, attributes, and element contents. understanding the syntax is important because small syntax errors can mean that a whole file won't be loaded correctly. however, while it may seem like this is a disadvantage, it's actually an advantage - if you make an error you'll know immediately, and you should be able to easily figure out what the problem is by directly loading the file in firefox. later, when we get to actually writing content, you'll need to know xhtml, but for now knowledge of the syntax should be enough. open up your favorite text editor and create the file content-pack.rdf. insert into it the following text: <?xml version="1.0"?> <rdf:rdf xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:nc="http://home.netscape.com/nc-rdf#">...
Helper Apps (and a bit of Save As) - Archive of obsolete content
ppen in onstartrequest, in the helper app dialog, and as a last ditch in the launching code. limitations of nsimimeinfo no way to say "do whatever the os default is." no support for command-line arguments. no support for multiple commands connected by pipes (mostly useful on unix). ongoing work support synchronous dialogs, not just asynchronous ones (fixes many issues related to pre-downloading, content-decoding, etc). reworking the nsimimeservice api to improve the quality of the mimeinfo we get. reworking the helper app dialog to save user choices better. gnome integration for unix. future work fix the deficiencies in nsimimeinfo. better support for mailcap syntax. possible kde integration. possibly reflecting the os settings in our helper app preferences (readonly? writable...
JavaScript crypto - Archive of obsolete content
server cgi */ var nickname= "mycertnickname"; var cert = "mkjflakdjfiwjflaksufklasf ..."; var forcebackup = false; function loadcertificate() { window.crypto.importusercertificates(nickname, cert, forcebackup); return false; } document.forms[0].onsubmit = loadcertificate; </script> signing text domstring signtext(domstring stringtosign, domstring caoption /* ... */); loading pkcs #11 modules long deletemodule(domstring modulename); long addmodule(domstring modulename, domstring libraryfullpath, long cryptomechanismflags, long cipherflags); loads or removes a new pkcs #11 module. in the add case, the module will be placed in the nss secmod.db database and will be loaded automatically on application restart. in the delete...
Metro browser chrome tests - Archive of obsolete content
the path points to the root tests directory, then all metro browser chrome tests will be run. for example, to run a specific test the command would be: ./mach mochitest-metro browser/metro/base/tests/mochitest/(testfile) writing browser chrome tests metro browser chrome tests make use of a common framework for defining and running tests. a simple test looks like this: gtests.push({ desc: "test loading about:blank", setup: function () { }, teardown: function () { }, run: function () { yield addtab("about:blank"); is(tab.browser.currenturi.spec, "about:blank", "about:blank is loaded"); } }); function test() { runtests(); } gtests contains individual tests that make up the library of tests your test file will contain. each test can have start up and tear down logic, plus the b...
Mozilla Application Framework in Detail - Archive of obsolete content
rom. documentation. web services mozilla includes built-in support for popular web services standards xml-rpc, soap, and wsdl as well as a simple xmlhttprequest object similar to the one in ie. all services are available from javascript code, which allows even simple xul+js applications to take advantage of them. mozilla's xml-rpc support includes synchronous and asynchronous requesting and downloading of data from a server. its soap support is broad and includes.... mozilla has introductory support for wsdl... mozilla engineers have written and are in the process of refining a new security model for web services that will ease the deployment of applications using web services while maintaining the security of sites inside the user's firewall. more information using the mozilla soap api (an a...
New Security Model for Web Services - Archive of obsolete content
_true if access granted else pr_false void invalidatecache(in string atransporturi); invalidate cached entry for the given transport uri. empty the cache by passing in a empty string nswebscriptsaccess(implements nsiwebscriptsaccessservice) maintains access information, for servers, in an access-info-cache ( hashtable ). 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. den...
Overview of how downloads work - Archive of obsolete content
one way is to encounter a file with an unknown content type, the other is to choose "save link target as" from the context menu of a link. things like file|save page as, save image as, etc. are all part of the second codepath. this document describes both codepaths (see below for the second one). click on the images to display them "stand-alone" in the browser, which may resize them to fit the browser window. 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. ...
Configuration - Archive of obsolete content
e actual icon file should be stored in the webapp bundle. status turns the status messages on or off for this web app: yes or no location turns the readonly location bar on or off for this web app: yes or no navigation turns the hotkey history navigation (alt+left, alt+right and alt+home) on or off for this web app: yes or no splashscreen filename of an html page to be displayed while the app is loading. the file must be located in the web app home directory: splashscreen.html include uris that should be opened in the web app, rather than in the default browser. an asterisk is used to match any string. separate multiple uris with commas: *google.com, *yahoo.com exclude urls that should be opened in the default browser, rather than in the web app. syntax is the same as for include. trayicon indic...
HostWindow - Archive of obsolete content
dth or quickly collapse it. the splitter itself cannot be hidden as it is the only ui to show a collapsed sidebar. when not displayed the entire sidebar area, including the splitter are hidden. note: the sidebar is currently not supported. we are considering whether to support a sidebar in future versions of prism and welcome input on this subject. status - area of the statusbar that displays the loading status message and a "percent complete" progress bar, as well as the "gear" menu that provides access to prism commands such as displaying the error console. to display the status bar, the statusbar option in webapp.ini must be set to true. command menu - a popup menu showing several prism-specific commands. ...
Scripting - Archive of obsolete content
sion is loaded into the browser chrome window. it can contain the following functions: startup when the app starts, before the user interface is displayed. since the web application has not yet loaded, the window object is still undefined. preload just before the user interface is displayed. returning false causes the application to terminate. load after the main application windows has finished loading. the window object has been initialized and can be used. error if there is an error loading the main app page (e.g. the server is not accessible). shutdown just before the application terminates. prism exposes desktop integration features through an property of the window object called platform. the platform property implements the nsiplatformglue interface, whose methods are described in the fo...
Prism - Archive of obsolete content
up notifications. customization: apps can be run using a shared browser runtime and customized using client-side script (similar to greasemonkey). custom stylesheets can be used to tweak the ui. architectural overview prism is a xulrunner application. in addition to the browser engine included in xulrunner, it consists of: web app bundle management: code for creating new web app bundles and loading existing bundles. shortcut creation ui: a dialog box lets the user specify attributes of the web app (name, uri, icon, shortcut locations). javascript api: an api that can be used by scripts inside the bundle to customize the application. we are refining this approach to make the api applicable in as many environments as possible (e.g. it might be useful even for applications running in a nor...
Standalone XPCOM - Archive of obsolete content
nsnativecomponentloader: autoregistering succeeded inital print: initial value set value to: xpcom defies gravity final print : xpcom defies gravity test passed. test failed: what went wrong? the most common case of why the sample would have failed if you didn't run it from the bin directory. here are some error messsages and possible ways of fixing them. ./nstestsample: error in loading shared libraries: libxpcom.so: cannot open shared object file: no such file or directory ld_library_path not set. to fix, setenv ld_library_path . (note the dot). link errors when building xpcom standalone this is usually due to xpcom not being built standalone. make sure you did configure --enable-standalone-modules=xpcom. what's the difference between standalone and non-standalone xpcom? ...
Running Tamarin performance tests - Archive of obsolete content
t avm needs to point to android_shell.sh which is a proxy for running the tests on the phone. the /android-public/android-vars.sh script has commented-out examples of the environment settings for running tests on the android avm shell. to recap the other environment settings: - set the builtinabc environment variable to the path of the /generated/builtin.abc. - you may build the .abc files by downloading the latest asc.jar. the latest asc.jar can be downloaded from from ftp://ftp.mozilla.org/pub/js/tamarin...latest/asc.jar. also the source to asc.jar may be downloaded and rebuilt from http://opensource.adobe.com/wiki/dis...exsdk/flex+sdk. - set the asc environment variable, as described above. - set the shellabc environment variable to the path of the /generated/shell_toplevel.abc. adb 'adb' stan...
Tamarin Build System Documentation - Archive of obsolete content
h platform until 2 minute is exceeded. the set of smoke tests can contain any shell build and any test suite (including performance). the smoke test list is constantly updated to contain the most recent failures, most frequent failures, and the newest testcases. the idea is to catch test failures in a few minutes rather than running the complete test run (1h 45m). the smoke test including downloading the shell takes about 3-4 minutes. the test phase runs all functional testcases including acceptance tests, cmdline tests, and selftests. the acceptance tests are the majority and are run on all shells (release, release-debugger, debug, debug-debugger). the test phase takes approximately 1 hour 45 minutes. the performance and deep phases do not run synchronously. the phases run when slaves are...
The Download Manager schema - Archive of obsolete content
f the file. preferredapplication text the preferred application to use to open the file after the download is complete. preferredaction integer the action constant from nsimimeinfo representing the action to take upon completing the download. default 0 (save to disk); may not be null. autoresume integer 0 if the file should not automatically resume downloading, 1 if it should. defaults to 0, and may not be null. see also nsidownloadmanager nsidownloadmanagerui nsidownloadprogresslistener ...
The life of an HTML HTTP request - Archive of obsolete content
the webshell then tells its documentloader to load (command "view") the specified url. [note: passes nswebshell.mobserver as nsistreamobserver and the webshell as nsicontentviewercontainer to the docloader.] (2) the document loader calls ns_openuri with the url to begin transfering the requested file. ...
Tuning Pageload - Archive of obsolete content
this document explains which preferences to tweak to affect your pageload time. you use the url about:config or the file prefs.js in your profile to change these. to best understand what the following preferences affect, there are a few things you should know. the data flows in gecko as follows: network -> necko -> parser -> content sink -> content model -> rendering model -> layout -> painting. ...
Writing textual data - Archive of obsolete content
gs at the end, you need to call finish and write its data to the stream. note that not many character encodings need it, but for those that do calling this is important for proper output. var fin = converter.finish(); if (fin.length > 0) os.write(fin, fin.length); os.close(); converting a string into a stream sometimes, it is useful to convert a string into a stream, for example for uploading it using nsiuploadchannel. the example here requires gecko 1.8 (firefox 1.5, seamonkey 1.0). 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 =...
Creating XPI Installer Modules - Archive of obsolete content
ntent, where the main xul file and the other resources live once they are installed. package creation overview this tutorial describes the following sequence of steps for creating a new package: developing the resources organizing the resources creating the contents.rdf file making the barley install script creating a xpi you can examine (or install!) the package described here by downloading the barley xpi file and using a zip unarchiver[zip] to open it. all of the resources described in this article are in the xpi archive and can be adapted for use in your own development. 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. the barley package ui is a single xul window with an accompanying ...
Install Wizards (aka: Stub Installers) - Archive of obsolete content
ose the destination directory for the installation, and select from various other options. subsequently, when users click the "install" button the install wizard downloads and installs only the selected software packages. this saves low-bandwidth users considerable time since they do not need to download software packages they may not be interested in. (the stub installer accomplishes this by downloading the xpinstall engine along with the selected software packages. it then proceeds to extract the xpinstall engine and feed it the downloaded software packages to install.) the stub installer code includes: the logic to display the install wizard widgets and dialogs the code that reads in the configuration file (config.ini) and dynamically installs from the net or from local xpi modules found n...
Trigger Scripts and Install Scripts - Archive of obsolete content
d perform simple software installations. install scripts use the install, file, installversion and platform-specific installation object methods to initialize, queue, manage, and perform the installation of one or more software packages. these install scripts are typically located at the top level of the xpi archives in which the installations are stored. a trigger script may trigger the downloading of a xpi, which in turn will use its own install.js script to manage the complete installation. ...
Install Object - Archive of obsolete content
show the use of the xpinstall api. the majority of this api is now deprecated and as of gecko 1.9 no longer available. extension, theme, and plug-in developers must switch away from install.js based packages to the new packaging scheme with an install.rdf manifest. in particular plugin developers should see how to package a plugin as an extension. install use the install object to manage the downloading and installation of software with the xpi installation manager. overview the install object is used primarily in installation scripts. in all cases, the install object is implicit--like the window object in regular web page scripts--and needn't be prefixed to the object methods. the following two lines, for example, are equivalent: f = getfolder("program"); f = install.getfolder("program"); an i...
XPJS Components Proposal - Archive of obsolete content
onents will 'live' in.js files. just as with native component modules each of these .js files will be expected to have the functions: nsregisterself nsgetfactory nsunregisterself (optional) nscanunload (optional) each .js file might implement one or more components. we will have one native module - called the xpjsmanager - which holds this system together. the xpjsmanager is in charge of loading these .js files, helping them register themselves, and acting as an intermediary between the xpcom component manager and the js code. xjs components are not run in browser windows. each .js file (let's call it a module) is started up and run in the context of a relatively 'raw' js global object. the standard (non-dom) js classes will be available. the xpconnectcomponents object will be available...
browser.type - Archive of obsolete content
y using window.content. content-targetable one browser among many for content. the content that is loaded inside the browser is not allowed to access the chrome above it. this is the preferred value for any browser element in an application, which will use multiple browsers of equal privileges, and is unselected at the moment. chrome (default behaviour): a browser, intended to be used for loading privileged content using a chrome:// uri. don't use for content from web, as this may cause serious security problems! see also more information in the xul tutorial and iframe ...
image.onload - Archive of obsolete content
this applies whether the image is applied via the src attribute or the list-style-image style property. ...
onerror - Archive of obsolete content
...
prefwindow.onload - Archive of obsolete content
...
XUL Events - Archive of obsolete content
released. attribute: onkeyup load this event is sent to the window after it has been fully loaded. you should place this event handler on the window element. this event may also be used on the image element, or an element that accepts an image attribute, and will be fired when the image has finished loading. for images, this event does not bubble up the element tree, so it will not conflict with the window's load event. attribute: onload mousedown this event is sent when the mouse is pressed on an element but not released. attribute: onmousedown ...
Accessing Files - Archive of obsolete content
file and stream guide: [ nsiscriptableio | accessing files | getting file information | reading from files | writing to files | moving, copying and deleting files | uploading and downloading files | working with directories ] important note: the pages from the file and stream guide use the io object (nsiscriptableio), which was not available in any released version of the platform (pending some fixes). there are alternative xpcom apis you can use, your help in updating this pages to use the supported api is very much welcome! other documentation on files and i/o not using the unavailable nsiscriptableio apis: code snippets: file i/o, open and save dialogs, reading textual data, writing textual data, list of file-related error codes. accessing files this section describes how to create...
Working With Directories - Archive of obsolete content
file and stream guide: [ nsiscriptableio | accessing files | getting file information | reading from files | writing to files | moving, copying and deleting files | uploading and downloading files | working with directories ] important note: the pages from the file and stream guide use the io object (nsiscriptableio), which was not available in any released version of the platform (pending some fixes). there are alternative xpcom apis you can use, your help in updating this pages to use the supported api is very much welcome! other documentation on files and i/o not using the unavailable nsiscriptableio apis: code snippets: file i/o, open and save dialogs, reading textual data, writing textual data, list of file-related error codes. a reference to a directory may be created in the same way a...
Getting File Information - Archive of obsolete content
file and stream guide: [ nsiscriptableio | accessing files | getting file information | reading from files | writing to files | moving, copying and deleting files | uploading and downloading files | working with directories ] important note: the pages from the file and stream guide use the io object (nsiscriptableio), which was not available in any released version of the platform (pending some fixes). there are alternative xpcom apis you can use, your help in updating this pages to use the supported api is very much welcome! other documentation on files and i/o not using the unavailable nsiscriptableio apis: code snippets: file i/o, open and save dialogs, reading textual data, writing textual data, list of file-related error codes. the nsifile object has a number of useful attribute...
Reading from Files - Archive of obsolete content
file and stream guide: [ nsiscriptableio | accessing files | getting file information | reading from files | writing to files | moving, copying and deleting files | uploading and downloading files | working with directories ] important note: the pages from the file and stream guide use the io object (nsiscriptableio), which was not available in any released version of the platform (pending some fixes). there are alternative xpcom apis you can use, your help in updating this pages to use the supported api is very much welcome! other documentation on files and i/o not using the unavailable nsiscriptableio apis: code snippets: file i/o, open and save dialogs, reading textual data, writing textual data, list of file-related error codes. reading data from a file involves getting a reference to a ...
Writing to Files - Archive of obsolete content
file and stream guide: [ nsiscriptableio | accessing files | getting file information | reading from files | writing to files | moving, copying and deleting files | uploading and downloading files | working with directories ] important note: the pages from the file and stream guide use the io object (nsiscriptableio), which was not available in any released version of the platform (pending some fixes). there are alternative xpcom apis you can use, your help in updating this pages to use the supported api is very much welcome! other documentation on files and i/o not using the unavailable nsiscriptableio apis: code snippets: file i/o, open and save dialogs, reading textual data, writing textual data, list of file-related error codes. to write to a file, an output stream is used. an ou...
Moving, Copying and Deleting Files - Archive of obsolete content
file and stream guide: [ nsiscriptableio | accessing files | getting file information | reading from files | writing to files | moving, copying and deleting files | uploading and downloading files | working with directories ] important note: the pages from the file and stream guide use the io object (nsiscriptableio), which was not available in any released version of the platform (pending some fixes). there are alternative xpcom apis you can use, your help in updating this pages to use the supported api is very much welcome! other documentation on files and i/o not using the unavailable nsiscriptableio apis: code snippets: file i/o, open and save dialogs, reading textual data, writing textual data, list of file-related error codes. there are several methods of the nsifile object whi...
TOC - Archive of obsolete content
Archive › Mozilla › XUL › FileGuide › TOC
file and stream guide: [ nsiscriptableio | accessing files | getting file information | reading from files | writing to files | moving, copying and deleting files | uploading and downloading files | working with directories ] important note: the pages from the file and stream guide use the io object (nsiscriptableio), which was not available in any released version of the platform (pending some fixes). there are alternative xpcom apis you can use, your help in updating this pages to use the supported api is very much welcome! other documentation on files and i/o not using the unavailable nsiscriptableio apis: code snippets: file i/o, open and save dialogs, reading textual data, writing textual data, list of file-related error codes. ...
Menus - Archive of obsolete content
images context-sendimage sends an image in an email images context-setdesktopbackground sets an image as the desktop background images context-blockimage blocks an image images context-back goes back a page context-forward goes forward a page context-reload reloads a page context-stop stops loading a page context-bookmarkpage bookmarks a page context-savepage saves a page context-sendpagetodevice send page to device context-sendpage send page in an email context-viewbgimage views a background image context-undo undo editable text context-cut cuts to clipboard editable text...
stop - Archive of obsolete content
Archive › Mozilla › XUL › Method › stop
...
webProgress - Archive of obsolete content
...
Sorting and filtering a custom tree view - Archive of obsolete content
= document.getelementbyid("tree"); loadtable(); } //this function is called every time the tree is sorted, filtered, or reloaded function loadtable() { //remember scroll position. this is useful if this is an editable table //to prevent the user from losing the row they edited var topvisiblerow = null; if (table) { topvisiblerow = gettopvisiblerow(); } if (data == null) { //put object loading code here. for our purposes, we'll hard code it. data = []; //the property names match the column ids in the xul. this way, we don't have to deal with //mapping between the two data.push({name: "leonardo", description: "leader", weapon: "dual katanas"}); data.push({name: "michaelangelo", description: "party dude", weapon: "nunchaku"}); data.push({name: "donatello", description: "does ...
Introduction - Archive of obsolete content
datasource is loaded via its url. some rdf datasources are provided with mozilla -- their url's start with 'rdf:'. otherwise, the datasource is loaded as any other url is loaded. if the datasource is already loaded and cached, the template builder can begin work right away. otherwise, there isn't anything to do until the data is loaded. actually, this isn't quite true. the rdf service starts the loading of the datasource in the background, and the template builder goes through the process of building content anyway. naturally, since there is no data yet, no results will be available, so the builder ends up building nothing. once some data starts arriving, the template builder scans its information to see if some results can be created. if so, some content can be generated. if not, nothing gets g...
RDF Modifications - Archive of obsolete content
ternally, this isn't any different than the other notifications, but it is worth discussing separately. when the rdf parser loads rdf/xml, it starts with a new empty datasource, and as the parser parses the input data, it calls the datasource's assert function to add each found triple. in effect, this isn't any different than adding the same set of triples yourself using the assert method. when reloading a datasource, you might think that the rdf parser removes all the existing data, loads the new data, and adds it to the datasource. or, you might think that it creates a fresh datasource with the new data. actually, the parser does something smarter. when reloading a datasource, it keeps the existing rdf triples intact, and only modifies the datasource based on what has changed. when parsing, any...
Rule Compilation - Archive of obsolete content
this step involves working through the query rules and processing them into internal structures. thus, changing the rule elements around dynamically doesn't affect anything. however, rebuilding the template (using the builder.rebuild method) will recompile the query and rules and reapply the template again. this means that you can change the rules using...
Static Content - Archive of obsolete content
at the element as already present as long as some element with the same tag name exists. if you were to change the static content to be some other element besides a menupopup, it won't match, so the builder will create a new one when handling the action. this becomes useful when using multiple rules and we'll see some examples of this later. here is the example to try. note that the workaround of loading the datasource beforehand as mentioned for the last example isn't necessary, as the existence of the static content is another effective workaround. so, if you're using menulists with templates and the data isn't displaying properly when the data hasn't loaded, try using a static menupopup. it doesn't even need to have any items in it. the static content may be placed before or after the template...
Template Builder Interface - Archive of obsolete content
the ref attribute (or the ref property) and the template will be rebuilt automatically. in the example above, there will be two datasources attached to the tree. they will both be loaded and the template reconstructed. note that if one of the datasources is already loaded it will not be loaded again. this is convenient when you want to simply add a new datasource to an existing template without reloading existing data. if you do want to reload the data, you can call the builder's refresh method: tree.builder.refresh(); this will reload the datasource attached to the template. if there is more than one datasource, as above, all of them will be reloaded. due to the nature of the way templates are updated, you don't usually need to rebuild a template after a refresh call, although there may situtat...
Template Logging - Archive of obsolete content
xml data was loaded and parsed correctly. if null, then the datasource could not be loaded, or hasn't yet been loaded. if the datasource load and parsing was successful, the datasource will be set to the xml document. for example: if (root.builder.datasource instanceof xmldocument) alert("xml datasource loaded ok"); be careful, as the datasource will only be set once the document has finished loading and has been parsed, so don't check this property too early. you may also get an error if you manipulate or analyze the template while the datasource is loading. you could iterate and wait using a timer. future versions may include other features to make it easier to debug problems with data loading. « previous ...
Complete - Archive of obsolete content
s (us). to make it eaiser to support different locales, developers usually place anything that might depend on the locale in separate files in a separate directory. in the custom toolbar button extension, the only things that might depend on the locale are the text strings displayed in the user interface. these are in the files button.xul and button.js. xul and javascript each have mechanisms for loading text strings from the correct locale directory. this extension only uses the xul method. its javascript code gets the text strings it needs from the xul. for more information about working with locales, see the main localization page here. how a text sting gets localized when you press button 1 you see an message in english or french, depending on your application's locale. this is how it happens...
Adding Methods to XBL-defined Elements - Archive of obsolete content
he children element itself. the length of the anonymous array of the outer box is two, the first element the description element and the second the stack element. constructors and destructors xbl supports two special methods created with separate tags, constructor and destructor. a constructor is called whenever the binding is attached to an element. it is used to initialize the content such as loading preferences or setting the default values of fields. the destructor is called when a binding is removed from an element. this might be used to save information. there are two points when a binding is attached to an element. the first occurs when a window is displayed. all elements that have xbl-bound content will have their constructors invoked. the order that they are called in should not be re...
More Event Handlers - Archive of obsolete content
learn more about the box object in a later section, but it holds information pertaining to how the element is displayed, including the x and y position of the element. in this example code, these coordinates are subtracted from the event coordinates to get the event position relative to the element. load events the load event is sent to the document (the window tag) once the xul file has finished loading and just before the content is displayed. this event is commonly used to initialize fields and perform other tasks that need to be done before the user can use the window. you should use a load event to do these kinds of things as opposed to adding a script at the top level outside of a function. this is because the xul elements may not have loaded or fully initialized yet, so some things may not...
Progress Meters - Archive of obsolete content
xul has a progressmeter element which can be used to create these. there are two types of progress meters: determinate and indeterminate. determinate progress meters are used when you know the length of time that an operation will take. ...
Skinning XUL Files by Hand - Archive of obsolete content
the various states of that button. for this reason, it can be very efficient to use button classes that appear in the global skin and to make new classes only when necessary. browse through the global skin to familiarize yourself with what's there. in the next few sections, you will be importing this style information into a custom stylesheet and extending it with new style rules for your xul. loading stylesheets in xul for your custom skin, let's assume you want to skin the xul file, xulnote_sample1.xul. to work with this xul file, save it locally and rename itsample1.xul. though applying inline styles is a perfectly legal move in xul and a good idea in some rare cases, in general you should try to keep the xul skin separate from the actual xul structure. this independence of function and f...
Using Remote XUL - Archive of obsolete content
s an element with a flex of "1", so the first element might show up as twice as wide as the second. in our case, the iframe will be the only flexible element in our document, so we don't have to worry about its value and give it a standard value of 1. [optionally add something about how flex only applies to one axis] note that for remote xul documents you can see changes you make to the ui by reloading the document with your browser's "reload" function, just as with a typical html page. source | rendered step 3: menus and buttons the mozilla.org web site uses an html navigation bar on the left-hand side of its pages to provide site navigation. the bar consists of a set of links organized into four main categories: the mozilla organization, developer docs, testing, and tools. the bar also c...
XUL Changes for Firefox 1.5 - Archive of obsolete content
non zero-based behaviour should be changed. <stringbundle> the <stringbundle> element has a strings property which may be used to retrieve an enumeration of all of the strings in the bundle. draggable tabs the tabbrowser now allows the user to rearrange tabs by dragging them. <tabbox> the <tabbox> element now supports a selectedindex attribute to specify the tab to be selected by default. loading overlays dynamically xul now supports loading overlays dynamically with the document.loadoverlay function. original document information author(s): neil deakin ...
XUL accessibility guidelines - Archive of obsolete content
ith images it is recommended to use both a text label in the label attribute and image alt text in the tooltiptext attribute. view the code examples below. <image src="stop.png" tooltiptext="stop" /> <html:img src="stop.jpg" alt="stop" /> <html:img src="decorative_image.jpg" alt="" /> <!-- in html the alt attribute is required. --> <toolbarbutton label="stop" image="stop.png" tooltiptext="stop loading the page" /> title provide unique titles to window container elements such as windows, wizards, and dialogs. titles provide users the most basic information about the application. the title is often the first thing spoken by a screen reader when an application is opened or activated. users can also refer back to the title to get a sense of where they are located. titles are displayed in the to...
iframe - Archive of obsolete content
y using window.content. content-targetable one browser among many for content. the content that is loaded inside the browser is not allowed to access the chrome above it. this is the preferred value for any browser element in an application, which will use multiple browsers of equal privileges, and is unselected at the moment. chrome (default behaviour): a browser, intended to be used for loading privileged content using a chrome:// uri. don't use for content from web, as this may cause serious security problems! transparenttype: one of the values belowset the background of an iframe as transparent.transparentthis results in the iframe's background being transparent. this can be used to workaround things like bug 540911 inherited from xul element align, allowevents, allownega...
image - Archive of obsolete content
Archive › Mozilla › XUL › image
element and shrinks both the width and height down proportionally. attributes onerror, onload, src, validate properties accessibletype, src style classes alert-icon, error-icon, message-icon, question-icon examples <image src='firefoxlogo.png' width='135' height='130'/> attributes onerror type: script code this event is sent to an image element when an error occurs loading the image. image.onload type: script code this event handler will be called on the image element when the image has finished loading. this applies whether the image is applied via the src attribute or the list-style-image style property. if you change the image, the event will fire again when the new image loads. this event will not bubble up the element tree. src type...
prefwindow - Archive of obsolete content
if the routine returns true, the dialog will indeed go away, but if it returns false it will not. ondialogdisclosure type: script code the code in this attribute is called when the "disclosure" button is pressed. ondialoghelp type: script code the code in this attribute is called when the "help" button is pressed. prefwindow.onload type: script code when a window finishes loading, it calls this event handler on the prefwindow element. title type: string the text to appear in the title bar of the window. type type: string set this attribute to child for preference dialogs that are child dialogs of a main preferences window. this ensures that the preferences are only saved when the main dialog is closed, if this is the appropriate behaviour for the platfor...
progressmeter - Archive of obsolete content
known beforehand. more information is available in the xul tutorial. attributes max, mode, value properties accessibletype, max, mode, value examples <progressmeter mode="determined" value="82"/> <progressmeter mode="undetermined"/> <!-- switching modes while the mouse is over a button --> <progressmeter mode="determined" id="myprogress"/> <button label="example" onmouseover="setloading(true)" onmouseout="setloading(false)"/> function setloading(state){ document.getelementbyid('myprogress').mode = (state) ? 'undetermined' : 'determined'; } attributes max type: integer the maximum value that progressmeter may have. the default value if not specified is 100 such that the value may be used as a percentage. mode type: one of...
Creating XULRunner Apps with the Mozilla Build System - Archive of obsolete content
illa build system. for the purposes of this article i'm using dave townsend's mccoy as an example. it's a straightforward xulrunner app that nonetheless uses most of the features any given application is likely to need. building xulrunner do i need to build xulrunner? if you are just creating a xulrunner app with some c++ components, you can avoid the challenge of building xulrunner itself by downloading a prebuilt sdk. do this if at all possible and send me some of the money you save on psychiatry sessions. if you are actively modifying xulrunner as part of your development, however, you'll have to bite the bullet. for example, you may be fixing bugs in xulrunner, applying patches from bugzilla that aren't yet checked into the main repository or making your own changes to deploy as part of a cus...
Deploying XULRunner - Archive of obsolete content
ons at xul application packaging. if your installer is capable of determining whether or not xulrunner has been registered on the system you could perform the check and register the appropriate version if necessary. after that, the app could be installed to the registered xulrunner and appear in start menus, lists of installed programs, etc. (bonus points for checking the operating system and downloading the right xulrunner on the fly, or bundling them into your installer). registration and app installation are performed with command line switches as outlined in the xulrunner section of article command line options. 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 la...
Mozilla.dev.apps.firefox-2006-10-06 - Archive of obsolete content
zing the first letter of firefox menu items in the ff ui. engineering student project - industry coach paul betts from ohio state university is looking for someone from mozilla to be his "industry coach" for engineering 494 - how great ideas turn into great products. mozilla is a great product afterall. reload vs. reload from cache discussion regarding the lack of user understanding regarding reloading and reloading from the cache and how to address it. why suggestions in search bar doesn't work for me? discussion regarding suggestions in the search bar not functioning in the october 3rd nightly build of ff 2.0. places in firefox 3 discussion regarding places (a new system for storing bookmarks, histroy and other page info) in firefox 3. a wiki has been set up aswell as weekly meetings, and a...
2006-10-06 - Archive of obsolete content
zing the first letter of firefox menu items in the ff ui. engineering student project - industry coach paul betts from ohio state university is looking for someone from mozilla to be his "industry coach" for engineering 494 - how great ideas turn into great products. mozilla is a great product afterall. reload vs. reload from cache discussion regarding the lack of user understanding regarding reloading and reloading from the cache and how to address it. why suggestions in search bar doesn't work for me? discussion regarding suggestions in the search bar not functioning in the october 3rd nightly build of ff 2.0. places in firefox 3 discussion regarding places (a new system for storing bookmarks, histroy and other page info) in firefox 3. a wiki has been set up aswell as weekly meetings, and a...
2006-10-20 - Archive of obsolete content
october 17th j. paul reed announced that: sparky, the linux performance test machine for the 1.8 branchs, is being decommissioned. he also added that the linux performance test data is now being provided by bl-bldlnx01. paul would like to hear from anyone who is against this decision. he can be contacted via: email: preed@mozilla.com irc: preed on irc.mozilla.org phone: 650.903.0800 x256 uploading language packs to amo on october 17th benjamin smedberg brought the following to the attention of the localizers and the build team: that he is planning to upload the firefox 2 language packages currently located at http://releases.mozilla.org/pub/mozi...rc3/win32/xpi/ to addons.mozilla.org in the next few days. this will make the language packages available to everyone. if you anyone has ques...
2006-10-20 - Archive of obsolete content
off of simplified chinese firefox 2 attention dictionary providers, or: warning, amo sucks there was at amo (addons.mozilla.org), which has been being fixed. people who want to upload dictionaries should be advised and check #amo at irc.mozilla.org. feedback from localizers regarding sunbird/lightning 0.3 release the sunbird/lightning developers are requesting feedback on release 0.3. uploading language packs to amo benjamin smedberg is ready to upload languange packs from here to addons.mozilla.org. if there are issues or questions, contact mozilla.dev.builds. firefox rc 3 is there, staging servers, too firefox rc3 build is located here. community was encouraged to do testing. discussions how to file a legal approval for a dictionary? discussion about how to file a legal app...
2006-12-08 - Archive of obsolete content
summary: mozilla.dev.l10n - december 8, 2006 announcements mozilla sponsored server for l10n the server for mozilla sponsored server for l10n should be up and running soon. seamonkey 1.1b es-es language and region packs language and region packs for seamonkey 1.1b is ready for downloading. new strings in thunderbird new strings in thunderbird new bugzilla-staging.mozilla.org a staging server for a new bugzilla upgrade. discussions none for this week. meetings none for this week. authors paul yanchun gu (gpaul) aditya nanda kuswanto(vipers101) ...
2006-12-01 - Archive of obsolete content
summary: mozilla.dev.security - november 25, 2006 to december 1, 2006 return to mozilla-dev-security announcements none during this week. discussions protocol security daniele rizzo posted a question as to whether or not it is possible to enable/disable the privilege of universalxpconnect in a 'entire' protocol (http://, file://). problem with downloading signed script components in a firefox extension andrew groom is having problems getting an extension to download a signed script and would appreciates some help with his problem. meetings none during this week. ...
JS-Engine FAQ - Archive of obsolete content
ser is not part of js but part of mozilla browser which makes it available to script in the browser using xpconnect. an alternative would be to use built-in e4x. newly created threads in js from mozilla_1_8_branch causes to hang in windows patch from bug 351602 should fix the problem. after applying that patch, recompile js and define js_use_only_nspr_locks in the build. spidermonkey library loading mechanism? to write wrappers in pure javascript to interface with any c library on the system there are mechanisms such as xpcshell, wxjs, jsdb, jsni coding spidermonkey in c check out this tutorial how to compile tamarin on linux/x86 there is a patch that allows you to compile it. rhino what is the performance between rhino js and native java rhino js is significantly slower in run-time ...
2006-11-17 - Archive of obsolete content
reflow branch testing wanted l. ...
2006-09-06 - Archive of obsolete content
n the problems and possible solutions running cygwin/g++ compiled xpcom components with windows-based gecko-sdk/xulrunner dll/exes. threading in xpcom rules on threading in xpcom or to firefox extensions. how to build xpcom component on mac os x a tutorial on how to build xpcom component on mac os x firefox crashes when calling a function provided by a .so library a solution to the problem loading a shared library when using xpcom firefoxes crashes while getting url in xpcom solutions to resolve the problem of the firefox crash when trying to get the path and the prepath of the url of the current page in xpcom meetings none during this week. ...
2006-09-30 - Archive of obsolete content
d a xpcom component on mac os x benjamin smedberg confirmed that this tutorial http://www.iosart.com/firefox/xpcom/ is misleading as it uses the standalone glue (-dxpcom_glue) for components, which is not recommended. developers should use this sample instead: http://developer.mozilla.org/en/docs/xpcom_glue discussions dynamic load overlay a short discussion about the possibilities of loading and unloading xul overlay runtime reading binary data from file discusses about the code to read binary data from file how to build xpcom component on mac os x discusses about the make file code used to build xpcom components on mac os x successfully meetings none during this week. ...
NPAPI plugin developer guide - Archive of obsolete content
out how much data the plug-in can accept writing the stream to the plug-in sending the stream in random-access mode sending the stream in file mode sending a stream creating a stream pushing data into the stream deleting the stream example of sending a stream urls getting urls getting the url and displaying the page posting urls posting data to an http server uploading files to an ftp server sending mail memory allocating and freeing memory mac os flushing memory (mac os only) version, ui, and status information displaying a status line message getting agent information getting the current version finding out if a feature exists reloading a plug-in ...
NPByteRange - Archive of obsolete content
o the next npbyterange request in the list of requests, or null if this is the last request. description the plug-in seeks within a stream by building a linked list of one or more npbyterange objects, which represents a set of discontiguous byte ranges. the only plug-in api call that uses the npbyterange type is npn_requestread(), which lets the plug-in read specified parts of a file without downloading it. the plug-in is responsible for deleting npbyterange objects when finished with them. the browser makes a copy if it needs to keep the objects beyond the call to npn_requestread(). see also npn_requestread() ...
NPN_GetURLNotify - Archive of obsolete content
alls npp_urlnotify(). this notification is the only way the plug-in can tell whether a request with a null target failed, or that a request with a non-null target completed. for requests that complete unsuccessfully, the browser calls npp_urlnotify() as soon as possible. for requests that complete successfully: if the target is non-null, the browser calls npp_urlnotify() after it has finished loading the url. if the target is null, the browser calls npp_urlnotify() after closing the stream by calling npn_destroystream(). if this function is called with a target parameter value of _self or a parent to _self, this function should return nperr_invalid_param. this is the only way to notify the plug-in once it is deleted. warning: in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1), np...
NP_Shutdown - Archive of obsolete content
« gecko plugin api reference « plug-in side plug-in api summary provides global deinitialization for a plug-in. syntax #include <npapi.h> void np_shutdown(void); windows #include <npapi.h> void winapi np_shutdown(void); description the browser calls this function once after the last instance of your plug-in is destroyed, before unloading the plug-in library itself. use np_shutdown to delete any data allocated in np_initialize to be shared by all instances of a plug-in. if you have defined a java class for your plug-in, be sure to release it at this time so that java can unload it and free up memory. 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. the browser calls np_shutdown o...
Table Reflow Internals - Archive of obsolete content
the initial chunk of an xml doc is loaded. the initial chunk of an html doc (or a subsequent chunk of an xml doc) is loaded. the container posts a dirty reflow command with itself as the target. content is inserted, appended, or deleted through the dom. the container posts a dirty reflow command with itself as the target. ...
Making sure your theme works with RTL locales - Archive of obsolete content
the force rtl extension enables you to switch the interface of firefox from ltr to rtl and the other way around dynamically by toggling a menu item. ...
Theme changes in Firefox 3 - Archive of obsolete content
used. mac os x mac os x themes for firefox 3 should add these two rules to the end of chrome://global/skin/wizard.css: .wizard-buttons-btm { padding:xpx; } .wizard-label-box { display: none; } the numeric value ofx, the number of pixels of padding in .wizard-buttons-btm, should be the same as the value of the margin for .wizard-buttons-box-2. image changes chrome://global/skin/icons/loading_16.gif was replaced with chrome://global/skin/icons/loading_16.png . changes in mozapps see also theme changes in firefox 2 ...
Date.prototype.toLocaleFormat() - Archive of obsolete content
rdering of the day and month and other localization tasks are not handled automatically since you have control over the order in which they occur. you should take care that the format string is localized properly according to the user's system settings. be aware that the locale used is not necessarily the same as the locale of the browser. extension and xulrunner developers should know that just loading the format string from a .dtd or .properties file using a chrome://somedomain/locale/somefile.ext uri should be avoided, as the .dtd/.properties file and the tolocaleformat() method does not not necessarily use the same locale, which could result in odd looking or even ambiguous or unreadable dates. also note that the behavior of the used locale depends on the platform, and the user might custom...
LiveConnect - Archive of obsolete content
methods (using the syntax document.applets.name.methodname()). standard java objects are also available for creation and manipulation by javascript code (e.g. by writing code like "new java.lang.string('javascript string')" for classes in the java.* package hierarchy, or using a new "packages" object for classes outside this hierarchy). old liveconnect documents, broken links: java method overloading and liveconnect 3 the technique that liveconnect uses to invoke overloaded java methods from javascript. liveconnect exceptions how do java and javascript catch exceptions generated by the other party? liveconnect testcases determine that applets within different html tags work properly. note: liveconnect blocked under some conditions liveconnect calls from javascript to java api...
Reference - Archive of obsolete content
nks, computers behind insane firewalls, as well as computers not connected to internet. unfortunately there is not an [easy] method to download content/packages of content off of devmo for 'local' browsing/viewing/printing, yet. it is in the "nice to have" category for us here, however i am unaware of anyone feverishly working on it. (there are some other priorities ahead of that, imho). if downloading the stuff is your priority you are free to field ideas/concept to the devmo mailing list for discussion, and then actually code it (or find someone to do so). thanks for your thoughts --callek 15:05, 13 january 2006 (pst) notification when reorganization is finished leandro (localiser for the portuguese wiki) would like to be emailed when the js reference reorganization has been finished. his ...
Troubleshooting XForms Forms - Archive of obsolete content
lot of errors. always check the javascript console (tools, javascript console) for errors. if you get errors there, do not expect your form to work. troubleshooting check the file type is the page parsed as an xhtml document? right-click on a blank spot on the page, and select view page info. the type field should say application/xhtml+xml. anything else, and something is wrong. if your are loading your file directly from the filesystem, make sure that has .xhtml or .xml as the file ending. if you are loading the form from a server, make sure that it serves the files as either application/xhtml+xml or text/xml. check the xhtml 1.0 namespace declaration mozilla xforms is built upon the xhtml 1.0 specification, which is located at http://www.w3.org/1999/xhtml . ensure that your <html> elem...
Common causes of memory leaks in extensions - Extensions
his kind of subtle bug is very common. // unload(function() window.removeeventlistener("leaky", leakref, false), window); // this is the right way to do it remove the listener. unload(function() window.removeeventlistener("leaky", leakref, true), window); } note: the unload() function is an external function which can be added in your add-on to easily provide a way to undo changes upon unloading of your add-on or a specific part/object. it is part of edward lee's restartless boilerplate. causes of other kinds of leaks other than javascript compartments, add-ons may also leak entities that do not get a dedicated compartment, most commonly chrome dom windows and javascript code modules. forgetting to unregister observers holding onto event observers for too long is another problem. ob...
Index - Game development
a shape's colors and other attributes. 25 async scripts for asm.js games, javascript, asm.js, async every medium or large game should compile asm.js code as part of an async script to give the browser the maximum flexibility to optimize the compilation process. in gecko, async compilation allows the javascript engine to compile the asm.js off the main thread when the game is loading and cache the generated machine code so that the game doesn't need to be compiled on subsequent loads (starting in firefox 28). to see the difference, toggle javascript.options.parallel_parsing in about:config. 26 audio for web games audio, games, web audio api, audio sprites, spatialization, syncing tracks audio is an important part of any game; it adds feedback and atmosphe...
Introduction to game development for the Web - Game development
nd so forth. web workers workers give you the ability to spawn background threads running their own javascript code, to take advantage of modern, multi-core processors. xmlhttprequest and file api the combination of xmlhttprequest and the file api lets you send and receive any kind of data you want (don't let the "xml" throw you!) from a web server. this is a great way to do anything from downloading new game levels and artwork to transmitting non-real-time game status information back and forth. ...
Game monetization - Game development
purpose. instead of risking of having your account closed and all the money blocked try to use the usual, gamedev targeted portals like leadbolt. they offer easy to implement systems to show the adverts in your games and split the earnings with you. video ads are getting more and more popular, especially in the form of a pre-roll — they are shown at the beginning of your game while it's still loading. and on the topic of where to put the advertisements in your game it really depends on you. it should be as subtle as possible so as to not annoy the players too much, but visible enough to make them click it or at least take notice. adding adverts between game sessions on game over screens is a popular approach. licensing there's an approach that can work as a monetization model on it's own, a...
Building up a basic demo with PlayCanvas - Game development
anvas 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. those approaches are different but work equally well regarding achieving end goals. playcanvas engine built for modern browsers, playcanvas is a fully-featured 3d game engine with resource loading, an entity and component system, advanced graphics manipulation, collision and physics engine (built with ammo.js), audio, and facilities to handle control inputs from various devices (including gamepads). that's quite an impressive list of features — let's see some in action, check out the building up a basic demo with playcanvas engine for details. playcanvas editor instead of coding everyt...
Async scripts for asm.js - Game development
to see the difference, toggle javascript.options.parallel_parsing in about:config. ...
Implementing game control mechanisms - Game development
ates — boot.js, preloader.js, mainmenu.js and game.js — these are loaded into the index file in this exact order. the first one initializes phaser, the second preloads all the assets, the third one controls the main menu welcoming the player, and the fourth controls the actual gameplay. every state has its own default methods: preload(), create(), and update(). the first one is needed for preloading required assets, create() is executed once the state had started, and update() is executed on every frame. for example, you can define a button in the create() function: create: function() { // ... var buttonenclave = this.add.button(10, 10, 'logo-enclave', this.clickenclave, this); // ... } it will be created once at the start of the game, and will execute this.clickenclave() action assig...
Game over - Game development
y; } instead of allowing the ball to bounce off all four walls, let's only allow three now — left, top and right. hitting the bottom wall will end the game. we'll edit the second if block so it's an if else block that will trigger our "game over" state upon the ball colliding with the bottom edge of the canvas. for now we'll keep it simple, showing an alert message and restarting the game by reloading the page. first, replace where you initially called setinterval() setinterval(draw, 10); with: var interval = setinterval(draw, 10); then replace the second if statement with the following: if(y + dy < ballradius) { dy = -dy; } else if(y + dy > canvas.height-ballradius) { alert("game over"); document.location.reload(); clearinterval(interval); // needed for chrome to...
Bounce off the walls - Game development
asily accomplished using the collideworldsbound property. add this line right after the existing game.physics.enable() method call: ball.body.collideworldbounds = true; now the ball will stop at the edge of the screen instead of disappearing, but it doesn't bounce. to make this occur we have to set its bounciness. add the following line below the previous one: ball.body.bounce.set(1); try reloading index.html again — now you should see the ball bouncing off all the walls and moving inside the canvas area. compare your code you can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: next steps this is starting to look more like a game now, but we can't control it in any way — it's high time we introduced the player pad...
Buttons - Game development
e game right away we can leave that decision to the player by adding a start button they can press. let's investigate how to do that. new variables we will need a variable to store a boolean value representing whether the game is currently being played or not, and another one to represent our button. add these lines below your other variable definitions: var playing = false; var startbutton; loading the button spritesheet we can load the button spritesheet the same way we loaded the ball's wobble animation. add the following to the bottom of the preload() function: game.load.spritesheet('button', 'img/button.png', 120, 40); a single button frame is 120 pixels wide and 40 pixels high. you also need to grab the button spritesheet from github, and save it in your /img directory. adding th...
Load the assets and print them on screen - Game development
's start by creating a javascript variable to represent our ball. add the following line between the game initialization code (our var game... block) and the preload() function: var ball; note: for the sake of this tutorial, we will use global variables. the purpose of the tutorial is to teach phaser-specific approaches to game development rather than dwelling on subjective best approaches. loading the ball sprite loading images and printing them on our canvas is a lot easier using phaser than using pure javascript. to load the asset, we will use the game object created by phaser, executing its load.image() method. add the following new line just inside the preload() function, at the bottom: function preload() { // ... game.load.image('ball', 'img/ball.png'); } the first paramet...
Physics - Game development
at the moment, the physics engine has gravity and friction set to zero. adding gravity would result in the ball falling down while friction would eventually stop the ball. fun with physics you can do much more with physics, for example by adding ball.body.gravity.y = 100; you will set the vertical gravity of t...
Player paddle and controls - Game development
g and bouncing off the walls, but it quickly gets boring — there's no interactivity! we need a way to introduce gameplay, so in this article we'll create a paddle to move around and hit the ball with. rendering the paddle from the framework point of view the paddle is very similar to the ball — we need to add a variable to represent it, load the relevant image asset, and then do the magic. loading the paddle first, add the paddle variable we will be using in our game, right after the ball variable: var paddle; then, in the preload function, load the paddle image by adding the following new load.image() call: function preload() { // ... game.load.image('ball', 'img/ball.png'); game.load.image('paddle', 'img/paddle.png'); } adding the paddle graphic just so we don't forge...
Visual typescript game engine - Game development
all browsers) implemented. socketio used for session staff. multirtc2 used for data transfer also for video chat. multirtc3 alias 'broadcaster' used for video chat. client part to make all dependency works in build process we need some plugins. npm install npm run build navigate in browser /build/app.html to see client app in action -the client part is a browser web application. no reloading or redirecting. this is a single page application. i use html request only for loading local/staged html (like register, login etc.). networking is based on websocket full-duplex communication only.you must be conform with classic socket connection methodology. webrtc can be used for any proportion. already implemented: -video chat webrtc (sip) chat and data communication. look back on main staf...
Ajax - MDN Web Docs Glossary: Definitions of Web-related terms
bpages using a technology known as xmlhttprequest. ajax allows you to update parts of the dom of an html page instead without the need for a full page refresh. ajax also lets you work asynchronously, meaning your code continues to run while the targeted part of your web page is trying to reload (compared to synchronously, which blocks your code from running until that part of your page is done reloading). with interactive websites and modern web standards, ajax is gradually being replaced by functions within javascript frameworks and the official fetch api standard. ...
FTP - MDN Web Docs Glossary: Definitions of Web-related terms
tandard protocol for many years for transferring files from one host to another over the internet. increasingly, though, teams and hosting accounts don't allow ftp and instead rely on a version control system like git. you will still find it used on older hosting accounts, but it is safe to say that ftp is no longer considered best practice. learn more general knowledge beginner's guide to uploading files via ftp ftp on wikipedia ...
First contentful paint - MDN Web Docs Glossary: Definitions of Web-related terms
the question "is it happening?" is "yes" when the first contentful paint completes. ...
First input delay - MDN Web Docs Glossary: Definitions of Web-related terms
often varies based on the the size and complexity of the javascript needing to be downloaded, parsed, and executed on the main thread, and on the device speed or lack thereof (think low end mobile devices). the longer the delay, the worse the user experience. reducing site initialization time and eliminating long tasks can help eliminate first input delays. see also requestidlecallback lazy loading ...
Netscape Navigator - MDN Web Docs Glossary: Definitions of Web-related terms
netscape navigator or netscape was a leading browser in the 1990s. netscape was based on mosaic and the netscape team was led by marc andreessen, a programmer who also wrote code for mosaic. netscape helped make the web graphical rather than a text-only experience. many browsing features became standard after netscape introduced them. netscape could display a webpage while loading, used javascript for forms and interactive content, and stored session information in cookies. despite netscape's technical advantages and initial dominance, by the late 1990s internet explorer swiftly overtook netscape in market share. learn more general knowledge netscape navigator on wikipedia ...
Page prediction - MDN Web Docs Glossary: Definitions of Web-related terms
however, page prediction may also download content a user does not seek. some web applications include a prediction feature completing search text and address bar urls based on browsing history and related searches. ...
Prefetch - MDN Web Docs Glossary: Definitions of Web-related terms
may be clicked on, like search engine results, dns prefetching resolves domain names in advance thereby speeding up load times by reducing the time associated with domain lookup at request time. <link rel="dns-prefetch" href="https://example.com/"> link prefetching link prefetching is a performance optimization technique that works by assuming which links the user is likely to click, then downloading the content of those links. if the user decides to click on one of the links, then the page will be rendered instantly as the content has already been downloaded. the prefetch hints are sent in http headers: link: ; rel=dns-prefetch, ; as=script; rel=preload, ; rel=prerender, ; as=style; rel=preload prefetch attribute value browsers will prefetch content when the prefetch <l...
SPA (Single-page application) - MDN Web Docs Glossary: Definitions of Web-related terms
an spa (single-page application) is a web app implemention that loads only a single web document, and then updates the body content of that single document via javascript apis such as xmlhttprequest and fetch when different content is to be shown. this therefore allows users to use websites without loading whole new pages from the server, which can result in performance gains and a more dynamic experience, with some tradeoff disadvantages such as seo, more effort required to maintain state, implement navigation, and do meaningful performance monitoring. learn more general knowledge some of the most popular spa frameworks include: react angular vue.js ...
Speculative parsing - MDN Web Docs Glossary: Definitions of Web-related terms
eam and runs the html tree construction algorithm speculatively. the upside is that when a speculation succeeds, there's no need to reparse the part of the incoming file that was already scanned for scripts, style sheets and images. the downside is that there's more work lost when the speculation fails. this document helps you avoid the kind of things that make speculation fail and slow down the loading of your page. to make speculative loads of linked scripts, style sheets and images successful, avoid document.write. if you use a <base> element to override the base uri of your page, put the element in the non-scripted part of the document. don't add it via document.write() or document.createelement. avoiding losing tree builder output speculative tree building fails when document.write() c...
HTML: A good basis for accessibility - Learn web development
contrast between all those state colors and the background color. onclick events anchor tags are often abused with the onclick event to create pseudo-buttons by setting href to "#" or "javascript:void(0)" to prevent the page from refreshing. these values cause unexpected behavior when copying or dragging links, opening links in a new tab or window, bookmarking, and when javascript is still downloading, errors out, or is disabled. this also conveys incorrect semantics to assistive technologies (e.g., screen readers). in these cases, it is recommended to use a <button> instead. in general you should only use an anchor for navigation using a proper url. external links and linking to non-html resources links that open in a new tab or window via the target="_blank" declaration and links to whose ...
HTML: A good basis for accessibility - Learn web development
contrast between all those state colors and the background color. onclick events anchor tags are often abused with the onclick event to create pseudo-buttons by setting href to "#" or "javascript:void(0)" to prevent the page from refreshing. these values cause unexpected behavior when copying or dragging links, opening links in a new tab or window, bookmarking, and when javascript is still downloading, errors out, or is disabled. this also conveys incorrect semantics to assistive technologies (e.g., screen readers). in these cases, it is recommended to use a <button> instead. in general you should only use an anchor for navigation using a proper url. external links and linking to non-html resources links that open in a new tab or window via the target="_blank" declaration and links to whose ...
Mobile accessibility - Learn web development
his idea in action in common-job-types.html (see the common jobs example live). it is also worth considering the use of html5 form input types such as the date on mobile platforms as they handle them well — both android and ios, for example, display usable widgets that fit well with the device experience. see html5-form-examples.html for some examples (see the html5 form examples live) — try loading these and manipulating them on mobile devices. for example: types number, tel, and email display suitable virtual keyboards for entering numbers/telephone numbers. types time and date display suitable pickers for selecting times and dates. if you want to provide a different solution for desktops, you could always serve different markup to your mobile devices using feature detection. see inp...
Accessible multimedia - Learn web development
he audio + transcript, and specifically link to them in the places where they are referred to in the transcript. this of course will help all users, not just people who are deaf. note: an audio transcript will in general help multiple user groups. as well as giving deaf users access to the information contained in the audio, think about a user with a low bandwidth connection, who would find downloading the audio inconvenient. think also about a user in a noisy environment like a pub or bar, who is trying to access the information but can't hear it over the noise. video text tracks to make video accessible for deaf, blind, or even other groups of users (such as those on low bandwidth, or who don't understand the language the video is recorded in), you need to include text tracks along with yo...
Debugging CSS - Learn web development
trying to work out which property is causing the problem. the following video provides some useful tips on debugging css using the firefox devtools: editing values in addition to turning properties on and off, you can edit their values. perhaps you want to see if another color looks better, or wish to tweak the size of something? devtools can save you a lot of time editing a stylesheet and reloading the page. with box1 selected, click on the swatch (the small colored circle) that shows the color applied to the border. a color picker will open up and you can try out some different colors; these will update in real time on the page. in a similar fashion, you could change the width or style of the border. adding a new property you can add properties using the devtools. perhaps you have rea...
Sizing items in CSS - Learn web development
led down to fit into the box. this technique is used to make images responsive, so that when viewed on a smaller device they scale down appropriately. you should, however, not use this technique to load really large images and then scale them down in the browser. images should be appropriately sized to be no larger than they need to be for the largest size they are displayed in the design. downloading overly large images will cause your site to become slow, and it can cost users more money if they are on a metered connection. note: find out more about responsive image techniques. viewport units the viewport — which is the visible area of your page in the browser you are using to view a site — also has a size. in css we have units which relate to the size of the viewport — the vw uni...
Multiple-column layout - Learn web development
his feature. 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. a basic example we will now explore how to use multiple-column layout, often referred to as multicol. you can follow along by downloading the multicol starting point file and adding the css into the appropriate places. at the bottom of the section you can see a live example of what the final code should look like. our starting point contains some very simple html; a wrapper with a class of container inside which is a heading and some paragraphs. the <div> with a class of container will become our multicol container. we switch on ...
Practical positioning examples - Learn web development
auto trick. previously in the course we advised against setting a fixed height on content containers if at all possible; it is ok in this circumstance because we have fixed content in our tabs. it also looks a bit jarring to have different tabs at different heights. styling our tabs now we want to style tabs to look like tabs — basically, these are a horizontal navigation menu, but instead of loading different web pages when they are clicked on like we've seen previously in the course, they cause different panels to be displayed on the same page. first, add the following rule at the bottom of your css to remove the default padding-left and margin-top from the unordered list: .info-box ul { padding-left: 0; margin-top: 0; } note: we are using descendant selectors with .info-box at the s...
Responsive design - Learn web development
would take an image that was at the largest size that might be needed, and scale it down. this is still an approach used today, and in most stylesheets, you will find the following css somewhere: img { max-width: 100%; } there are obvious downsides to this approach. the image might be displayed a lot smaller than its intrinsic size, which is a waste of bandwidth — a mobile user may be downloading an image several times the size of what they actually see in the browser window. in addition, you may not want the same image aspect ratio on mobile as on desktop. for example, it might be nice to have a square image for mobile, but show the same scene as a landscape image on desktop. or, acknowledging the smaller size of an image on mobile you might want to show a different image altogether, one...
How do you upload your files to a web server? - Learn web development
u store your website (e.g. mdn). on the center right pane, you see remote files. we are logged into our distant ftp root (in this case, users/demozilla) you can ignore the bottom and top panes for now. respectively, these are a log of messages showing the connection status between your computer and the sftp server, and a live log of every interaction between your sftp client and the server. uploading to the server our example host instructions told us "to publish on the web, put your files into the public/htdocs directory." you need to navigate to the specified directory in your right pane. this directory is effectively the root of your website — where your index.html file and other assets will go. once you've found the correct remote directory to put your files in, to upload your files t...
What are hyperlinks? - Learn web development
starting out, you don't have to worry about external and incoming links as much, but they are very important if you want search engines to find your site (see below for more details). anchors most links tie two webpages together. anchors tie two sections of one document together. when you follow a link pointing to an anchor, your browser jumps to another part of the current document instead of loading a new document. however, you make and use anchors the same way as other links. links and search engines links matter both to users and search engines. every time search engines crawl a webpage, they index the website by following the links available on the webpage. search engines not only follow links to discover the various pages of the website, but they also use the link's visible text to d...
Sending form data - Learn web development
ity warning to the user each time they try to send data because the data will not be encrypted. the names and values of the non-file form controls are sent to the server as name=value pairs joined with ampersands. the action value should be a file on the server that can handle the incoming data, including ensuring server-side validation. the server then responds, generally handling the data and loading the url defined by the action attribute, causing a new page load (or a refresh of the existing page, if the action points to the same page). how the data is sent depends on the method attribute. the method attribute the method attribute defines how data is sent. the http protocol provides several ways to perform a request; html form data can be transmitted via a number of different methods, th...
UI pseudo-classes - Learn web development
abel { color: #aaa; } we've directly selected the inputs we want to disable using input[type="text"]:disabled, but we also wanted to gray out the corresponding text labels. these weren't quite as easy to select, so we've used a class to provide them with that styling. ...
JavaScript basics - Learn web development
ove) place the <script> element near the bottom of the html file is that the browser reads code in the order it appears in the file. if the javascript loads first and it is supposed to affect the html that hasn't loaded yet, there could be problems. placing javascript near the bottom of an html page is one way to accommodate this dependency. to learn more about alternative approaches, see script loading strategies. what happened? the heading text changed to hello world! using javascript. you did this by using a function called queryselector() to grab a reference to your heading, and then store it in a variable called myheading. this is similar to what we did using css selectors. when you want to do something to an element, you need to select it first. following that, the code set the value o...
Use HTML to solve common problems - Learn web development
Learn › HTML › Howto
advanced images & multimedia how to add a responsive image to a webpage how to add vector image to a webpage how to add a hit map on top of an image internationalization html is not monolingual. it provides tools to handle common internationalization issues. how to add multiple languages into a single webpage how to display time and date with html performance how to author fast-loading html pages ...
Images in HTML - Learn web development
ead with long sharp teeth" width="400" height="341"> this doesn't result in much difference to the display, under normal circumstances. but if the image isn't being displayed, for example, the user has just navigated to the page, and the image hasn't yet loaded, you'll notice the browser is leaving a space for the image to appear in: this is a good thing to do, resulting in the page loading quicker and more smoothly. however, you shouldn't alter the size of your images using html attributes. if you set the image size too big, you'll end up with images that look grainy, fuzzy, or too small, and wasting bandwidth downloading an image that is not fitting the user's needs. the image may also end up looking distorted, if you don't maintain the correct aspect ratio. you should use an ima...
Video and audio content - Learn web development
ttributes or with css. in both cases, videos maintain their native width-height ratio — known as the aspect ratio. if the aspect ratio is not maintained by the sizes you set, the video will grow to fill the space horizontally, and the unfilled space will just be given a solid background color by default. autoplay makes the audio or video start playing right away, while the rest of the page is loading. you are advised not to use autoplaying video (or audio) on your sites, because users can find it really annoying. loop makes the video (or audio) start playing again whenever it finishes. this can also be annoying, so only use if really necessary. muted causes the media to play with the sound turned off by default. poster the url of an image which will be displayed before the video is play...
Introducing asynchronous JavaScript - Learn web development
e url in, appending it to the document's <body>. however, we then create a loadasset() function that takes a callback as a parameter, along with a url to fetch and a content type. it uses xmlhttprequest (often abbreviated to "xhr") to fetch the resource at the given url, then pass the response to the callback to do something with. in this case the callback is waiting on the xhr call to finish downloading the resource (using the onload event handler) before it passes it to the callback. callbacks are versatile — not only do they allow you to control the order in which functions are run and what data is passed between them, they also allow you to pass data to different functions depending on circumstance. so you could have different actions to run on the response downloaded, such as processjson(...
Graceful asynchronous programming with Promises - Learn web development
ently, there is nothing to explicitly handle errors if one of the promises fails (rejects, in promise-speak). we can add error handling by running the .catch() method off the previous promise. add this now: let errorcase = promise3.catch(e => { console.log('there has been a problem with your fetch operation: ' + e.message); }); to see this in action, try misspelling the url to the image and reloading the page. the error will be reported in the console of your browser's developer tools. this doesn't do much more than it would if you just didn't bother including the .catch() block at all, but think about it — this allows us to control error handling exactly how we want. in a real app, your .catch() block could retry fetching the image, or show a default image, or prompt the user to provide a...
Build your own function - Learn web development
directly. try saving and refreshing the page — now you should see the message box appear when you click the button. you might be wondering why we haven't included the parentheses after the function name. this is because we don't want to call the function immediately — only after the button has been clicked. if you try changing the line to btn.onclick = displaymessage(); and saving and reloading, you'll see that the message box appears without the button being clicked! the parentheses in this context are sometimes called the "function invocation operator". you only use them when you want to run the function immediately in the current scope. in the same respect, the code inside the anonymous function is not run immediately, as it is inside the function scope. if you tried the last experi...
Introduction to events - Learn web development
es in it — this might be a single element, set of elements, the html document loaded in the current tab, or the entire browser window. there are many different types of events that can occur. for example: the user selects a certain element or hovers the cursor over a certain element. the user chooses a key on the keyboard. the user resizes or closes the browser window. a web page finishes loading. a form is submitted. a video is played, paused, or finishes. an error occurs. you can gather from this (and from glancing at the mdn event reference) that there are a lot of events that can be responded to. each available event has an event handler, which is a block of code (usually a javascript function that you as a programmer create) that runs when the event fires. when such a block of ...
Test your skills: Loops - Learn web development
we didn't provide live editable versions of these tasks because of the risk of creating infinite loops and crashing the assessment page! if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. ...
Drawing graphics - Learn web development
ollowing lines to the bottom of your javascript: let image = new image(); image.src = 'firefox.png'; here we create a new htmlimageelement object using the image() constructor. the returned object is the same type as that which is returned when you grab a reference to an existing <img> element). we then set its src attribute to equal our firefox logo image. at this point, the browser starts loading the image. we could now try to embed the image using drawimage(), but we need to make sure the image file has been loaded first, otherwise the code will fail. we can achieve this using the onload event handler, which will only be invoked when the image has finished loading. add the following block below the previous one: image.onload = function() { ctx.drawimage(image, 50, 50); } if...
A first splash into JavaScript - Learn web development
orm text field and focus it again, ready for the next guess to be entered. events at this point we have a nicely implemented checkguess() function, but it won't do anything because we haven't called it yet. ideally we want to call it when the "submit guess" button is pressed, and to do this we need to use an event. events are things that happen in the browser — a button being clicked, a page loading, a video playing, etc. — in response to which we can run blocks of code. the constructs that listen out for the event happening are called event listeners, and the blocks of code that run in response to the event firing are called event handlers. add the following line below your checkguess() function: guesssubmit.addeventlistener('click', checkguess); here we are adding an event listener to...
Adding features to our bouncing balls demo - Learn web development
r to set the ball() constructor's prototype and constructor appropriately. the ball draw(), update(), and collisiondetect() method definitions should be able to stay exactly the same as they were before. you also need to add a new parameter to the new ball() ( ... ) constructor call — the exists parameter should be the 5th parameter, and should be given a value of true. at this point, try reloading the code — it should work just the same as it did before, with our redesigned objects. defining evilcircle() now it's time to meet the bad guy — the evilcircle()! our game is only going to involve one evil circle, but we are still going to define it using a constructor that inherits from shape() to give you some practice. you might want to add another circle to the app later on that can be ...
Inheritance in JavaScript - Learn web development
rototype as its prototype and will therefore inherit, if and when needed, all the methods available on person.prototype. we need to do one more thing before we move on. after adding the last line, teacher.prototype's constructor property is now equal to person(), because we just set teacher.prototype to reference an object that inherits its properties from person.prototype! try saving your code, loading the page in a browser, and entering teacher.prototype.constructor into the console to verify. this can become a problem, so we need to set this right. you can do so by going back to your source code and adding the following line at the bottom: object.defineproperty(teacher.prototype, 'constructor', { value: teacher, enumerable: false, // so that it does not appear in 'for in' loop ...
Working with JSON - Learn web development
s. we want to access the second object inside the array, so we use [1]. inside this object, we want to access the powers property, so we use ["powers"]. inside the powers property is an array containing the selected hero's superpowers. we want the third one, so we use [2]. note: we've made the json seen above available inside a variable in our jsontest.html example (see the source code). try loading this up and then accessing data inside the variable via your browser's javascript console. arrays as json above we mentioned that json text basically looks like a javascript object, and this is mostly right. the reason we said "mostly right" is that an array is also valid json, for example: [ { "name": "molecule man", "age": 29, "secretidentity": "dan jukes", "powers": [ ...
Measuring performance - Learn web development
these interfaces allows the accurate measurement of the time it takes for javascript tasks to complete. the performanceentry object is part of the performance timeline. 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. the performanceobserver api can be used to observe performance measurement events and it can notify you of new performance entries as they are recorded in the browser's performance timeline. while this article does not dive into using these apis, it is useful to know they exist. you can also refer to the navigation and timings article for further examples on using p...
Web performance resources - Learn web development
ns-prefetch, rel=prefetch, and rel=preload keep the size of javascript to a minimum. only use as much javascript as needed for the current page. css performance factors use http/2 on your server (or cdn). use a cdn for resources which can reduce load times significantly. compress your resources using gzip, brotli, and zopfli. image optimization (use css animation, or svg if possible). lazy loading parts of your application outside the viewport. if you do, have a backup plan for seo (e.g render full page for bot traffic); for example, by using the loading attribute on the <img> element it is also crucial to realize what is really important to your users. it might not be absolute timing, but user perception. quick wins css web performance is all about user experience and perceived perfo...
Website security - Learn web development
fense, your site can prevent itself from being embedded in an iframe in another site by setting the appropriate http headers. denial of service (dos). dos is usually achieved by flooding a target site with fake requests so that access to a site is disrupted for legitimate users. the requests may simply be numerous, or they may individually consume large amounts of resource (e.g., slow reads or uploading of large files). dos defenses usually work by identifying and blocking "bad" traffic while allowing legitimate messages through. these defenses are typically located before or in the web server (they are not part of the web application itself). directory traversal (file and disclosure). in this attack, a malicious user attempts to access parts of the web server file system that they should not b...
Introduction to client-side frameworks - Learn web development
nal websites. the biggest example of this is in client-side routing, as mentioned earlier. with traditional (server-side) routing, navigating the web has predictable results. the browser knows to set focus to the top of the page and assistive technologies will announce the title of the page. these things happen every time you navigate to a new page. with client-side routing, your browser is not loading new web pages, so it doesn't know that it should automatically adjust focus or announce a new page title. framework authors have devoted immense time and labor to writing javascript that recreates these features, and even then, no framework has done so perfectly. the upshot is that you should consider accessibility from the very start of every web project, but bear in mind that abstracted codeba...
TypeScript support in Svelte - Learn web development
'll take care of them propertly, later on. porting our to-do list app to typescript now we are ready to start porting our to-list application to take advantage of all the features that typescript offers to us. let's start by running the validate script in watch mode inside your project root: npm run validate -- --watch this should output something like the following: svelte-check "--watch" loading svelte-check in workspace: ./svelte-todo-typescript getting svelte diagnostics... ==================================== svelte-check found no errors and no warnings note that if you are using a supporting code editor like vs code, a simple way to start porting a svelte component is to just add the <script lang='ts'> at the top of your component and look for the three-dotted hints: alert.svelte...
Working with Svelte stores - Learn web development
torage, we will need a writable store that: initially reads the value from web storage, and if it's not present initializes it with a default value. whenever the value is modified, updates the store itself and also the data in local storage. moreover, because web storage only supports saving string values, we will have to convert from string to object when saving, and vice versa when we are loading the value from local storage. create a new file called localstore.js, in your src directory. give it the following content: import { writable } from 'svelte/store'; export const localstore = (key, initial) => { // receives the key of the local storage and an initial value const tostring = (value) => json.stringify(value, null, 2) // helper function const toob...
Creating our first Vue component - Learn web development
to the todoitem call in app.vue. note that you need to use the v-bind syntax, because otherwise true is passed as a string. the displayed checkbox should be checked. <template> <div id="app"> <h1>my to-do list</h1> <ul> <li> <to-do-item label="my todo item" :done="true"></to-do-item> </li> </ul> </div> </template> try changing true to false and back again, reloading your app in between to see how the state changes. giving todos a unique id great! we now have a working checkbox where we can set the state programmatically. however, we can currently only add one todolist component to the page because the id is hardcoded. this would result in errors with assistive technology since the id is needed to correctly map labels to their checkboxes. to fix this, we ca...
Implementing feature detection - Learn web development
dernizr-css.css" rel="stylesheet"> above this <link> element, add a <script> element to apply the modernizr library to the page, as shown below. this needs to be applied to the page before any css (or javascript) that might make use of it. <script src="modernizr-custom.js"></script> now edit your opening <html> tag, so that it looks like this: <html class="no-js"> at this point, try loading your page, and you'll get an idea of how modernizr works for css features. if you look at the dom inspector of your browser's developer tools, you'll see that modernizr has updated your <html> class value like so: <html class="js no-htmlimports sizes flash transferables applicationcache blobconstructor blob-constructor cookies cors ...and loads more values!> it now contains a large number of cl...
Handling common HTML and CSS problems - Learn web development
packages text field, type "lint" and press enter/return to search for linting-related packages. you should see a package called lint at the top of the list. install this first (using the install button), as other linters rely on it to work. after that, install the linter-csslint plugin for linting css, and the linter-tidy plugin for linting html. after the packages have finished installing, try loading up an html file and a css file: you'll see any issues highlighted with green (for warnings) and red (for errors) circles next to the line numbers, and a separate panel at the bottom provides line numbers, error messages, and sometimes suggested values or other fixes. other popular editors have similar linting packages available. for example, see: sublimelinter for sublime text notepad++ l...
Setting up your own test automation environment - Learn web development
ed this construct to tab out of the form input before submitting it: driver.sleep(1000).then(function() { driver.findelement(by.name('q')).sendkeys(webdriver.key.tab); }); waiting for something to complete there are times where you'll want to make webdriver wait for something to complete before carrying on. for example if you load a new page, you'll want to wait for the page's dom to finish loading before you try to interact with any of its elements, otherwise the test will likely fail. in our google_test.js test for example, we included this block: driver.sleep(2000).then(function() { driver.gettitle().then(function(title) { if(title === 'webdriver - google search') { console.log('test passed'); } else { console.log('test failed'); } }); }); the sleep() metho...
Command line crash course - Learn web development
expanding — you can expect to see more package providers as time goes on. installing node.js also installs the npm command line tool (and a supplementary npm-centric tool called npx), which offers a gateway to installing additional command line tools. node.js and npm work the same across all systems: macos, windows, and linux. install npm on your system now, by going to the url above and downloading an running a node.js installer appropriate to your operating system. if prompted, make sure to include npm as part of the installation. although we'll look at a number of different tools in the next article onwards, we'll cut our teeth on prettier. prettier is an opinionated code formatter that has "few options". fewer options tends to mean simpler. given how tooling can sometimes get out of h...
Introducing a complete toolchain - Learn web development
e code to something the browser can consume without issue. there's a number of choices for transform tools and though webpack is a particularly popular one, this project is going to use parcel — specifically because it requires a lot less configuration. parcel works on the basis that it will try to configure your development requirements on the fly. parcel will watch the code and run a live-reloading web server during development. this also means that parcel will install our software dependencies automatically as they are referenced in the source code, as we saw in chapter 3. parcel will take care of installing any transformation tooling and configuration required without us needing to intervene (in most cases). then as a final bonus, parcel can bundle and prepare the code for production de...
Chrome Worker Modules
start by importing the module loader. you only need to do it once for each worker, from within the chrome worker itself: importscripts("resource://gre/modules/workers/require.js"); note: although you only need to do this once for each worker, it doesn't hurt if you do it more than once. ...
Accessibility/LiveRegionDevGuide
e between at-spi and iaccessible2 is that at-spi is an inter-process communication service while iaccessible2 runs in process. as a result, care must be taken in an at-spi based application to minimize performance degradation by only acting on events that are truly live regions. these "non-live" events may be events originating from the chrome, user interaction in the chrome or document, document loading events, or real live region events from hidden tabs. with the goal of eliminating the "non-live" events, some sort of event filtering logic must be employed. the following is a list of potential filtering techniques: the "event-from-input" object attribute can be used to filter events that were triggered by user action. the ":system" (or lack thereof) can be used to filter events that are syst...
Mozilla’s UAAG evaluation report
s 10.7 highlight current viewport. (p1) vg uses title bar color and focus indicator to indicate with view port has focus the currently focused content frame has a dotted outline, until a key is pressed or scrolling occurs the focus appearance is not configurable 10.8 indicate rendering progress. (p3) vg a progress bar and status bar message indicates loading progress the scroll bar indicates how far into the document the current graphical view is the size of the current document is in the page info screen, sometimes it says unavailable guideline 11. allow configuration and customization. checkpoint title status notes/plans 11.1 current user bindings. (p1) g menus indicate accesskey and acce...
Theme concepts
h the developer hub select "upload new version" on the left upload your packaged file for validation or modify it using the theme generator for self-hosted static themes, a new version can be updated through amo by following the above steps or be handled by you through an updateurl or external application updates. a new version will need to be signed through the developer hub. if you are uploading a packaged file, the version number must be higher than the current version number dynamic themes as an alternative to defining a static theme, you can use the theme api to control the theme used in firefox from within a browser extension. there are a couple of use cases for this option: to bundle a theme with a browser extension, as an added extra. create a dynamic theme that changes unde...
Add-ons
can still port it to use webextension apis. there are some porting resources on firefox extension workshop, our site for firefox-specific development resources. for more information about transition support, please visit our wiki page. publishing add-ons addons.mozilla.org, commonly known as "amo," is mozilla's official site for developers to list add-ons, and for users to discover them. by uploading your add-on to amo, you can participate in our community of users and creators and find an audience for your add-on. you are not required to list your add-on on amo, but your add-on must be signed by mozilla else users will not be able to install it. for an overview for the process of publishing your add-on see signing and distributing your add-on. other types of add-ons in addition to extens...
Command line options
ces created with this parameter do not accept or send remote commands, see bug 650078. that means that such instances won't be re-used. also when using this argument a new instance is created in any case. -override /path/to/override.ini load the specified override.ini file to override application.ini (browser/app/application.ini). this can be used to suppress the migration wizard at startup by loading the following override.ini. firefox only. [xre] enableprofilemigrator=0 -profilemanager start with profile manager. short form: -p without a profile name. -p "profile_name" bypass profile manager and launch application with the profile named profile_name. useful for dealing with multiple profiles. firefox -p "joel user" note: profile_name is case sensitive. if you don't specify a profile...
Debugging Frame Reflow
: point the gecko_display_reflow_rules_file environment variable to the path of the reflow_rules.txt file. run the debug build, saving stdout to a file. on mac this is accomplished with: $ env dyld_library_path="`pwd`/obj-ff-dbg/dist/nightlydebug.app/contents/macos" \ ./obj-ff-dbg/dist/nightlydebug.app/contents/macos/firefox-bin > logfile.txt after loading your testcase, the log file will contain the promised information. 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>...
Debugging on Mac OS X
nable hardened runtime and only differ from production builds in that they are not notarized which should not otherwise affect functionality, (other than the ability to easily launch the browser on macos 10.15+ -- see quarantine note below). at this time, developers can obtain a hardened runtime build with the com.apple.security.get-task-allow entitlement allowed by submitting a try build and downloading the dmg generated by the "rpk" shippable build job. a debugger can be attached to firefox processes of these builds. try builds use the developer.entitlements.xml file from the source tree while production builds use production.entitlements.xml. on macos 10.15+, downloaded try builds will not launch by default because notarization is required. to workaround this problem, remove the quarantine ext...
Listening to events on all tabs
progress for all requests associated with webprogress. amaxtotalprogress the total progress for all requests associated with webprogress. onsecuritychange notification called for security progress. this method will be called on security transitions (eg http -> https, https -> http, foo -> https) and after document load completion. it might also be called if an error occurs during network loading. note: these notifications will only occur if a security package is installed. void onsecuritychange( nsidomxulelement abrowser, nsiwebprogress awebprogress, nsirequest arequest, unsigned long astate ); parameters abrowser the browser that fired the notification. awebprogress the nsiwebprogress instance that fired the notification. arequest the nsirequest that ...
Experimental features in Firefox
eveloper edition 75 no beta 75 no release 75 no preference name dom.forms.inputmode <link rel="preload"> the <link> element's rel attribute is intended to help provide performance gains by letting you download resources earlier in the page lifecycle, ensuring that they're available earlier and are less likely to block page rendering. read preloading content with rel="preload" for more details. for more details on the status of this feature, see bug 1639607. release channel version added enabled by default? nightly 78 yes developer edition 78 yes beta 78 yes release 78 no preference name network.preload css display stray control characters in c...
Limitations of chrome scripts
...
Message manager
extension's code, to access web content while the browser is running web content in a separate process. these guides explain how to use message managers in multiprocess firefox. note that none of this requires multiprocess firefox: everything described here will work with single-process firefox, so the same code will work on both variants. ...
Performance best practices for Firefox front-end engineers
great, because it reduces build times, and means we can do our work faster. we should remind ourselves that the majority of our user base is unlikely to have similar hardware. look at the firefox hardware report to get a sense of what our users are working with. test on slower machines to make it more obvious to yourself if what you’ve written impacts the performance of the browser. consider loading scripts with the subscript loader asynchronously if you've ever used the subscript loader, you might not know that it can load scripts asynchronously, and return a promise once they're loaded. for example: services.scriptloader.loadsubscriptwithoptions(myscripturl, { async: true }).then(() => { console.log("script at " + myscripturl + " loaded asynchronously!"); }); ...
HTMLIFrameElement.getStructuredData()
is a json object representation of all microdata contained on the page loaded in the browser. parameters none. ...
mozbrowserloadend
non-standard this feature is not on a current w3c standards track, but it is supported on the firefox os platform. although implementations may change in the future and it is not supported widely across browsers, it is suitable for use in code dedicated to firefox os apps. the mozbrowserloadend event is fired when the browser <iframe> has finished loading all its assets, or has failed to load. this can be used when the embedder wants to stop spinning a loading indicator, or update the ui in some other way to indicate loading is complete. general info specification non standard interface customevent bubbles yes cancelable yes target <iframe> default action none properties property type description target read only ev...
mozbrowserloadstart
non-standard and is not on a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. the mozbrowserloadstart event is fired when the browser <iframe> starts to load a new page. this can be used when the embedder wants to start spinning a loading indicator, or update the ui in some other way to indicate loading has started. general info specification non standard interface customevent bubbles yes cancelable yes target <iframe> default action none properties property type description target read only eventtarget the event target (the topmost target in the dom tree). type read on...
mozbrowserscrollareachanged
on a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. the mozbrowserscrollareachanged event is fired when the available scrolling area in the browser <iframe> changes. this can occur on resize and when the page size changes (while loading for example.) general info specification non standard interface customevent bubbles yes cancelable yes target <iframe> default action none properties property type description target read only eventtarget the browser iframe type read only domstring the type of event. bubbles read only boolean whether the event no...
HTMLIFrameElement.stop()
Mozilla › Gecko › Chrome › API › Browser API › stop
non-standard this feature is non-standard and is not on a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. the stop() method of the htmliframeelement interface is used to stop loading the content of the <iframe>. syntax instanceofhtmliframeelement.stop(); returns void. parameters none. examples stopreload.addeventlistener('touchend',function() { if(stopreload.textcontent === 'x') { browser.stop(); } else { browser.reload(); } }); specification not part of any specification. ...
Embedding the editor
eds, it indicates that the frame is editable. nsieditorframe should contain methods for getting the editing session, and doing some generic editor-related stuff (probably common to html and plain text editing). a subset of nsieditorshell will probably move into this interface. (this would be analogous to the nsiwebnavigation interface used for a browser.) when we have one editor per docshell, loading a frameset document, or a page with an <iframe> in composer, will instantiate more than one low-level editor. we need a concept of an "editing session" - a single top-level document which is editable, and which may embody more than one editor. this interface will be called nsi????. high-level ui and emebedding code should deal with this editing session interface, without knowledge of the underlyi...
Embedding Tips
fault service implementations with their own. for example, the default prompt service uses xul to render prompt dialogs and embedders may wish to render them in a way more appropriate for their application and platform.. how do i load a page? get thensiwebnavigation interface on your webbrowser and call the loaduri method with the appropriate uri and flags. this interface also has methods for reloading, stopping a load and going back and forward in the history. how do i block a load? implement the nsiwebprogresslistener interface and register it with the appropriate web browser object via the nsiwebbrowser::addwebbrowserlistener() method. use the callbacks for after-the-fact cancellation. alternatively, implement a nsiuricontentlistener as described below. how do i watch/intercept a load bef...
Roll your own browser: An embedding how-to
dings/xparts/. (news release, screenshot) mozilla examples gtkmozembed widget: gtk widget wrapper for the mozilla gecko engine. testgtkembed: basic browser built with the gtkmozembed widget. url location field, menu bar, html area, supports ssl. windows external projects k-meleon browser: the windows answer to galeon. fast ie-look-alike browser, uses ie and ns bookmarking system, fast loading time, privacy features, java support and complete control of the menus and "hotkeys". implemented with mozilla embedding apis. (screenshots) neoplanet browser: a gecko add-on for the neoplanet browser. activestate's komodo: development environment, based on mozilla's xul. (screenshot) macromedia homesite html editor: internal browser for the homesite studio application is implemented by embedd...
Getting Started with Chat
client to automatically connect to a server and join a particular set of channels when you start the client. the following are some other options available to you: windows mac linux colloquy ● irssi ● ● ●* xchat ● ○ ● key: ● — binary or executable program available ○ — only available by downloading and compiling source code ●* — binary or executable may be available. if not, you'll have to download source code and compile. note: for a complete list of irc clients go here. web-based clients there are also a few web-based clients which allow connecting to irc by clicking on irc:// links. one of the simplest web-based clients is mibbit, another is irccloud. these operate very much in...
PBackground
child process. for most purposes this is great, because the dom is already bound to the main thread. but in some cases we don't necessarily want to talk to the main thread. what if i want to talk to a different thread? not every communication between the chrome and content processes necessarily wants to go through the main threads of both (or even either) processes. for example, when we are uploading textures from the content process we don't need to go through the main thread of the parent process. instead we can go directly to the compositor thread in the parent process by creating a new top-level protocol that connects the compositor thread in the parent process to the main thread of a child process. this protocol is called pcompositor, and allows us to bypass the main thread of the parent...
Implementing Download Resuming
n ns_error_entity_changed error code. the front-end may want to offer the user to get the new file from scratch in such a case. resuming not supported in some cases, it's not possible to detect whether the server supports resuming until the user actually tries to resume. in such a case, the stream listener will get an ns_error_not_resumable status. here, too, the front-end may want to offer downloading the entire file from scratch. ...
AddonUpdateChecker
teinfo getnewestcompatibleupdate(in updateinfo updates[], in string appversion, in string platformversion) void checkforupdates(in string id, in string type, in string updatekey, string url, in updatechecklistener listener) constants constant description error_timeout the update check timed out. error_download_error there was an error while downloading the update information. error_parse_error the update information was malformed in some way. error_unknown_format the update information was not in any known format. error_security_error the update information was not signed by the update key used for retrieval. methods getcompatibilityupdate() retrieves the best matching compatibility update for the ap...
DownloadTarget
in download metadata. if that metadata is no longer available and the file has been deleted, then this value is zero. for single-file downloads, this property's value will always match the actual size of the file on disk, while the download.totalbytes property, when available, may indicate the size of the data as encoded for transfer instead. for downloads of multiple files, such as downloading a web page and its required media to disk, the meaning of this property is undefined. it currently indicates the size of the main file (such as the html document) rather than the sum of all of the files' sizes, but you must not rely upon this behavior, as it is subject to change. this is a dynamic property, which is updated when the download finishes or whenever the download.refresh() method...
Promise.jsm
a+ proposal until gecko 25: components.utils.import("resource://gre/modules/commonjs/promise/core.js"); // gecko 17 to 20 components.utils.import("resource://gre/modules/commonjs/sdk/core/promise.js"); // gecko 21 to 24 this implementation also includes helper functions that are specific to the add-on sdk. while you may still import this module from the above paths, the recommended way for loading it is through the add-on sdk loader. introduction for an introduction to promises, you may start from the add-on sdk documentation, keeping in mind that only the core subset is implemented in this module. a promise is an object representing a value that may not be available yet. internally, a promise can be in one of three states: pending, when the final value is not available yet. this is...
Using JavaScript code modules
le.jsm"); bar = "foo"; alert(bar); // displays "foo" scope 2: components.utils.import("resource://app/my_module.jsm"); alert(bar); // displays "[object object]" the main effect of the by-value copy is that global variables of simple types won't be shared across scopes. always put variables in a wrapper class and export the wrapper (such as bar in the above example). unloading code modules requires gecko 7.0(firefox 7.0 / thunderbird 7.0 / seamonkey 2.4) components.utils.unload() allows you to unload a previously imported code module. once this method has been called, references to the module will continue to work but any subsequent import of the module will reload it and give a new reference. examples a template to download and edit is seen here on github - ...
JavaScript code modules
n xpcom component. customizableui.jsm allows you to interact with customizable buttons and items in firefox's main window ui. deferredtask.jsm run a task after a delay. dict.jsm provides an api for key/value pair dictionaries. downloadlastdir.jsm supplies the path to the directory into which the last download occurred. downloads.jsm provides a single entry point to interact with the downloading capabilities of the platform. fileutils.jsm provides helpers for dealing with files. geometry.jsm provides routines for performing basic geometric operations on points and rectangles. http.jsm a wrapper for xmlhttprequest that provides convenient and simplified api for dealing with http requests. jni.jsm abstracts the js-ctypes to provide an interface that allows javascript code to call c...
Application Translation with Mercurial
any other tool in which you can attach different kind of states to the individual texts to translate. the firefox extension scrapbook is used in this guide. install it into your default firefox profile (you will have more than one profile when following this guide). getting the current texts in english and your locale obtaining the english texts with the source code get the source code by downloading the following file: firefox desktop or firefox for android: download the mozilla-<branch>.hg file (e.g. mozilla-aurora.hg) from https://ftp.mozilla.org/pub/mozilla.org/firefox/bundles/ the file is not small, but after initially downloading it, you only need to download the latest changes in the future. thunderbird, lightning or seamonkey: download the comm-<branch>.hg file (e.g. comm-aurora.h...
Bootstrapping a new locale
w we'll set up a not-so-compile environment by calling configure. if you just checked out the localizable parts of en-us above, it will create a plethora of warnings no such file or directory, but no errors. ../mozilla/configure --disable-compile-environment --enable-application=browser whenever you need a build directory, these are the steps that you need to do to initialize it. if you're downloading a new release of firefox from cvs, you might want to run configure again, too. now we can actually create the language pack, make -c browser/locales langpack-en-x-dude you should find your newly created language pack in dist/install. ls dist/install you can open that file in firefox and check it out. you have to set your selected language still. you can either use the locale switcher exten...
Localizing with Mercurial
ercurial distributed scm (version 1.3.1)), you have installed mercurial successfully! more details for more details on installing hg on windows, refer to the instructions on mercurial's download page. mercurial on mac osx installing hg on mac osx is super easy. you can install mercurial via macports through the terminal, like so: $ sudo port install mercurial you can also install it by downloading the dmg package from the hg download page. it has an install dialog that will walk you through the process. if you prefer a graphical interface, you can download and install mercurialeclipse here. did it work? open a terminal window and type hg --version. if you see a message about the version of mercurial (e.g. mercurial distributed scm (version 1.3.1)), you have installed mercurial successfu...
Localizing with Pontoon
subpages or localization files. hidden if no resources available for project. locale selector (slovenian) switches between languages to localize. go opens project-resource-locale selection. progress indicator displays your progress on the resource being localized. more details are available in the popup. user menu allows for user-specific tasks, like commiting to repository, downloading files and signing out. info menu gives important information, like the anticipated project timeline and a list of keyboard shortcuts. alright, how about we do some translating now? translate strings when using pontoon for localization, you have a couple of options to translate your strings. you can translate in-context, out-of-context, or a combination of the two. we'll start with loo...
Mozilla Development Tools
to build mozilla are described on the build page for your platform. mozilla source code (mercurial and cvs) "trunk" development for gecko 1.9.1/firefox 3.5 and beyond uses the mercurial source code version control system. earlier releases and other products use the cvs version control system. if you are doing active development, checking out source code from one of these is preferable to downloading an archived snapshot, as you get up-to-the-minute changes. mxr you can browse the up-to-the-minute latest version of the source code online through a massively-hyperlinked source code browser (based on lxr) that lets you cross-reference function and variable names. bonsai bonsai is tree control (get it?). it is our home-grown web-based tool for watching the up-to-the-minute goings-on in...
Mozilla Style System Documentation
s specified by that rule that are not filled in already. the walking stops when all of the properties are filled in or when the root of the rule tree is reached. then the style struct is computed from the declaration and stored at the appropriate location in the rule tree or on the style context. problems: dynamic style changes often destroy too much data. css stylesheet backend css stylesheet loading [this section needs to be written. i'm reluctant to write it both since i don't know much about it.] problems:a bunch the code needs to be rewritten to prevent stylesheets from blocking the parser and to reduce string copying (although that partly goes with parsing).] parsing stylesheet representation problems: the stylesheet representation uses way too much memory. other nsistylesheet impl...
Profiling with Xperf
at all on xp. this page applies to xperf version 4.8.7701 or newer. to see your xperf version, either run 'xperf' on a command line with no arguments, or start 'xperfview' and look at help -> about performance analyzer. (note that it's not the first version number in the about window; that's the windows version.) if you have an older version, you will experience bugs, especially around symbol loading for local builds. installation for all versions, the tools are part of the latest windows 7 sdk (sdk version 7.1). use the web installer to install at least the "win32 development tools". once the sdk installs, execute either wpt_x86.msi or wpt_x64.msi in the redist/windows performance toolkit folder of the sdk's install location (typically program files/microsoft sdks/windows/v7.1/redist/windo...
Reporting a Performance Problem
rmance problem as only the last few seconds are recorded. if the timeline has a large red block it's a good sign. the data will open in a new tab. wait until the "symbolicating call stacks" notification disappears before sharing the profile. there will be a button in the top right labeled 'publish' which will allow you to upload this profile and once completed will write out a link. before uploading, the publish button asks you what data you'd like to publish to our servers. note that while it's possible to strip profiles of potentially privacy sensitive information, the less information a profile contains, the harder it is to analyze and turn into actionable data. once uploaded, copy permalink url to your clipboard by right clicking and add the profile url to a bug for your performance pr...
nglayout.debug.disable_xul_cache
the effect is that the source xml file is not read and re-parsed each time the chrome in question is displayed. the xul cache is serialized and saved between mozilla sessions in the xul fastload file, which saves a “compiled” version of the xul and javascript in a document to disk for faster startup the next time the application runs. during development of xul applications, it’s convenient to disable the xul cache so that changes you make to files on disk take effect the next time the window or dialog is loaded (instead of the next time mozilla starts). ...
Preference reference
bird 17.0, the tabs are drawn in the title bar. the old behavior can be restored by setting the preference mail.tabs.drawintitlebar to false.nglayout.debug.disable xul fastloadthe preference nglayout.debug.disable_xul_fastload controls whether or not xul fastload is used.nglayout.debug.disable_xul_cacheto improve performance, mozilla caches chrome xul documents the first time they load for faster loading later. the effect is that the source xml file is not read and re-parsed each time the chrome in question is displayed. the xul cache is serialized and saved between mozilla sessions in the xul fastload file, which saves a “compiled” version of the xul and javascript in a document to disk for faster startup the next time the application runs.reader.parse-on-load.force-enabledthe preference rea...
Profile Manager
fox and other xulrunner applications store user settings and data in special folders, called profiles. 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. downloading binaries you can download profile manager builds from https://ftp.mozilla.org/pub/mozilla.org/utilities/profilemanager/1.0/ note: there is no installer; just extract the files from the archive. system requirements: mac: an intel processor, i386 or x86_64 linux: any version capable of running firefox 4.0 windows: xp or later source code you can download the source as well: hg clone h...
About NSPR
from most well-known forms of ascii into the 64-bit nspr representation. memory management nspr provides api to perform the basic malloc, calloc, realloc and free functions. depending on the platform, the functions may be implemented almost entirely in the nspr runtime or simply shims that call immediately into the host operating system's offerings. linking support for linking (shared library loading and unloading) is part of nspr's feature set. in most cases this is simply a smoothing over of the facilities offered by the various platform providers. where it's headed nspr is applicable as a platform on which to write threaded applications that need to be ported to multiple platforms. the current implementation supports macintosh (ppc), win-32 (winnt, win9x) and 20 versions of unix and is s...
Dynamic Library Linking
", &lib); when pr_findsymbolandlibrary returns, funcptr is the value of the function pointer you want to look up, and the variable lib references the main executable program. you can then call pr_findsymbol on lib to look up other symbols defined in the main program. remember to call pr_unloadlibrary(lib) to close the library handle when you are done. platform notes to use the dynamic library loading functions on some platforms, certain environment variables must be set at run time, and you may need to link your executable programs using special linker options. this section summarizes these platform idiosyncrasies. for more information, consult the man pages for ld and dlopen (or shl_load on hp-ux) for unix, and the loadlibrary documentation for win32. dynamic library search path exporti...
PR_LoadLibrary
he library to be loaded, as returned by pr_getlibraryname. returns if successful, returns a reference to an opaque prlibrary object. if the operation fails, returns null. use pr_geterror to find the reason for the failure. description this function loads and returns a reference to the specified library. the returned reference becomes the library's identity. the function suppresses duplicate loading if the library is already known by the runtime. each call to pr_loadlibrary must be paired with a corresponding call to pr_unloadlibrary in order to return the runtime to its original state. ...
JSS
Mozilla › Projects › NSS › JSS
pto technologies it uses. you might want to read these documents: introduction to public-key cryptography. explains the basic concepts of public-key cryptography that underlie nss and jss. introduction to ssl. introduces the ssl protocol, including information about cryptographic ciphers supported by ssl and the steps involved in the ssl handshake. for information on downloading nss releases, see nss sources building testing. read using jss to get you started with development after you've built and downloaded it. release notes 4.3.1 release notes 4.3 release notes older release notes build instructions building jss 4.4.x building jss 4.3.x older build instructions download or view source d...
NSS 3.12.6 release notes
bug 527759: add multiple roots to nss (single patch) bug 528741: pkix_hash throws a null-argument exception on empty strings bug 530907: the peerid argument to ssl_setsockpeerid should be declared const bug 531188: decompression failure with https://livechat.merlin.pl/ bug 532417: build problem with spaces in path names bug 534943: ...
NSS 3.16.2 release notes
in nss 3.16.2 the btoa command has a new command-line option -w suffix, which causes the output to be wrapped in begin/end lines with the given suffix. use "c" as a shorthand for the suffix certificate. the certutil commands supports additionals types of subject alt name extensions: --extsan type:name[,type:name]... the certutil commands supports generic certificate extensions, by loading binary data from files, which have been prepared using external tools, or which have been extracted and dumped to file from other existing certificates: --dump-ext-val oid --extgeneric oid:critical-flag:filename[,oid:critical-flag:filename]... the certutil command has three new certificate usage specifiers: l: certificateusagesslca a: certificateusageanyca y: certifica...
NSS Sample Code Sample1
st be started to perform // this function (see start()) int exportkeys(secitem *pubkey, secitem **wrappedenckey, secitem **wrappedmackey); // import the keys received from another server in the // cluster. the admin should make sure the keys actually // came from the correct source. int importkeys(secitem *wrappedenckey, secitem *wrappedmackey); // start the server, loading the encryption and macing keys // from files int start(); // shut down the server. (for completeness) int shutdown(); // compare keys in two server instances. use this in the // example to make sure the keys are transferred correctly. // this will not work in real life! // // the servers must be started int comparekeys(server *peer); // create a server - the name distigui...
PKCS #11 Module Specs
flags - comma separated list of flag values, parsed case-insensitive. valid flag values are: internal - this library is actually the netscape internal library fips - this library is the netscape internal fips library. critical - if this library cannot be loaded, completely fail initialization. moduledb - this library includes nss specific functions to supply additional module specs for loading. moduledbonly - this library has no pkcs #11 functions and is only used for loading additional modules. trustorder - integer value specifying the order in which the trust information for certificates specified by tokens on this pkcs #11 library should be rolled up. '0' means that tokens on this library should not supply trust information (default). the relative order of two pkcs#11 libraries w...
PKCS11 Implement
sion whenever ckf_login_required is true and the user state indicates that the user isn't logged in. 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. currently pkcs #12 isn't allowed to import onto a token. the nss also uses c_createobject to create new session keys. the nss sometimes loads raw key data and builds a key from that. the nss will...
Python binding for NSS
d and been further proven in the field a 1.0 release will be made. at that point in time existing users of the python-nss api will need to some elements of their code. a migration script will be provided to assist them. licensing information python-nss is available under the mozilla public license, the gnu general public license, and the gnu lesser general public license. for information on downloading python-nss releases as tar files, see source download. documentation python-nss api documentation the python-nss api documentation for the current release can be viewed at python-nss api documentation. the api documentation is generated from the python-nss source code and compiled modules. you can build it yourself via ./setup.py build_doc. most distributions include the python-nss api docum...
NSS_Initialize
support locking - either os locking or nss-provided locks . if a pkcs#11 module isn't thread-safe, don't serialize its calls; just don't load it instead. this is necessary if another piece of code is using the same pkcs#11 modules that nss is accessing without going through nss, for example, the java sunpkcs11 provider. nss_init_pk11reload - ignore the ckr_cryptoki_already_initialized error when loading pkcs#11 modules. this is necessary if another piece of code is using the same pkcs#11 modules that nss is accessing without going through nss, for example, java sunpkcs11 provider. nss_init_nopk11finalize - never call c_finalize on any pkcs#11 module. this may be necessary in order to ensure continuous operation and proper shutdown sequence if another piece of code is using the same pkcs#11 modul...
NSS environment variables
", "sql", or "extern") determines the default database type to open if the app does not specify. nss_shared_db 3.12 nss_disable_arena_free_list string (any non-empty value) define this variable to get accurate leak allocation stacks when using leak reporting software. nss_memory_allocation 3.4 nss_disable_unload string (any non-empty value) disable unloading of dynamically loaded nss shared libraries during shutdown. necessary on some platforms to get correct function names when using leak reporting software. 3.11.8 nss_enable_audit boolean (1 to enable) enable auditing of activities of the nss cryptographic module in fips mode. audit data 3.11.2 nss_enable_pkix_verify boolean (any non-empty value to enable) ...
NSS tools : modutil
bled token name: nss certificate db token manufacturer: mozilla foundation token model: nss 3 token serial number: 0000000000000000 token version: 8.3 token firmware version: 0.0 access: not write protected login type: login required user pin: initialized a related command, -rawlist returns information about the database configuration for the modules. (this information can be edited by loading new specs using the -rawadd command.) modutil -rawlist -dbdir sql:/home/my/sharednssdb name="nss internal pkcs #11 module" parameters="configdir=. certprefix= keyprefix= secmod=secmod.db flags=readonly " nss="trustorder=75 cipherorder=100 slotparams={0x00000001=[slotflags=rsa,rc4,rc2,des,dh,sha1,md5,md2,ssl,tls,aes,random askpw=any timeout=30 ] } flags=internal,critical" setting a default pro...
NSS Tools
below describes both the tools that are currently working and those that are still under development. the links for each tool take you to the source code, documentation, plans, and related links for each tool. the links will become active when information is available. currently, you must download the nss 3.1 source and build it to create binary files for the nss tools. for information about downloading the nss source, see https://developer.mozilla.org/nss/building. if you have feedback or questions, please feel free to post to mozilla.dev.tech.crypto. this newsgroup is the preferred forum for all questions about nss and nss tools. overall objectives provide a tool for analyzing and repairing certificate databases (dbck). migrate tools from secutil.h interface to pkcs #11 interface. elim...
certutil
tokenname argument can search a specific token or all tokens. o if there are multiple key types available, then the -k key-type argument can search a specific type of key, like rsa, dsa, or ecc. listing security modules the devices that can be used to store certificates -- both internal databases and external devices like smart cards -- are recognized and used by loading security modules. the -u command option lists all of the security modules listed in the secmod.db database. the path to the directory (-d) is required. $ certutil -u -d sql:/home/my/sharednssdb slot: nss user private key and certificate services token: nss certificate db slot: nss internal cryptographic services token: nss generic crypto services adding certificate...
NSS tools : modutil
Mozilla › Projects › NSS › tools › modutil
certificate db token manufacturer: mozilla foundation token model: nss 3 token serial number: 0000000000000000 token version: 8.3 token firmware version: 0.0 access: not write protected login type: login required user pin: initialized a related command, -rawlist returns information about the database configuration for the modules. (this information can be edited by loading new specs using the -rawadd command.) modutil -rawlist -dbdir sql:/home/my/sharednssdb name="nss internal pkcs #11 module" parameters="configdir=. certprefix= keyprefix= secmod=secmod.db flags=readonly " nss="trustorder=75 cipherorder=100 slotparams={0x00000001=[slotflags=rsa,rc4,rc2,des,dh,sha1,md5,md2,ssl,tls,aes,random askpw=any timeout=30 ] } flags=internal,critical" setting a de...
Necko Architecture
ich is not required if all you need is a parsed representation of a uri string). for every uri you want to transact with, there is exactly one channel. in order to get a channel from a uri an intermediary layer was introduced. because a uri has no self knowledge about what "protocol" it represents, another component is responsible for deciding which channel implementation will be responsible for "loading" the uri. this layer is the protocol handler layer. a protocol handler's primary responsibility is to create channels for the scheme it has registered to handle. for example, the http protocol handler registers itself as the protocol handler for "http." the http protocol handler creates http channels for http urls. once you have a channel you can read or write data from or to your uri. nsiioser...
Multithreading in Necko
til its buffers are full (empty). once at the limit of its buffers, it yields the thread to another pending file transport object. as with the socket transport thread, the nsistreamlistener passed to a file transport's asyncread method can operate partially on the file transport's thread before proxying data to the main thread. the file transport is confusingly named since it is not restricted to loading files. it simply promises to read from a nsiinputstream (or write to a nsioutputstream) on a background thread. the implementation of the stream should be blocking; however, there is limited support for non-blocking streams. cached page loads, file url loads, and jar url loads all utilize the file transport service. the jar protocol handler, for rexample, passes a special nsiinputstream impl that...
Renaming With Pork
usually, ides require one to use their build system. pork does not yet have a ui, but it is also build-system agnostic and scales to large codebases. these notes are based on tools pork refactoring toolchain [required]. see installing pork. filterdiff from patchutils renaming a class 1. make two copies of the source(analysis and test). this isn't strictly required, but will save time. 2. the first copy will be an analysis copy. ...
Rhino history
ape to do so, allowing work on rhino to continue. now rhino is part of mozilla's open-source repository. originally, rhino compiled all javascript code to java bytecodes in generated classfiles. this produced the best performance (often beating the c implementation of javascript when run on a jit), but suffered from two faults. first, compilation time was long since generating java bytecodes and loading the generated classes was a heavyweight process. also, the implementation effectively leaked memory since most jvms don't really collect unused classes or the strings that are interned as a result of loading a class file. so in fall of 1998, rhino added an interpretive mode. the classfile generation code was moved to an optional, dynamically-loaded package. compilation is faster and when scripts...
Rhino scopes and contexts
.sealobject(); it would no be possible to set the additional properties to different values, one still would be able to alter the objects themselves. note that currently in order to use java classes (liveconnect) from a sealed shared scope you need to pre-load a number of objects needed for liveconnect into the scope before it gets sealed. these objects would normally be lazy loaded but the lazy loading fails if the scope is sealed. scriptableobject sealedsharedscope = cx.initstandardobjects(null, true); // force the liveconnect stuff to be loaded. string loadme = "regexp; getclass; java; packages; javaadapter;"; cx.evaluatestring(sealedsharedscope , loadme, "lazyload", 0, null); sealedsharedscope .sealobject(); dynamic scopes there's one problem with the setup outlined above. calls to func...
Rhino serialization
s.jsc.main f.js $ cat test2.js loadclass("f"); serialize(f, "f.ser"); g = deserialize("f.ser"); print(g()); $ java -classpath 'js.jar;.'org.mozilla.javascript.tools.shell.main test2.js 3 now the function f is compiled to a java class, but that class is then made available in the classpath so serialization works. this isn't that interesting an example since compiling a function to a class and then loading it accomplishes the same as serializing an interpreted function, but it becomes more relevant if you wish to serialize javascript objects that have references to compiled functions. original document information author: norris boyd last updated date: november 15, 2006 copyright information: portions of this content are © 1998–2006 by individual mozilla.org contributors; content available und...
Rebranding SpiderMonkey (1.8.5)
for example the default brand for spidermonkey 1.8.5 is 'mozjs185'. mkdir build-$brand-release cd build-$brand-release configure this build of spidermonkey with the desired options. for example: ../configure --enable-ctypes --with-system-nspr note: your desired configuration may be different. the only required part in this step is the ../configure command. so far, so good. now for the tricky parts. ...
SpiderMonkey Build Documentation
you can override this by passing options to the configure script: what it is where it gets put configure option executables, shell scripts /usr/...
Future directions
ps the spec work. for these features: do not add vendor prefixes. see http://hsivonen.iki.fi/vendor-prefixes/ for an extended argument. disable the feature before the beta channel. nightly and aurora are the good channels for experimental work. nspr the plan is to make spidermonkey not depend on nspr. no fundamental blockers currently exist, but ctypes is still using nspr's runtime library loading facilities. directories and filenames see https://wiki.mozilla.org/js_engine_modularization. ...
Getting SpiderMonkey source code
you can get the spidermonkey source code in gzipped form or directly from the mercurial repository. downloading gzipped spidermonkey source code you can download gzipped spidermonkey source code from the following urls: http://ftp.mozilla.org/pub/spidermonkey/releases/ http://ftp.mozilla.org/pub/spidermonkey/prereleases/ here is a command-line example of downloading and unzipping spidermonkey source code version 59.0: mkdir mozilla cd mozilla wget http://ftp.mozilla.org/pub/spidermonkey/prereleases/59/pre1/mozjs-59.0a1.0.tar.bz2 tar xvf mozjs-59.0a1.0.tar.bz2 these commands should work on most platforms including windows, as long as on windows you are using the mozillabuild bash shell. getting the latest spidermonkey source code from mercurial the mercurial repository at https://hg.mozil...
Hacking Tips
d*.*id*.tl" and "tl-dict.*pid*.*id*.json" file). these files contain all information to create a tracelogger graph. on https://github.com/h4writer/tracelogger you can find the instructions to create the graph (tools v2 > 1. creating a tracelogging graph). note 1: when you are doing this from "file:///" you will probably get a security warning in the console. this is because firefox doesn't allow loading files from the harddisk using httprequest, even when the file loading the file is on the harddisk. there are two solutions. one is to create a localhost server and serving the files there. the simplest way to do this is to run python -m simplehttpserver from within the above directory. the other being disable this check in "about:config", by temporarily switching "security.fileuri.strict_origin_p...
64-bit Compatibility
n nanojit will catch it while generating code. if this happens you will get an assert that points directly to the ill-typed lir. not all pointer-width values are actually pointers. to avoid equivocating, the rest of this article will use the term "native integers". a native integer is the size used for intptr_t/uintptr_t, which is usually the width of a general-purpose register on the target cpu. loading and storing native integers the harder cases to detect usually involve runtime value truncation. for example, this code will not load a native integer correctly on a 64-bit machine: struct object { void *data; }; lir->insload(lir_ld, objins, ins->insimm(offsetof(object, data))); lir_ld is 32-bit. on 64-bit machines you must use lir_ldq. luckily there is an alias that will choose the right op...
Introduction to the JavaScript shell
t easier to do comparisons between strings. note: this function is intended only for use when testing the javascript engine. line2pc([function, ] line) returns the program counter value corresponding to the specified line of code. if function is specified, line is an offset into the specified function. load(filename1 [filename]) loads the javascript files with the specified names. note: for loading non-javascript files, use read(). options([option ...]) lets you set or get options. if you specified options on the command line, the results of calling options will indicate which options you requested. you can also pass in new options to set. the available options are: option name description strict strict mode is enabled. werror warnings should be treat...
JS_AddExternalStringFinalizer
e returned from this function, and that understands how to free or release the memory pointed at by js_getstringchars(str). returns a nonnegative type index if there is room for finalizer in the global gc finalizers table, else returns -1. in a js_threadsafe build, this function must be invoked on the primordial thread only, at startup—or else the entire program must single-thread itself while loading a module that calls this function. to remove an external string finalizer, use js_removeexternalstringfinalizer. see also js_removeexternalstringfinalizer bug 724810 ...
JS_DecompileScript
this jscontext. script js::handle<jsscript*> script or function to decompile. description js_decompilescript returns the source code of script. if script is a function, it calls js_decompilefunction. otherwise, it returns the original source code of the script. if the script is not cached, it tries to load the source from file, and returns nullptr if an error happened while loading. if successful, js_decompilescript returns a string containing the source code of the script. otherwise, it returns a string containing "[no source]". from spidermonkey 17, this does not actually decompile the script, but returns the original source code (bug 761723). see also mxr id search for js_decompilescript js::compile js_compilescript js_decompilefunction js_destroyscript js::...
WebReplayRoadmap
re features are planned for the timeline, as described below. retroactive console logging console logging is one of the primary tools most developers use to debug a page. seeing messages in the console provides a simple and intuitive view into the order in which events have happened. without time travel, using the console requires repeatedly updating the source or the debugger's log points, reloading, and reproducing the bug. this is time consuming, especially when the bug only reproduces intermittently. retroactive console logging offers a large improvement to this workflow. the bug only needs to be reproduced in a recording tab once, and then console logs can be added which apply throughout the entire recording. this is based on the logpoints feature in the debugger, which can be enable...
Mozinfo
e this problem. mozinfo is a bridge interface, making the underlying (complex) plethora of os and architecture combinations conform to a subset of values of relevance to mozilla software. the current implementation exposes relevant key, values: os, version, bits, and processor. additionally, the service pack in use is available on the windows platform. api usage mozinfo is a python package. downloading the software and running python setup.py develop will allow you to do import mozinfo from python. mozinfo.py is the only file contained is this package, so if you need a single-file solution, you can just download or call this file through the web. the top level attributes (os, version, bits, processor) are available as module globals: if mozinfo.os == 'win': ... in addition, mozinfo exports...
XForms Accessibility
s based on top of the existing object hierarchy introduced in the mozilla accessibility module. xforms elements behavior is implemented in accordance with accessible toolkit checklist. in general, when elements are similar to html elements, they are exposed to msaa/atk in a similar way. get build subsections below explain how you can obtain accessible xforms-enabled build. these are either downloading latest build of firefox or building it yourself. downloading builds notion: xforms is no longer distributed with firefox build. you must build it yourself. see section below. for firefox, you may directly download the nighly "trunk" build of firefox and install the xforms extension which lives in 'xpi' directory of the build. note, xforms accessibility is implemented only on trunk. trunk build...
Using the Places history service
page: hides a page so that it does not appear in the ui. many pages are not visible in normal history lists, such as redirects and sub-frame contents.this is not implemented in navhistory. nsibrowserhistory.markpageastyped: called by the url bar when the user types in a url. this can be and is calledbefore the page is actually added to history, since the page isn't added until it actually starts loading. the typed flag affects the url bar autocomplete. this will cause the transition type of the next visit of the url to be marked as "typed." nsinavhistoryservice.markpageasfollowedbookmark: called by the ui (implemented, but not yet called, see bug 409301) when the user selects a bookmark. this will cause the transition type of the next visit of the url to be marked as "bookmark." nsinavhistorys...
Using the Places livemark service
. accessing a livemark's feed uri nsilivemarkservice.getfeeduri() gets the uri of the syndication feed associated with a livemark container. var feeduri = livemarkservice.getfeeduri(newlvmkid); //newlvmkid = see "create a new livemark" for more detail. nsilivemarkservice.setfeeduri() sets the uri of feed associated with a livemark container. note: the caller is responsible for reloading the livemark after changing its feed uri (since the contents are likely to be different given a different feed). livemarkservice.setfeeduri(newlvmkid, uri("http://foo.example.com/rss.xml")); //newlvmkid = see "create a new livemark" for more detail. update behavior five seconds after the browser starts up, the livemark service's update timer is started. the update timer fires im...
XPCOM glue
Mozilla › Tech › XPCOM › Glue
dy has full xpcom loaded and initialized. frozen linkage: standalone glue (no dll dependencies) note: support for locating a standalone glue was removed in gecko 6.0. use this when you have a custom application where you want to embed gecko to show webpages in your own window. i.e. this linkage strategy is used when an embedder needs to bootstrap xpcom by finding a compatible gre on disk and loading it. in order to use xpcom, the embedding application first needs to find where the xpcom runtime is located. this is typically done using gre_getgrepathwithproperties. then, the code must call xpcomgluestartup, which will dynamically link against the xpcom runtime. only then can the embedding application initialize and use xpcom. embedding code which wishes to use only frozen symbols and cannot...
An Overview of XPCOM
assembled back together at runtime. the goal of xpcom is to allow different pieces of software to be developed and built independently of one another. in order to allow interoperability between components within an application, xpcom separates the implementation of a component from the interface, which we discuss in interfaces. 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. ...
Building the WebLock UI
d to the xpcom interfaces that carry out a lot of the browser functionality in mozilla. in using xpcom components you saw how xpcom objects are reflected into the interface layer as javascript objects. in this chapter, now that we've created the weblock component and made it available to xpcom, we create the ui that actually instantiates the weblock component and uses its methods to control page loading in the browser. in the previous section, we outlined the javascript that interacts with the weblock component. in this section, we are going to create the xul interface that calls the javascript methods when the user interacts with it. the xul document the first thing to do is create the actual xul document in which the user interface for the dialog and the events that initiate interaction wit...
Component Internals
focusing on "native components," shared libraries exporting a nsgetmodule symbol. but if there is a component loader for javascript installed, then you can also write a javascript component. to register, unregister, load and manage various component types, xpcom abstracts the interface between the xpcom component and xpcom with the component loader. this loader is responsible for initialization, loading, unloading, and supporting the nsimodule interface on behalf of each component. it is the component loader's responsibility to provide scriptable component support. when building a "native" component, the component loader looks for an exported symbol from the components shared library. "native" here includes any language that can generate a platform native dynamically loaded library. scripting l...
Packaging WebLock
file, an rdf manifest for the package as a whole, and the component files (weblock.xpt and weblock4.dll). the component files are copied to the components directory of the gecko application, and the weblock subdirectory gets copied over into the chrome subdirectory, where its ui resources can be added dynamically to the xul-based gecko application. the next section shows how this process of downloading, copying and registering the necessary files from the xpi can be achieved with an xpinstall installation script. the weblock installation script the installation script is the javascript file that is stored within the xpi. it must appear at the top level of the installation archive (i.e., weblock.xpi) itself. once triggered (see the weblock trigger script), the installation script: downloads...
Preface
ial is a practical (and, we hope, genuinely useful) addition to the browser. in order to build it, your gecko sdk or mozilla source tree needs to be version 1.2 or later (xpcom interfaces were not fully frozen in prior releases). this book assumes you are using the sdk rather than compiling in a mozilla source tree, though the difference between these two approaches is minimal. details about downloading the sdk, building, and getting programmatic access to gecko components are provided in the appendix to this book, setting up the gecko sdk. conventions the formatting conventions listed below are used to designate specific types of information in the book and make things easier to scan. the goal is to use as few formats as possible, but to distinguish the various different types of information ...
Setting up the Gecko SDK
« previousnext » this chapter provides basic setup information for the gecko software development kit (sdk) used to build the weblock component in this tutorial. 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. downloading and setting the sdk the gecko sdk provides all of the tools, headers, and libraries that you need to build xpcom components. the sdk is available for windows, linux, and mac operating systems, and versions for other operating systems are being developed, and can be retrieved from as a single archive from the following platform-specific locations (need correction for last version (now 1.9.2.8). there is now separate archive with gecko-sdk, just x...
Starting WebLock
e iweblock : nsisupports the web locking interface the body of the block (the stuff between the curly braces) defines the methods and attributes of our interface. there are basically two functional sets on this interface. the first section of the interface controls whether or not weblock checks to see if a web page can be loaded. if locked, weblock will prevent sites not on the white list from loading. void lock(); void unlock(); this interface does not enforce any policy with respect to how the user enables or disables this feature. this allows maximum flexibility in the implementation. any place in the application can acquire this interface via the service manager and call unlock or lock. for example, the user interface may bring up a dialog asking the user for a password before calli...
Creating XPCOM components
this material may be distribute...
Receiving startup notifications
plication's manifest is used to get a list of the components it needs to register, and those components are loaded. this gets enough of xpcom and the application loaded and running that the extension manager can then be loaded and handle installing, uninstalling, and updating any installed extensions. once that process is completed, extensions can then be loaded by simply reading their manifests, loading their components, and continuing with application startup, all without having to restart the browser. receiving startup notifications prior to gecko 2.0 (firefox 4) to receive startup notifications, one needs to register with the "app-startup" category using nsicategorymanager; having done so, the component will receive these startup notifications, including: xpcom-startup sent when xpcom finish...
Components.utils.Sandbox
, in some cases it can be difficult to remove all references. for example, the code in the sandbox might be a third-party library that sets expando properties or adds event listeners to a window. in this case, components.utils.nukesandbox can be used to force the sandbox to be freed immediately. example executing in current tab scope more ways to load scripts into a sandbox can be found on the loading scripts page. this example is to be run from scratchpad with environemnt set to browser. it alerts the dollar sign function. this code was tested on twitter.com and gets access to the jquery $. var sandboxscript = 'alert($)'; var options = { sandboxprototype: content, wantxrays: false // only set this to false if you need direct access to the page's javascript. true provides a safer, is...
Components.utils.unload
the "resource://" url of the script to unload. this must be the same url that was used to load the script. example you can unload a module called mymodule.jsm using the following line of code: components.utils.unload("resource://myaddon/modules/mymodule.jsm"); note: currently components.utils.unload clears the global object of an unloaded module. this may cause modules to misbehave after unloading even if you have a reference to them. see bug 769253 see also bug 481603 the documentation in xpccomponents.idl the tests in js/xpconnect/tests/unit/ ...
Profiling XPCShell
nd; the total time; the time spend in the function itself is given (that is the total time excluding the time spend in functions called from this function). notes you need a trunk build from after 2007-05-28. using an earlier build will cause the profiler to hang the more adventurous can use the nsixpctoolsprofiler.idl interface directly, but be aware that you must start the profiler before loading the files you want to profile (creating an instance of a component loads the file!) ...
imgIDecoderObserver
1.0 66 introduced gecko 12.0 inherits from: imgicontainerobserver last changed in gecko 1.7 we make the distinction here between "load" and "decode" notifications. load notifications are fired as the image is loaded from the network or filesystem. decode notifications are fired as the image is decoded. ...
imgIRequest
sult of a failure of a proxy holder and not an internal failure. at least i think that's what it does. regardless, there's no reason for this flag to be public, and it should either go away or become a private state flag within imgrequest. do not rely on it. status_load_complete 0x4 the data has been fully loaded to memory, but not necessarily fully decoded. status_error 0x8 an error occurred loading the image. status_frame_complete 0x10 the first frame has been completely decoded. status_decode_complete 0x20 the whole image has been decoded. cors_none 1 cors modes images can be loaded with. by default, all images are loaded with cors_none and cannot be used cross-origin in context like webgl. if an html img element has the crossorigin attribute set, the imgirequest will be validated ...
mozIAsyncFavicons
ccurred while fetching it. if auri is not null, the other parameters may contain the favicon data. however, if no favicon data is currently associated with the favicon uri, adatalen will be 0, adata will be an empty array, and amimetype will be an empty string. setandfetchfaviconforpage() declares that a given page uses a favicon with the given uri and attempts to fetch and save the icon data by loading the favicon uri through a asynchronous network request. if the icon data already exists, we will not try to reload the icon unless aforcereload is true. similarly, if the icon is in the failed favicon cache we will not do anything unless aforcereload is true, in which case we'll try to reload the favicon. this function will only save favicons for "good" uris, as defined by what gets added to hist...
mozIJSSubScriptLoader
bject). ...
nsIAccessibleEvent
s been closed. event_scrolling_start 0x0026 0x0023 scrolling has started on a scroll bar. event_scrolling_end 0x0027 0x0024 scrolling has ended on a scroll bar. event_minimize_start 0x0028 0x0025 a window object is about to be minimized or maximized. event_minimize_end 0x0029 0x0026 a window object has been minimized or maximized. event_document_load_complete 0x002b 0x0027 the loading of the document has completed. event_document_reload 0x002c 0x0028 the document contents are being reloaded. event_document_load_stopped 0x002d 0x0029 the loading of the document was interrupted. event_document_attributes_changed 0x002e 0x002a the document wide attributes of the document object have changed. event_document_content_changed 0x002f 0x002b the contents of the document...
nsIAlertsService
supported platforms. lang optional language of title and text of the alert. only available on supported platforms. data optional the value of the cookie parameter passed to showalertnotification. principal optional the principal of the page that created the alert. used for ipc security checks, and to determine whether the alert is actionable. inprivatebrowsing optional controls the image loading behavior. if true, the image url will be loaded in private browsing mode. exceptions thrown ns_error_not_available unable to display the notification; this may happen, for example, on mac os x if growl is not installed. example simple usage the following code was used to display the above notification. var alertsservice = components.classes["@mozilla.org/alerts-service;1"]. ...
nsIApplicationCacheNamespace
or more namespace types. must be one or more of the constants defined under constants on this page. read only. namespacespec acstring the prefix of this namespace. this should be the asciispec of the uri prefix. read only. constants constant value description namespace_bypass 1 items matching this namespace can be fetched from the network when loading from this cache. the data attribute is not used. namespace_fallback 2 items matching this namespace can be fetched from the network when loading from this cache; however, if the load fails, the cache entry specified by the data attribute should be loaded intstead. namespace_opportunistic 4 items matching this namespace should be cached opportunistically. successful t...
nsIBrowserHistory
her interface in gecko 22.0. you should use nsinavhistoryservice.markpageastyped() instead. this method designates the url as having been explicitly typed in by the user, so it can be used as an autocomplete result. it is called by the url bar when the user types in a url. this can be and is called before the page is actually added to history, since the page isn't added until it actually starts loading. the typed flag affects the url bar autocomplete. this will cause the transition type of the next visit of the url to be marked as "typed." void markpageastyped( in nsiuri auri ); parameters auri the page that is to be marked as typed by the user. registeropenpage() obsolete since gecko 9.0 (firefox 9.0 / thunderbird 9.0 / seamonkey 2.6) mark a page as being ...
nsIChannelEventSink
when a redirect occurs. this may happen due to an http 3xx status code. this method notifies the sink that a redirect is about to happen, but also to gives the sink the right to veto the redirect by throwing an exception or passing a failure code in the callback. note: vetoing the redirect simply means that newchannel will not be opened. it is important to understand that oldchannel will continue loading as if it received a response of http 200, which includes notifying observers and possibly display or process content attached to the http response. if the sink wants to prevent this loading it must explicitly deal with it, e.g. by calling oldchannel->cancel() there is a certain freedom in implementing this method: if the return-value indicates success, a callback on callback is required. this cal...
nsIChromeFrameMessageManager
1.0 66 introduced gecko 2.0 inherits from: nsiframemessagemanager last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview void loadframescript(in astring aurl, in boolean aallowdelayedload); void removedelayedframescript(in astring aurl); methods loadframescript() loads a script into the remote frame. void loadframescript( in astring aurl, in boolean aallowdelayedload ); parameters aurl the url of the script to load into the frame; this must be an absolute url, but data: urls are supported. ...
nsIDOMProgressEvent
1.0 66 introduced gecko 1.9.1 deprecated gecko 22 inherits from: nsidomevent last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) the nsidomprogressevent is used in the media elements (<video> and <audio>) to inform interested code of the progress of the media download. this implementation is a placeholder until the specification is complete, and is compatible with the webkit progressevent. ...
nsIDownloadProgressListener
acurtotalprogress the current amount of progress that's been made on all downloads. amaxtotalprogress the value that the total progress needs to reach to indicate that all downloads are complete. adownload the nsidownload object whose progress is represented by the acurselfprogress and amaxselfprogress parameters. onsecuritychange() called when the level of security being used while downloading changes; for example, if the initial request is made via https but the download switches to http, this function gets called to notify you of that transition. void onsecuritychange( in nsiwebprogress awebprogress, in nsirequest arequest, in unsigned long astate, in nsidownload adownload ); parameters awebprogress the nsiwebprogress instance used by the download manager to monitor do...
nsIFrameMessageManager
parameters amessage the name of the message for which to add a listener. alistener an object implementing nsiframemessagelistener whose receivemessage method will be called when the message is received. listenwhenclosed default is false. set to oo if you want to receive messages during the short period after a frame has been removed from the dom and before its frame script has finished unloading. this parameter only has an effect for frame message managers in the main process. an alternative method to listen for death of frame script is to use message-manager-disconnect observer: observer notifications :: message manager. removemessagelistener() removes a message listener previously added by calling addmessagelistener(). void removemessagelistener( in astring amessage, in nsifra...
nsIInstallLocation
on nsifile the file system location where items live. items can be dropped in at this location. can be null for install locations that don't have a file system presence. note: this is a clone of the actual location which the caller can modify freely. read only. name astring the string identifier of this install location. read only. priority long the priority level of this install location in loading. read only. restricted boolean whether or not this install location is on an area of the file system that could be restricted on a restricted-access account, regardless of whether or not the location is restricted with the current user privileges. read only. constants constants representing priority of some default install locations. you should not use the exact values here, you should offse...
nsILivemarkService
d reloadalllivemarks(); parameters none. reloadlivemarkfolder() this method reloads the livemark with this folder id, whether or not it's expired. void reloadlivemarkfolder( in long long folderid ); parameters folderid the id of the folder to be reloaded. setfeeduri() this method sets the uri of the feed associated with a livemark container. note: the caller is responsible for reloading the livemark after changing its feed uri (since the contents are likely to be different given a different feed). void setfeeduri( in long long container, in nsiuri feeduri ); parameters container the folder id of a livemark container. feeduri nsiuri object representing the syndication feed uri. exceptions thrown ns_error_invalid_arg if the folder id isn't known or identifies a ...
nsIMessageListenerManager
n listenwhenclosed); parameters messagename a string indicating the name of the message to listen for. listener an nsimessagelistener to invoke when a message is received. see nsimessagelistener for details of the message syntax. listenwhenclosed specify true to receive messages during the short period after a frame has been removed from the dom and before its frame script has finished unloading; this is false by default. this parameter only has an effect for frame message managers in the main process. an alternative method to listen for death of frame script is to use a message-manager-disconnect observer; see observer notifications :: message manager. removemessagelistener() undo an addmessagelistener() call; that is, calling this causes listener to stop being invoked when the spec...
nsIMessenger
inherits from: nsisupports implemented by: @mozilla.org/messenger;1. 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. ...
nsIMicrosummary
return value returns true if the microsummaries are equal. false if they aren't. note: this method returns false if either objects don't have a generator removeobserver() remove a microsummary observer from this microsummary. void removeobserver( in nsimicrosummaryobserver observer ); parameters observer the microsummary observer to remove. update() update the microsummary, first loading its generator and page content as necessary. if you want know when a microsummary finishes updating, add an observer before calling this method. void update(); see also microsummary topics creating a microsummary ...
nsIMsgDBView
wstypes2.idl. currentlydisplayedmessage nsmsgviewindex readonly: the index of the currently displayed message. nsmsgviewindex is defined as a unsigned long in mailnewstypes2.idl. suppressmsgdisplay boolean suppress displaying messages. used when the message pane is collapsed. suppresscommandupdating boolean suppress command updating. used during folder loading. db nsimsgdatabase readonly: the current database of messages. supportsthreading boolean readonly: does the current database support threading? searchsession nsimsgsearchsession the current search session. removerowonmoveordelete boolean readonly: usinglines boolean readonly: use lines for size. if false kb are used. ...
nsINavHistoryContainerResultNode
has been dynamically generated by the remote container api, or a bookmark folder (result_type_folder) for which some service (such as livemarks) has registered to provide certain operations. state unsigned short the current state of the container. this is one of the state constants. constants state constants constant value description state_closed 0 the container is closed. state_loading 1 the container has been opened asynchronously, but is still loading and is not all the way opened yet. state_opened 2 the container is open. methods findnodebydetails() returns a node matching specified details. nsinavhistoryresultnode findnodebydetails( in autf8string auristring, in prtime atime, in long long aitemid, in boolean recursive ); parameters auristring the uri attr...
nsINavHistoryService
meters auri the page that is to be marked as followed by a bookmark. markpageastyped() this method designates the url as having been explicitly typed in by the user, so it can be used as an autocomplete result. it is called by the url bar when the user types in a url. this can be and is called before the page is actually added to history, since the page isn't added until it actually starts loading. the typed flag affects the url bar autocomplete. this will cause the transition type of the next visit of the url to be marked as "typed." void markpageastyped( in nsiuri auri ); parameters auri the page that is to be marked as typed by the user. markpageasfollowedlink() designates the specified url as coming from a link explicitly followed by the user (for example by clicking on it)...
nsIParserUtils
ized content is inserted into a different-origin context without an iframe-equivalent sandboxing mechanism. by default, the sanitizer doesn't try to avoid leaking information that the content was viewed to third parties. that is, by default, for example <img> with a source pointing to an http server potentially controlled by a third party is not removed. to avoid ambient information leakage upon loading the sanitized content, use the sanitizerinternalembedsonly flag. in that case, <a> links (and similar) to other content are preserved, so an explicit user action (following a link) after the content has been loaded can still leak information. by default, non-dangerous non-css presentational html elements and attributes or forms are not removed. to remove these, use sanitizerdropnoncsspresentatio...
nsISHistoryListener
siwebnavigation.loaduri(). note: you can't cancel this operation. void onhistorynewentry( in nsiuri anewuri ); parameters anewuri the uri of the document to be added to session history. onhistorypurge() called when entries are removed from session history. entries can be removed from session history for various reasons; for example to control the browser's memory usage, to prevent users from loading documents from history, to erase evidence of prior page loads, etc. to purge documents from session history call nsishistory.purgehistory(). boolean onhistorypurge( in long anumentries ); parameters anumentries the number of entries to be removed from session history. return value true to allow the purge operation to proceed or false to cancel it. onhistoryreload() called when the current do...
nsIScriptableIO
file and stream guide: [ nsiscriptableio | accessing files | getting file information | reading from files | writing to files | moving, copying and deleting files | uploading and downloading files | working with directories ] important note: the pages from the file and stream guide use the io object (nsiscriptableio), which was not available in any released version of the platform (pending some fixes). there are alternative xpcom apis you can use, your help in updating this pages to use the supported api is very much welcome! other documentation on files and i/o not using the unavailable nsiscriptableio apis: code snippets: file i/o, open and save dialogs, reading textual data, writing textual data, list of file-related error codes. nsiscriptableio provides a convenient api for creati...
nsITraceableChannel
tab that made the request) with your own implementation (see "implementing nsistreamlistener" below). after that your nsistreamlistener implementation will get the response data and will be able to pass the data on to the original nsistreamlistener (possibly modifying it). see nsitraceablechannel, intercept http traffic for a more detailed description with code samples. see modify url before loading page in firefox for an overview of how to modify a request before it is made. method overview nsistreamlistener setnewlistener(in nsistreamlistener alistener); methods setnewlistener() replaces the channel's current listener with a new one, returning the listener previously assigned to the channel. nsistreamlistener setnewlistener( in nsistreamlistener alistener ); parame...
nsIUpdateCheckListener
pleted. void oncheckcomplete( in nsixmlhttprequest request, [array, size_is(updatecount)] in nsiupdate updates, in unsigned long updatecount ); parameters request the nsixmlhttprequest object handling the update check. updates an array of nsiupdate objects describing the available updates. updatecount the number of updates in the updates array. onerror() called when an error occurs while loading the remote update service file. void onerror( in nsixmlhttprequest request, in nsiupdate update ); parameters request the nsixmlhttprequest object handling the update check. update an nsiupdate object containing details about the error in its statustext attribute. onprogress() called every time there is a progress notification loading the update service file. void onprogress( in nsixmlht...
nsIVersionComparator
backwards compatibility, if "string-b" is "+" then "number-a" is incremented by 1 and "string-b" becomes "pre". 1.0pre1 < 1.0pre2 < 1.0 == 1.0.0 == 1.0.0.0 < 1.1pre == 1.1pre0 == 1.0+ < 1.1pre1a < 1.1pre1 < 1.1pre10a < 1.1pre10 implemented by: @mozilla.org/xpcom/version-comparator;1. the service can be accessed directly via services.vc after loading services.jsm or with the following code: var versioncomparator = components.classes["@mozilla.org/xpcom/version-comparator;1"] .getservice(components.interfaces.nsiversioncomparator); method overview long compare(in acstring a, in acstring b); methods compare() compare two version strings. long compare( in acstring a, in acstring b ); paramet...
nsIWebNavigation
, all content is loaded from the cache (if available) and page state (such as form values and scroll position) is restored. void goforward( ); gotoindex() tells the object to navigate to the session history item at a given index. void gotoindex( in long index ); parameters index the index of the session history item to go to. loaduri() loads a given uri. this will give priority to loading the requested uri in the object implementing this interface. if it can't be loaded here however, the uri dispatcher will go through its normal process of content loading. void loaduri( wstring uri, unsigned long loadflags, nsiuri referrer, nsiinputstream postdata, nsiinputstream headers ); parameters uri the uri string to load. for http and ftp urls and possibly others, character...
nsIXMLHttpRequestEventTarget
1.0 66 introduced gecko 1.9.1 inherits from: nsidomeventtarget last changed in gecko 5.0 (firefox 5.0 / thunderbird 5.0 / seamonkey 2.2) attributes attribute type description onabort nsidomeventlistener a javascript function object that gets invoked if the operation is canceled by the user. onerror nsidomeventlistener a javascript function object that gets invoked if the operation fails to complete due to an error. ...
nsIXMLHttpRequestUpload
content/base/public/nsixmlhttprequest.idlscriptable this interface provides access to the features needed when uploading data using nsixmlhttprequest. 1.0 66 introduced gecko 1.9.1 inherits from: nsidomeventtarget last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) attributes attribute type description onabort nsidomeventlistener onerror nsidomeventlistener onload nsidomeventlistener onloadstart nsidomeventlistener onprogress nsidomeventlistener see also nsixmlhttprequest nsixmlhttprequesteventtarget xmlhttprequest using xmlhttprequest ...
Address Book examples
k type do not support. } registerloadlistener(foo); save listeners are functions that take the same parameters, and can be registered with: registersavelistener(foo); load and save listeners can be unregistered using unregisterloadlistener(foo) and unregistersavelistener(foo), respectively. photo handlers photo handlers allow developers to customize the behavior of the contact editor when loading or saving contact photos. this is useful if, for example, cards within your address book implementation need to save contact photos within a database. a photo handler defines the behavior of the contact editor for a particular photo type. each photo handler must implement the following interface: /* * onload: function(acard, adocument): * called when the editor wants to populate the contact...
Filelink Providers
ageable from within the preferences dialog, in the attachment pane, in the outgoing tab. the content to the right of the menulist is an iframe, pointed at a url read from the providers managementurl attribute, which should point to an xhtml page. the xhtml page should have a function in the global scope called onloadprovider. this function is called automatically once the dom content is done loading, and is passed a single parameter - the provider instance whose data is being displayed. ...
MailNews Filters
er. in the case of pop3, filter execution is synchronous. for each new header, we evaluate the filter criteria and apply the actions synchronously, including moving a message to an other local folder, and advance to the next header. for imap, we tend to initiate the urls synchronously, but because we don't run two urls simultaneously on the same folder, the urls don't run until we've finished downloading headers. we also coalesce moves to the same destination folder, so that we can do them in one url/command to the server, and we playback those moves when the header download is done. after the fact filters these are one or more filters run on one or more folders *after* the headers have been downloaded. these filters are initiated in the filter editor, and implemented in nsmsgfilterservice.cp...
Mail client architecture overview
that operate on this mail data. events - as data changes throughout the mail application, the event system notifies key components such as datasources and the url system of these changes. mail window management - each mail window maintains a certain amount of state to aid in view navigation, progress display, etc. url display and dispatching - in order to perform network operations such as downloading new mail, copying and moving messages, and displaying messages from a remote server, the url system interacts with necko and reflects it's state to the mail window. there are also a number of protocol independant subsystems that have a symbiotic relationship with base: libmime - for dealing with rfc822 messages and their mime parts. this library has the cabability to stream messages to an ht...
Thunderbird Binaries
hunderbird/releases/ early preview releases whilst writing new versions of thunderbird, developers release preview versions, known as betas. these builds are made to get feedback from testers and extension developers. note: while beta builds have had some testing, they should be considered preview only and should not be used in a production environment. please read the release notes before downloading. preview releases are available from http://www.mozilla.org/thunderbird/channel/ nightly builds nightly builds are cutting-edge builds. they are built every 24 hours by the tinderboxes from the very latest source code. there are various sorts of nightly builds available for download. if you wish to download nightly builds to help us test for the next release, please read the testing page for w...
Add to iPhoto
t the fsref structure to reference the same file as the cfurl. if that fails, we display an error; otherwise, we cast the cfmutablearrayref into a cfarrayref by calling ctypes.cast(), then call lsopenurlswithrole() to actually send the image to iphoto. after doing that, we clean up after ourselves by releasing the cfurl object and the array, then shutting down the three libraries we used. downloading the image the downloadimage() method handles actually downloading the image to a temporary file; it then returns the local pathname of the downloaded file to the caller. downloadimage: function(src) { // get the file name to download from the url var filename = src.slice(src.lastindexof("/")+1); // build the path to download to var dest = components.classes["@mozilla.org/file/directo...
Using js-ctypes
before you can use js-ctypes, you need to import the ctypes.jsm code module. this is as simple as including the following line of code in the desired javascript scope: components.utils.import("resource://gre/modules/ctypes.jsm") loading a native library once you've imported the code module, you can call the ctypes.open() method to load each native library you wish to use. on windows, for example, you might load the system user32 library like this: var lib = ctypes.open("user32.dll"); on mac os x, you can load the core foundation library from the core foundation framework like this: var corefoundation = ctypes.open("/system/library/frameworks/corefoundation.framework/corefoundation"); the returned object is a library object that you use to declare functions and data types for use with t...
js-ctypes reference
the ctypes object also provides numerous predefined types that correspond to primitives and common typedefs in c. working with libraries to load a library, use ctypes.open(). the library object is used mostly to declare native functions provided by the library so that js-ctypes knows how to call them. ...
Constants - Plugins
npapi.h. error codes code value description nperr_no_error 0 no errors occurred. nperr_generic_error 1 error with no specific error code occurred. nperr_invalid_instance_error 2 invalid instance passed to the plug-in. nperr_invalid_functable_error 3 function table invalid. nperr_module_load_failed_error 4 loading of plug-in failed. nperr_out_of_memory_error 5 memory allocation failed. nperr_invalid_plugin_error 6 plug-in missing or invalid. nperr_invalid_plugin_dir_error 7 plug-in directory missing or invalid. nperr_incompatible_version_error 8 versions of plug-in and communicator do not match. nperr_invalid_param 9 parameter missi...
Version, UI, and Status Information - Plugins
r platforms did not have windowless plug-in support at the time it was added to ms windows and mac os x, so a different method must be used to detect whether the browser provides support. bool has_windowless() { npbool supportswindowless = false; nperror ret = npn_getvalue(instance, npnvsupportswindowless, &supportswindowless); return ret == nperr_no_error && supportswindowless; } reloading a plug-in when the browser starts up, it loads all the plug-ins it finds in the plugins directory for the platform. if you call npn_reloadplugins, the browser reloads all plug-ins in the plugins directory without restarting. this causes the browser to install a new plug-in and load it, or remove a plug-in, without having to restart. consider using this function as part of the plug-in's smartupda...
Gecko Plugin API Reference - Plugins
out how much data the plug-in can accept writing the stream to the plug-in sending the stream in random-access mode sending the stream in file mode sending a stream creating a stream pushing data into the stream deleting the stream example of sending a stream urls getting urls getting the url and displaying the page posting urls posting data to an http server uploading files to an ftp server sending mail memory allocating and freeing memory mac os flushing memory (mac os only) version, ui, and status information displaying a status line message getting agent information getting the current version finding out if a feature exists reloading a plug-in plug-in side plug-in api this chapter describes methods in the plug-in api t...
Source map errors - Firefox Developer Tools
n" is a required argument original source missing an original source may be missing. you may encounter this when trying to open one of the original sources in the debugger. the message looks a little different in this case: in this case, the error will also be displayed in the source tab in the debugger: networkerror when attempting to fetch resource a bug in firefox prevents it from loading source maps for web extensions. see bug 1437937: webextensions doesn't find source maps for details. source-map-fehler: typeerror: networkerror when attempting to fetch resource. ressourcen-adresse: moz-extension://c7f0f003-4fcf-49fd-8ec0-c49361266581/background.js source-map-adresse: background.js.map the only workaround is to manually change the map url to a public one (http://localhost:12...
DevTools API - Firefox Developer Tools
t that was returned from toolpanel.build(). getpanel(toolid) get the toolpanel for given tool. parameters: toolid {string} - the tool identifier. return value: the toolpanel object if the tool with the given toolid is active, otherwise undefined. getpanelwhenready(toolid) similar to getpanel() but waits for the tool to load first. if the tool is not already loaded or currently loading the returned promise won't be fulfilled until something triggers the tool to load. parameters: toolid {string} - the tool identifier. return value: a promise that is fulfilled with the toolpanel object once the tool has finished loading. gettoolpanels() returns a toolid → toolpanel map for currently loaded tools. getnotificationbox() returns a <xul:notificationbox> element f...
Index - Firefox Developer Tools
e, networking, tools the request details pane appears when you click on a network request in the request list. this pane provides more detailed information about the request. 51 network request list 110n:priority, debugging, dev tools, firefox, guide, networking, tools the request list of the network monitor shows a list of all the network requests made in the course of loading the page. 52 performance analysis 110n:priority, debugging, dev tools, firefox, guide, networking, tools the network monitor includes a performance analysis tool, to help show you how long the browser takes to download the different parts of your site. 53 throttling 110n:priority, debugging, dev tools, firefox, guide, networking, tools the network monitor...
Basic operations - Firefox Developer Tools
taking a heap snapshot to take a snapshot of the heap, click the "take snapshot" button, or the camera icon on the left: the snapshot will occupy the large pane on the right-hand side. on the left, you'll see an entry for the new snapshot, including its timestamp, size, and controls to save or clear this snapshot: clearing a snapshot to remove a snapshot, click the "x" icon: saving and loading snapshots if you close the memory tool, all unsaved snapshots will be discarded. to save a snapshot click "save": you'll be prompted for a name and location, and the file will be saved with an .fxsnapshot extension. to load a snapshot from an existing .fxsnapshot file, click the import button, which looks like a rectangle with an arrow rising from it (before firefox 49, this button was label...
Memory - Firefox Developer Tools
the memory tool lets you take a snapshot of the current tab's memory heap. it then provides a number of views of the heap that can show you which objects account for memory usage and exactly where in your code you are allocating memory. the basics opening the memory tool taking a heap snapshot comparing two snapshots deleting snapshots saving and loading snapshots recording call stacks analyzing snapshots the tree map view is new in firefox 48, and the dominators view is new in firefox 46. once you've taken a snapshot, there are three main views the memory tool provides: the tree map view shows memory usage as a treemap. the aggregate view shows memory usage as a table of allocated types. the dominators view shows the "retained size" of objects: that is, the size...
Network request details - Firefox Developer Tools
a more detailed, annotated, view of the timeline bar, so it is easy to locate performance bottlenecks. this tab can include the following sections. queued, started, downloaded new in firefox 72, we now show the following timings at the top of the timings tab, making dependency analysis a lot easier: queued: when the resource was queued for download. started: when the resource started downloading. downloaded: when the the resource finished downloading. note: future versions will also show this information when entries in the network monitor timeline graph are moused over (see bug 1580493). request timing the request timing section breaks a network request down into the following subset of the stages defined in the http archive specification: name description ...
Network request list - Firefox Developer Tools
each request is displayed in its own row: by default, the network monitor is cleared each time you navigate to a new page or reload the current page. you can override this behavior by checking "enable persistent logs" in the settings. network request columns you can toggle columns on and off by right-clicking on the table header and choosing the specific column from the context menu. ...
Examine and edit CSS - Firefox Developer Tools
perty that starts with the letters you've typed. for example, here the user has typed "c" and the default choice is "color": if you enter an invalid value for a property when editing it, or an unknown property name, a yellow alert icon appears besides the declaration. edits that you make in the rules view are reflected in the style editor, and vice versa. any changes you make are temporary: reloading the page will restore the original styling. while you're editing css, the context menu you'll see is the normal one for working with editable text: css variable autocompletion css variable names will auto-complete depending on the variables defined in the css. if you enter var( into a property value and then type a dash (-), any variables you have declared in your css will then appear in an ...
Responsive Design Mode - Firefox Developer Tools
browser window show user agent - when checked displays the user agent string the final two options define when the page is reloaded: reload when touch simulation is toggled: when this option is enabled, the page is reloaded whenever you toggle touch support. reload when user agent is changed: when this option is enabled, the page isreloaded whenever the user agent is changed. reloading on these changes can be helpful because certain page behaviors would otherwise not be applied. for example, many pages check for touch support on load and only add event handlers if it is supported, or only enable certain features on certain browsers. however, if you are not interested in examining such features (maybe you are just checking the overall layout at different sizes), these reloads c...
Tips - Firefox Developer Tools
tyle sheet. click an @media rule to apply it in responsive design mode. click the import button () to import a style sheet or the create button () to create a new one. click the options button in the style sheet pane and click "show original sources" to toggle the display of css preprocessor files. network monitor click the request summary to compare performance of cache vs. no-cache page loading. when a request is selected click "edit and resend" to modify its headers and send it again. check "enable persistent logs" in the settings to keep requests from before even after navigation. hover the "js" icon within the "cause" column to see the javascript stack trace, which caused the request. check "disable http cache (when toolbox is open)" in the settings to disable the network cache w...
AbstractRange - Web APIs
eah row beneath them shows the next layer of depth into the dom tree. blue nodes are text nodes, containing the text that gets shown onscreen. each element's contents are linked below it in the tree, potentially spaw...
Attr - Web APIs
Web › API › Attr
erdocument you shouldn't have been using this in the first place, so you probably don't care that this is going away. parentnode this property now always returns null. previoussibling this property now always returns null. schematypeinfo read only the type information associated with this attribute. while the type information contained in this attribute is guaranteed to be correct after loading the document or invoking document.normalizedocument, this property may not be reliable if the node was moved. specified this property now always returns true. textcontent use attr.value instead. the following methods have been deprecated: appendchild() obsolete since gecko 14 modify the value of attr.value instead. clonenode() you shouldn't have been using this in the first place, so ...
Background Tasks API - Web APIs
ges to only be available to the main thread. because event handling and screen updates are two of the most obvious ways users notice performance issues, it's important for your code to be a good citizen of the web and help to prevent stalls in the execution of the event loop. in the past, there's been no way to do this reliably other than by writing code that's as efficient as possible and by offloading as much work as possible to workers. window.requestidlecallback() makes it possible to become actively engaged in helping to ensure that the browser's event loop runs smoothly, by allowing the browser to tell your code how much time it can safely use without causing the system to lag. if you stay within the limit given, you can make the user's experience much better. getting the most out of idle...
Body.arrayBuffer() - Web APIs
Web › API › Body › arrayBuffer
ybuffer. syntax response.arraybuffer().then(function(buffer) { // do something with buffer }); parameters none. return value a promise that resolves with an arraybuffer. examples playing music in our fetch array buffer live, we have a play button. when pressed, the getdata() function is run. note that before playing full audio file will be downloaded. 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. when the fetch is successful, we read an arraybuffer out of the response using arraybuffer(), decode the audio data using audiocontext.
CSS.paintWorklet (Static property) - Web APIs
Web › API › CSS › paintWorklet
paintworklet is a static, read-only property of the css interface that provides access to the paintworklet, which programmatically generates an image where a css property expects a file. syntax var worklet = css.paintworklet; value the paintworklet object. examples the following example demonstrates loading a paintworklet from its js file and does so by feature detection. <script> if ('paintworklet' in css) { css.paintworklet.addmodule('checkerboard.js'); } </script> specifications specification status comment css painting api level 1the definition of 'paintworklet' in that specification. working draft initial definition. ...
CanvasRenderingContext2D.font - Web APIs
css font value. the default font is 10px sans-serif. examples using a custom font in this example we use the font property to specify a custom font weight, size, and family. html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.font = 'bold 48px serif'; ctx.stroketext('hello world', 50, 100); result loading fonts with the css font loading api with the help of the fontface api, you can explicitly load fonts before using them in a canvas. let f = new fontface('test', 'url(x)'); f.load().then(function() { // ready to use the font in a canvas context }); specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.font' in tha...
Basic usage of canvas - Web APIs
this function, or one like it, could also be called using window.settimeout(), window.setinterval(), or any other event handler, as long as the page has been loaded first. here is how a template would look in action. as shown here, it is initially blank. a simple example to begin, let's take a look at a simple example that draws ...
CustomElementRegistry.whenDefined() - Web APIs
scription syntaxerror if the provided name is not a valid custom element name, the promise rejects with a syntaxerror. examples this example uses whendefined() to detect when the custom elements that make up a menu are defined. the menu displays placeholder content until the actual menu content is ready to display. <nav id="menu-container"> <div class="menu-placeholder">loading...</div> <nav-menu> <menu-item>item 1</menu-item> <menu-item>item 2</menu-item> ... <menu-item>item n</menu-item> </nav-menu> </nav> const container = document.getelementbyid('menu-container'); const placeholder = container.queryselector('.menu-placeholder'); // fetch all the children of menu that are not yet defined. const undefinedelements = container.queryselectorall(':n...
DOMHighResTimeStamp - Web APIs
gin the time origin is a standard time which is considered to be the beginning of the current document's lifetime. 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 during the process of unloading the previous document which was loaded in the window, a confirmation dialog was displayed to let the user confirm whether or not to leave the previous page, the time origin is the time at which the user confirmed that navigating to the new page was acceptable. if neither of the above determines the time origin, then the time origin is the time at which the navigation responsible for creating t...
Document.location - Web APIs
Web › API › Document › location
though document.location is a read-only location object, you can also assign a domstring to it. this means that you can work with document.location as if it were a string in most cases: document.location = 'http://www.example.com' is a synonym of document.location.href = 'http://www.example.com'. to retrieve just the url as a string, the read-only document.url property can also be used. ...
Document.write() - Web APIs
Web › API › Document › write
ent();"> <p>some original document content.</p> </body> </html> notes the text you write is parsed into the document's structure model. in the example above, the h1 element becomes a node in the document. writing to a document that has already loaded without calling document.open() will automatically call document.open(). after writing, call document.close() to tell the browser to finish loading the page. if the document.write() call is embedded within an inline html <script> tag, then it will not call document.open(). for example: <script> document.write("<h1>main title</h1>") </script> note: document.write() and document.writeln do not work in xhtml documents (you'll get an "operation is not supported" [ns_error_dom_not_supported_err] error in the error console). this happens whe...
Introduction to the DOM - Web APIs
different implementations of the dom, and these implementations exhibit varying degrees of conformance to the actual dom standard (a subject we try to avoid in this documentation), but every web browser uses some document object model to make web pages accessible via javascript. 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 sophisticate...
Element: error event - Web APIs
{ grid-area: log; } .event-log-contents { resize: none; } label, button { display: block; } button { height: 2rem; margin: .5rem; } img { width: 0; height: 0; } js const log = document.queryselector('.event-log-contents'); const badimg = document.queryselector('.bad-img'); badimg.addeventlistener('error', (event) => { log.textcontent = log.textcontent + `${event.type}: loading image\n`; console.log(event) }); const imgerror = document.queryselector('#img-error'); imgerror.addeventlistener('click', () => { badimg.setattribute('src', 'i-dont-exist'); }); result specifications specification status ui events working draft ...
FileReader.abort() - Web APIs
Web › API › FileReader › abort
the abort method aborts the read operation. upon return, the readystate will be done. syntax instanceoffilereader.abort(); exceptions dom_file_abort_err thrown when abort is called while no read operation is in progress (that is, the state isn't loading). specifications specification status comment file apithe definition of 'abort()' in that specification. working draft initial definition ...
FileReader - Web APIs
newly constructed filereader. see using files from web applications for details and examples. properties filereader.error read only a domexception representing the error that occurred while reading the file. filereader.readystate read only a number indicating the state of the filereader. this is one of the following: empty 0 no data has been loaded yet. loading 1 data is currently being loaded. done 2 the entire read request has been completed. filereader.result read only the file's contents. this property is only valid after the read operation is complete, and the format of the data depends on which of the methods was used to initiate the read operation. event handlers filereader.onabort a handler for the...
Introduction to the File and Directory Entries API - Web APIs
offline access or local cache (great for performance and speed) the app can write to files in place (for example, overwriting just the id3/exif tags and not the entire file). offline video viewer the app can download large files (>1gb) for later viewing. the app can access partially downloaded files (so that you can watch the first chapter of your dvd, even if the app is still downloading the rest of the content or if the app didn't complete the download because you had to run to catch a train). offline web mail client the client downloads attachments and stores them locally. the client caches attachments for later upload. big concepts before you start using the file and directory entries api, you need to understand a few concepts: the file and directory entri...
FontFace.FontFace() - Web APIs
Web › API › FontFace › FontFace
working draft initial definition ...
FontFace.family - Web APIs
Web › API › FontFace › family
'font family name'; var fontface = instanceoffontface.family; // "font family name" value a domstring. example var fontface = new fontface('roboto', 'url(https://fonts.example.com/roboto.woff2)'); console.log(fontface.family); // 'roboto' fontface.family = 'newroboto'; console.log(fontface.family); // 'newroboto' specifications specification status comment css font loading module level 3the definition of 'family' in that specification. working draft initial definition ...
FontFace.featureSettings - Web APIs
or sets infrequently used font features that are not available from a font's variant properties. it is equivalent to the font-feature-settings descriptor. syntax var featuresettingdescriptor = fontface.featuresettings; fontface.featuresettings = featuresettingdescriptor; value a cssomstring containing a descriptor. specifications specification status comment css font loading module level 3the definition of 'featuresettings' in that specification. working draft initial definition. ...
FontFace.load - Web APIs
Web › API › FontFace › load
face interface loads a font based on current object's constructor-passed requirements, including a location or source buffer, and returns a promise that resolves with the current fontface object. syntax var promise = fontface.load(); parameters none. return value a promise that resolves with a reference to the current fontface object when the font loads or rejects with a networkerror if the loading process fails. exceptions networkerror indicates that the attempt to load the font failed. specifications specification status comment css font loading module level 3the definition of 'load' in that specification. working draft initial definition. ...
FontFace.loaded - Web APIs
Web › API › FontFace › loaded
the loaded read-only property of the fontface interface returns a promise that resolves with the current fontface object when the font specified in the object's constructor is done loading or rejects with a syntaxerror. syntax var apromise = fontface.loaded; value a promise that resolves with the current fontface object. specifications specification status comment css font loading module level 3the definition of 'loaded' in that specification. working draft initial definition. ...
FontFace.status - Web APIs
Web › API › FontFace › status
the status read-only property of the fontface interface returns an enumerated value indicating the status of the font, one of "unloaded", "loading", "loaded", or "error". syntax var status = fontface.status; value one of "unloaded", "loading", "loaded", or "error". specifications specification status comment css font loading module level 3the definition of 'status' in that specification. working draft initial definition. ...
FontFace.stretch - Web APIs
Web › API › FontFace › stretch
property of the fontface interface retrieves or sets how the font stretches. it is equivalent to the font-stretch descriptor. syntax var stretchdescriptor = fontface.stretch; fontface.stretch = stretchdescriptor; value a cssomstring containing a descriptor as it would be defined in a style sheet's @font-face rule. specifications specification status comment css font loading module level 3the definition of 'stretch' in that specification. working draft initial definition. ...
FontFace.style - Web APIs
Web › API › FontFace › style
the style property of the fontface interface retrieves or sets the font's style. it is equivalent to the font-style descriptor. syntax var style = fontface.style; fontface.style = value; value a cssomstring containing the descriptors defined in the style sheet's @font-face rule. specifications specification status comment css font loading module level 3the definition of 'style' in that specification. working draft initial definition. ...
FontFace.unicodeRange - Web APIs
sets the range of unicode codepoints encompassing the font. it is equivalent to the unicode-range descriptor. syntax var unicoderangedescriptor = fontface.unicoderange; fontface.unicoderange = unicoderangedescriptor; value a cssomstring containing a descriptor as it would appear in a style sheet's @font-face rule. specifications specification status comment css font loading module level 3the definition of 'unicoderange' in that specification. working draft initial definition. ...
FontFace.variant - Web APIs
Web › API › FontFace › variant
e fontface interface programatically retrieves or sets font variant values. it is equivalent to the font-variant descriptor. syntax var variantsubproperty = fontface.variant; fontface.variant = variantsubproperty; value a cssomstring containing a descriptor as it would be defined in a style sheet's @font-face rule. specifications specification status comment css font loading module level 3the definition of 'variant' in that specification. working draft initial definition. ...
FontFace.weight - Web APIs
Web › API › FontFace › weight
eight property of the fontface interface retrieves or sets the weight of the font. it is equivalent to the font-weight descriptor. syntax var weightdescriptor = fontface.weight; fontface.weight = weightdescriptor; value a cssomstring containing a descriptor as it would be defined in a style sheet's @font-face rule. specifications specification status comment css font loading module level 3the definition of 'weight' in that specification. working draft initial definition. ...
FontFaceSet.check() - Web APIs
Web › API › FontFaceSet › check
icode range contains at least one of the characters in text. this does not check for individual glyph coverage. examples document.fonts.check("12px courier"); // returns true if the font courier is available at 12px document.fonts.check("12px myfont", "ß"); // returns true if the font 'myfont' has a ß character. specifications specification status comment css font loading module level 3the definition of 'check' in that specification. working draft initial definition ...
FontFaceSet.load() - Web APIs
Web › API › FontFaceSet › load
ntains at least one of the characters in text. this does not check for individual glyph coverage. examples // returns a promise that will be fulfilled or rejected according the success to load myfont // the code in 'then' can assume the availability of that font. document.fonts.load("12px myfont", "ß").then(…); specifications specification status comment css font loading module level 3the definition of 'load' in that specification. working draft initial definition ...
FontFaceSet.ready - Web APIs
Web › API › FontFaceSet › ready
the ready readonly property of the fontfaceset interface returns a promise that resolves to the given fontfaceset. syntax fontfaceset.ready.then(function(fontfaceset) { // ... }); returns a promise that resolves to the given fontfaceset. parameters none. specifications specification status comment css font loading module level 3the definition of 'fontfaceset' in that specification. working draft initial definition ...
FontFaceSetLoadEvent.FontFaceSetLoadEvent() - Web APIs
new fontfaceloadevent object which is fired whenever a fontfaceset loads. syntax var fontfacesetloadevent = new fontfacesetloadevent(type[, options]) parameters type the literal value 'type' (quotation marks included). options optional options are as follows: fontfaces: an array of fontface instances. specifications specification status comment css font loading module level 3the definition of 'fontfacesetloadevent()' in that specification. working draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. desktopmobilechromeedgefirefoxinternet explore...
FontFaceSetLoadEvent.fontfaces - Web APIs
working draft initial definition. ...
Using FormData Objects - Web APIs
...
GlobalEventHandlers.onloadeddata - Web APIs
the onloadeddata property of the globaleventhandlers mixin is the eventhandler for processing loadeddata events. the loadeddata event is fired when the first frame of the media has finished loading. syntax element.onloadeddata = handlerfunction; var handlerfunction = element.onloadeddata; handlerfunction is either null or a javascript function specifying the handler for the event. specification specification status comment html living standardthe definition of 'onloadeddata' in that specification. living standard ...
GlobalEventHandlers.onloadend - Web APIs
the onloadend property of the globaleventhandlers mixin is an eventhandler representing the code to be called when the loadend event is raised (when progress has stopped on the loading of a resource.) syntax img.onloadend = funcref; value funcref is the handler function to be called when the resource's loadend event fires. examples html content <img src="myimage.jpg"> javascript content // 'loadstart' fires first, then 'load', then 'loadend' image.addeventlistener('load', function(e) { console.log('image loaded'); }); image.addeventlistener('loadstart', function(e) { console.log('image load started'); }); image.addeventlistener('loadend', function(e) { console.log('image load finished'); }); ...
GlobalEventHandlers.onloadstart - Web APIs
the onloadstart property of the globaleventhandlers mixin is an eventhandler representing the code to be called when the loadstart event is raised (when progress has begun on the loading of a resource.) syntax img.onloadstart = funcref; value funcref is the handler function to be called when the resource's loadstart event fires. examples html content <img src="myimage.jpg"> javascript content // 'loadstart' fires first, then 'load', then 'loadend' image.addeventlistener('load', function(e) { console.log('image loaded'); }); image.addeventlistener('loadstart', function(e) { console.log('image load started'); }); image.addeventlistener('loadend', function(e) { console.log('image load finished'); }); specifications specification status comment html l...
GlobalEventHandlers - Web APIs
andlers.onloadeddata is an eventhandler representing the code to be called when the loadeddata event is raised. globaleventhandlers.onloadedmetadata is an eventhandler representing the code to be called when the loadedmetadata event is raised. globaleventhandlers.onloadend is an eventhandler representing the code to be called when the loadend event is raised (when progress has stopped on the loading of a resource.) globaleventhandlers.onloadstart is an eventhandler representing the code to be called when the loadstart event is raised (when progress has begun on the loading of a resource.) globaleventhandlers.onlostpointercapture is an eventhandler representing the code to be called when the lostpointercapture event type is raised. globaleventhandlers.onmousedown is an eventhandler repr...
HTMLAudioElement - Web APIs
properties no specific properties; inherits properties from its parent, htmlmediaelement, and from htmlelement. methods inherits methods from its parent, htmlmediaelement, and from htmlelement. it offers no methods of its own. obsolete mozilla-only methods the following methods are non-standard and should not be used. mozcurrentsampleoffs...
HTMLCanvasElement.mozGetAsFile() - Web APIs
is 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. function draw() { var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); ctx.fillstyle = 'rgb(200, 0, 0)'; ctx.fillrect(10, 10, 55, 50); ctx.fillstyle = 'rgba(0, 0, 200, 0.5)'; ctx.fillrect(30, 30, 55, 50); var link = document.getelementbyid(...
HTMLFormElement - Web APIs
specifications specification status comment html living standardthe definition of 'htmlformelement' in that specification. living standard the following method has been added: requestautocomplete(). html5the defin...
HTMLImageElement.decoding - Web APIs
the image synchronously for atomic presentation with other content. async: decode the image asynchronously to reduce delay in presenting other content. auto: default mode, which indicates no preference for the decoding mode. the browser decides what is best for the user. usage notes the decoding property allows you to control whether or not the browser is allowed to try to parallelize loading your image. if doing so would cause problems, you can specify sync to disable asynchronous loading. this can be useful when applied to <img> elements, but may be even more so when used for offscreen image objects. examples var img = new image(); img.decoding = 'sync'; img.src = 'img/logo.png'; specifications specification status comment html living standardthe def...
HTMLImageElement.lowSrc - Web APIs
this property reflects the html lowsrc attribute. syntax htmlimageelement.lowsrc = imageurl; imageurl = htmlimageelement.lowsrc; value a domstring specifying the url of a version of the image specified by src which has been modified in some fashion so that it loads significantly more quickly than the primary image. ...
HTMLImageElement.srcset - Web APIs
; 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. if you happen to have both standard and high density displays, try moving this window between them and reloading the page to see the results change. for additional examples, see our guide to responsive images. specifications specification status comment html living standardthe definition of 'htmlimageelement.srcset' in that specification. living standard browser compatibility the compatibility table on this page is generated from structured data. if you'd like...
HTMLImageElement - Web APIs
ap a boolean that reflects the ismap html attribute, indicating that the image is part of a server-side image map. this is different from a client-side image map, specified using an <img> element and a corresponding <map> which contains <area> elements indicating the clickable areas in the image. the image must be contained within an <a> element; see the ismap page for details. htmlimageelement.loading a domstring providing a hint to the browser used to optimize loading the document by determining whether to load the image immediately (eager) or on an as-needed basis (lazy). htmlimageelement.naturalheight read only returns an integer value representing the intrinsic height of the image in css pixels, if it is available; else, it shows 0. this is the height the image would be if it were rend...
HTMLLinkElement - Web APIs
ent.target is a domstring representing the name of the target frame to which the resource applies. methods no specific method; inherits methods from its parent, htmlelement, and linkstyle. specifications specification status comment preload candidate recommendation defines <link rel="preload">, and the as property. note that currently firefox only supports preloading of cacheable resources. html living standardthe definition of 'htmllinkelement' in that specification. living standard adds the following properties: crossorigin, referrerpolicy, and as. html 5.1the definition of 'htmllinkelement' in that specification. recommendation html5the definition of 'htmllinkelement' in that specification. recommendation the f...
HTMLMediaElement: abort event - Web APIs
the abort event is fired when the resource was not fully loaded, but not as the result of an error. ...
HTMLMediaElement: error event - Web APIs
ed when the resource could not be loaded due to an error (for example, a network connectivity problem). ...
HTMLMediaElement: loadeddata event - Web APIs
bubbles no cancelable no interface event target element default action none event handler property globaleventhandlers.onloadeddata specification html5 media note that this event will not fire in mobile/tablet devices if data-saver is on in browser settings. examples these examples add an event listener for the htmlmediaelement's loadeddata event, then post a message when that event handler has reacted to the event firing. ...
The HTML DOM API - Web APIs
he document interface is defined as part of the dom specification, the html specification significantly enhances it to add information specific to using the dom in the context of a web browser, as well as to using it to represent html documents specifically. among the things added to document by the html standard are: support for accessing various information provided by the http headers when loading the page, such as the location from which the document was loaded, cookies, modification date, referring site, and so forth. access to lists of elements in the document's <head> block and body, as well as lists of the images, links, scripts, etc. contained in the document. support for interacting with the user by examining focus and by executing commands on editable content. event handlers for...
IDBDatabase.close() - Web APIs
Web › API › IDBDatabase › close
te transactions throw an exception if a closing operation is pending. note: this feature is available in web workers. syntax idbdatabase.close(); example // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); // opening a database. // 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. db = dbopenrequest.result; // now let"s close the database again! db.close(); }; specification specification status comment indexed database api 2.0the definition of 'close()' in ...
IDBDatabase.createObjectStore() - Web APIs
/ this handler is called when a new version of the database // is created, either when one has not been created before // or when a new version number is submitted by calling // window.indexeddb.open(). // this handler is only supported in recent browsers. ...
IDBDatabase.name - Web APIs
Web › API › IDBDatabase › name
e object being stored in a db variable, and the name property then being logged. for a full example, see our to-do notifications app (view example live). // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); // these two event handlers act on the database being // opened successfully, or not 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. this is used a lot below db = dbopenrequest.result; // this line will log the name of the database, which should be "todolist" console.log(db.name); }; specifications specification status c...
IDBDatabase.objectStoreNames - Web APIs
[] = idbdatabase.objectstorenames; value a domstringlist containing a list of the names of the object stores currently in the connected database. example // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); // these two event handlers act on the database being opened successfully, or not 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. this is used a lot below db = dbopenrequest.result; // this line will log the version of the connected database, which should be // an object that looks like { ['my-store-name'] } console.log(db.objectsto...
IDBDatabase.version - Web APIs
is available in web workers. syntax var myinteger = idbdatabase.version; value an integer containing the version of the connected database. example // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); // these two event handlers act on the database // being opened successfully, or not 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. this is used a lot below db = dbopenrequest.result; // this line will log the version of the connected database, which should be "4" console.log(db.version); }; specifications specification st...
IDBFactory.open() - Web APIs
Web › API › IDBFactory › open
this is used a lot later on, for opening // transactions and suchlike. db = dbopenrequest.result; }; specifications specification status comment indexed database api 2.0the...
IDBFactory - Web APIs
this is used a lot later on, for opening transactions and suchlike. db = dbopenrequest.result; }; specifications specification status comment indexed database api 2.0the definition of 'idbfactory'...
IDBObjectStore - Web APIs
= dbopenrequest.result; }; // 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 dbopenrequest.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" }); // 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 });...
IDBRequest - Web APIs
s functions are included to handle the success and error cases. for a full working example, see our to-do notifications app (view example live.) var db; // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); // these two event handlers act on the database being // opened successfully, or not 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. db = dbopenrequest.result; }; specifications specification status comment indexed database api 2.0the definition of 'idbrequest' in that specification. recommendation initial definition. in...
IDBVersionChangeEvent.newVersion - Web APIs
// this is used a lot later on, for opening transactions and suchlike. db = dbopenrequest.result; }; specifications specification status comment indexed database api 2.0the defi...
IDBVersionChangeEvent - Web APIs
this is used a lot later on, for opening transactions and suchlike. db = dbopenrequest.result; }; specifications specification status comment indexed database api 2.0the definitio...
startSoftwareUpdate - Web APIs
method of installtrigger object syntax boolean startsoftwareupdate ( string url); parameters the startsoftwareupdate method has the following parameter: url a uniform resource locator specifying the location of the xpi file containing the software. returns true. description the startsoftwareupdate method triggers a software download and install from the specified url. this method has been largely superseded by newer install method, which is more flexible and allows you to install more than one xpi. note also that xpis installed with this method must have their own install.js files in which the full installation is defined. ...
InstallTrigger - Web APIs
...
Timing element visibility with the Intersection Observer API - Web APIs
set to the unique value nextarticleid (which starts at 1 and goes up for each article). then we create and append an <h2> element for the article title and then we append the html from contents to that. finally, nextarticleid is incremented (so that the next element gets a new unique id) and we return the new <article> element to the caller. creating an ad the loadrandomad() function simulates loading an ad and adding it to the page. if you don't pass a value for replacebox, a new element is created to contain the ad; the ad is then appended to the page. if you specify a replacebox, that box is treated as an existing ad element; instead of creating a new one, the existing element is changed to contain the new ad's style, content, and other data. this avoids the risk of lengthy layout work bein...
Key Values - Web APIs
appcommand_browser_refresh gdk_key_refresh (0x1008ff29) gdk_key_reload (0x1008ff73) "browsersearch" activates the user's preferred search engine or the search interface within their browser. vk_browser_search (0xaa) appcommand_browser_search gdk_key_search (0x1008ff1b) qt::key_search (0x01000092) keycode_search (84) "browserstop" stops loading the currently displayed web view or content. vk_browser_stop (0xa9) appcommand_browser_stop gdk_key_stop (0x1008ff28) qt::key_search (0x01000063) [1] prior to firefox 37, this key's value was reported as "unidentified". numeric keypad keys these keys are found on the keyboard's numeric keypad. however, not all are present on every keyboard. although typical numeric ...
MediaImage - Web APIs
deo or audio track. properties src the url from which user agent can fetch the image's data. sizes specifies the resource in multiple sizes so that user agent does not have to scale a single image. type the mime type hint for the user agant. note that it is just a hint so that user agent may ignore images of types it does not support; user agent still may use mime type sniffing after downloading the image to determine its type. specifications specification status comment media session standardthe definition of 'mediaimage' in that specification. draft initial definition. ...
load() - Web APIs
syntax mediakeysession.load(sessionid).then(function(booleanvalue) { ... }); parameter sessionid a unique string generated by the content decription module for the current media object and its associated keys or licenses. return value a promise that resolves to a boolean indicating whether the load succeeded or failed. ...
MediaKeySession - Web APIs
mediakeysession.close() returns a promise after notifying the current media session is no longer needed and that the cdm should release any resources associated with this object and close it. mediakeysession.generaterequest() returns a promise after generating a media request based on initialization data. mediakeysession.load() returns a promise that resolves to a boolean value after loading data for a specified session object. mediakeysession.remove() returns a promise after removing any session data associated with the current object. mediakeysession.update() returns a promise after loading messages and licenses to the cdm. examples // tbd specifications specification status comment encrypted media extensionsthe definition of 'mediakeysession' in t...
Recording a media element - Web APIs
> download </a> </div> on the right we see a stop button and the <video> element which will be used to play back the recorded video. notice that the playback panel doesn't have autoplay set (so the playback doesn't start as soon as media arrives), and it has controls set, which tells it to show the user controls to play, pause, and so forth. below the playback element is a button for downloading the recorded video. <div class="bottom"> <pre id="log"></pre> </div> css content body { font: 14px "open sans", "arial", sans-serif; } video { margin-top: 2px; border: 1px solid black; } .button { cursor: pointer; display: block; width: 160px; border: 1px solid black; font-size: 16px; text-align: center; padding-top: 2px; padding-bottom: 4px; color: white; backgro...
Navigation Timing API - Web APIs
the request was initiated (requeststart). from the time at which the response was finished being received (responseend). calculate page render time as another example of an interesting piece of data you can obtain using the navigation timing api that you can't otherwise easily get, you can get the amount of time it took to render the page: const rendertime = perfdata.domcomplete - perfdata.domloading; this is obtained by starting with the time at which loading of the dom and its dependencies is complete (domcomplete) and subtracting from it the time at which parsing of the dom began (domloading). specifications specification status comment navigation timing level 2 working draft adds performancenavigationtiming navigation timing recommendation ...
Network Information API - Web APIs
changed from " + type + " to " + connection.effectivetype); type = connection.effectivetype; } connection.addeventlistener('change', updateconnectionstatus); preload large resources the connection object is useful for deciding whether to preload resources that take large amounts of bandwidth or memory. this example would be called soon after page load to check for a connection type where preloading a video may not be desirable. if a cellular connection is found, then the preloadvideo flag is set to false. for simplicity and clarity, this example only tests for one connection type. a real-world use case would likely use a switch statement or some other method to check all of the possible values of networkinformation.type. regardless of the type value you can get an estimate of connection spe...
PageTransitionEvent.persisted - Web APIs
syntax window.addeventlistener('pageshow', function(event) { if (event.persisted) { console.log('page was loaded from cache.'); } }); value a boolean. ...
PageTransitionEvent - Web APIs
211" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">pagetransitionevent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface also inherits properties from its parent, event. pagetransitionevent.persisted read only indicates if the document is loading from a cache. example html <!doctype html> <html> <body> </body> </html> javascript window.addeventlistener('pageshow', myfunction); function myfunction(event) { if (event.persisted) { alert("the page was cached by the browser"); } else { alert("the page was not cached by the browser"); } } specifications specification status comment html livin...
Using the Payment Request API - Web APIs
the following snippet we do just this — depending on whether the user can make a fast payment or needs to add payment credentials first, the title of the checkout button changes between "fast checkout with w3c" and "setup w3c checkout". in both cases, the checkout button calls paymentrequest.show(). ...
performance.clearResourceTimings() - Web APIs
d return value none this method has no return value. ...
PerformanceEntry - Web APIs
the performanceentry object encapsulates a single performance metric that is part of the performance timeline. 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). performanceentry instances will always be one of the following subtypes: performancemark performancemeasure performanceframetiming performancenavigationtiming performanceresourcetiming performancepainttiming note: this feature is available in web workers. properties performanceentry.name read only a value that further specifies the value returned by the performanceentry.entrytype property. the value of both...
PerformanceResourceTiming - Web APIs
the performanceresourcetiming interface enables retrieval and analysis of detailed network timing data regarding the loading of an application's resources. an application can use the timing metrics to determine, for example, the length of time it takes to fetch a specific resource, such as an xmlhttprequest, <svg>, image, or script. 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.. additionally, the interface extends performanceentry with other properties which provide data about the size of the fetched resource as well as the type of resource that initiated the fetch. <div id="interfacediagram" style="display:...
PerformanceTiming.domInteractive - Web APIs
nterface instead. the legacy performancetiming.dominteractive read-only property returns an unsigned long long representing the moment, in miliseconds since the unix epoch, when the parser finished its work on the main document, that is when its document.readystate changes to 'interactive' and the corresponding readystatechange event is thrown. this property can be used to measure the speed of loading web sites that users feels. nevertheless there are a few caveats that happens if scripts are blocking rendering and not loaded asynchronously or with custom web fonts. check if you are in one of these cases before using this property as a proxy for the user experience of a web site's speed of loading. syntax time = performancetiming.dominteractive; specifications specification sta...
Performance API - Web APIs
or metrics regarding the browser's document navigation events. performanceobserver provides methods and properties used to observe performance measurement events and be notified of new performance entries as they are recorded in the browser's performance timeline. performanceresourcetiming provides methods and properties for retrieving and analyzing detailed network timing data regarding the loading of an application's resources. specifications specification status comment high resolution time recommendation initial definition. high resolution time level 2 recommendation adds performance attribute on window and workerglobalscope. high resolution time level 3 editor's draft add timeorigin property to performance interface. ...
PluginArray - Web APIs
es of pluginarray objects are no longer enumerable in the latest browser versions. properties pluginarray.lengthread only the number of plugins in the array. methods pluginarray.item returns the plugin at the specified index into the array. pluginarray.nameditem returns the plugin with the specified name. pluginarray.refresh refreshes all plugins on the current page, optionally reloading documents. examples the following example function returns the version of the shockwave flash plugin. var pluginslength = navigator.plugins.length; document.body.innerhtml = pluginslength + " plugin(s)<br>" + '<table id="plugintable"><thead>' +'<tr><th>name</th><th>filename</th><th>description</th><th>version</th></tr>' +'</thead><tbody></tbody></table>'; var table = document.geteleme...
ProgressEvent() - Web APIs
total work to be done, and the amount of work already done, by the underlying process is calculable. in other words, it tells if the progress is measurable or not. it defaults to false. loaded optional is an unsigned long long representing the amount of work already performed by the underlying process. the ratio of work done can be calculated with the property and progressevent.total. when downloading a resource using http, this only represent the part of the content itself, not headers and other overhead. it defaults to 0. total optional is an unsigned long long representing the total amount of work that the underlying process is in the progress of performing. when downloading a resource using http, this only represent the content itself, not headers and other overhead. it defaults to 0. ...
ProgressEvent.initProgressEvent() - Web APIs
boolean flag indicating if the total work to be done, and the amount of work already done, by the underlying process is calculable. in other words, it tells if the progress is measurable or not. loaded is an unsigned long long representing the amount of work already performed by the underlying process. the ratio of work done can be calculated with the property and progressevent.total. when downloading a resource using http, this only represent the part of the content itself, not headers and other overhead. total is an unsigned long long representing the total amount of work that the underlying process is in the progress of performing. when downloading a resource using http, this only represent the content itself, not headers and other overhead. specifications this feature does not exist i...
ProgressEvent.loaded - Web APIs
the progressevent.loaded read-only property is an integer representing the amount of work already performed by the underlying process. the ratio of work done can be calculated with the property and progressevent.total. when downloading a resource using http, this only represent the part of the content itself, not headers and other overhead. syntax value = progressevent.loaded specifications specification status comment xmlhttprequestthe definition of 'progressevent.loaded' in that specification. living standard ...
ProgressEvent.total - Web APIs
the progressevent.total read-only property is an integer representing the total amount of work that the underlying process is in the progress of performing. when downloading a resource using http, this only represent the content itself, not headers and other overhead. syntax value = progressevent.total specifications specification status comment xmlhttprequestthe definition of 'progressevent.lengthcomputable' in that specification. living standard ...
SVGElement: abort event - Web APIs
this basically implements the standard abort dom event. ...
SVGElement - Web APIs
this interface has no methods, but inherits methods from: documentandelementeventhandlers, element, elementcssinlinestyle, globaleventhandlers, htmlorforeignelement, svgelementinstance events listen to these events using addeventlistener() or by assigning an event listener to the equivalent on... handler property defined on globaleventhandlers or windoweventhandlers. abort fired when page loading is stopped before an svg element has been allowed to load completely. also available via the onabort property. error fired when an svg element does not load properly or when an error occurs during script execution. also available via the onerror property. load fires on an svgelement when it is loaded in the browser. also available via the onload property. resize fired when an svg documen...
ServiceWorkerContainer - Web APIs
iceworkercontainer in an array. the method returns a promise that resolves to an array of serviceworkerregistration. serviceworkercontainer.startmessages() explicitly starts the flow of messages being dispatched from a service worker to pages under its control (e.g. sent via client.postmessage()). this can be used to react to sent messages earlier, even before that page's content has finished loading. examples the example below first checks to see if the browser supports service workers. if supported, the code registers the service worker and determines if the page is actively controlled by the service worker. if it isn't, it prompts the user to reload the page so the service worker can take control. the code also reports any registration failures. if ('serviceworker' in navigator) { //...
Using Service Workers - Web APIs
chain a success case onto our promise structure. when the promise resolves successfully, the code inside it executes. finally, we chain a .catch() function onto the end that will run if the promise is rejected. this registers a service worker, which runs in a worker context, and therefore has no dom access. you then run code in the service worker outside of your normal pages to control their loading. a single service worker can control many pages. each time a page within your scope is loaded, the service worker is installed against that page and operates on it. bear in mind therefore that you need to be careful with global variables in the service worker script: each page doesn’t get its own unique worker. note: your service worker functions like a proxy server, allowing you to modify...
Service Worker API - Web APIs
controlled page. installevent the parameter passed into the oninstall handler, the installevent interface represents an install action that is dispatched on the serviceworkerglobalscope of a serviceworker. as a child of extendableevent, it ensures that functional events such as fetchevent are not dispatched during installation. navigationpreloadmanager provides methods for managing the preloading of resources with a service worker. navigator.serviceworker returns a serviceworkercontainer object, which provides access to registration, removal, upgrade, and communication with the serviceworker objects for the associated document. notificationevent the parameter passed into the onnotificationclick handler, the notificationevent interface represents a notification click event that is di...
Storage Access API - Web APIs
s policies implemented in the two browsers. design properties unique to firefox are summarized here: if the embedded origin tracker.example has already obtained first-party storage access on the top-level origin foo.example, and the user visits a page from foo.example embedding a page from tracker.example again in less than 30 days, the embedded origin will have storage access immediately when loading. if a page from top-level origin foo.example embeds more than one <iframe> from tracker.example, and one of those <iframe>s uses the storage access api in order to obtain storage access successfully, all other iframes from tracker.example on foo.example top-level origins will immediately gain storage access as well, without needing to call requeststorageaccess() separately. if an embedded page ...
TextTrack.mode - Web APIs
Web › API › TextTrack › mode
e resource fetch and memory usage are avoided unless the cues are actually needed. however, that means that if you wish to perform any actions involving the track's cues while handling, for example, the load event—in order to process some aspect of the cues upon page load—and the track mode was initially disabled, you'll have to change the mode to either hidden or showing in order to trigger loading of the cues. when the mode is showing, text tracks are performed. the exact appearance and manner of that performance varies depending on each text track's kind. in general: tracks whose kind is "subtitles" or "captions" are rendered with the cues overlaid over the top of the video. tracks whose kind is "descriptions" are presented in a non-visual form (for example, the text might be spoken ...
TimeRanges - Web APIs
a timeranges object includes one or more ranges of time, each specified by a starting and ending time offset. you reference each time range by using the start() and end() methods, passing the index number of the time range you want to retrieve. the term "normalized timeranges object" indicates that ranges in such an object are ordered, don't overlap, aren't empty, and don't touch (adjacent ranges are folded into one bigger range). ...
TransformStream - Web APIs
options} super(t) _jstes_wm.set(this, t) } get encoding() {return _jstds_wm.get(this).decoder.encoding} get fatal() {return _jstds_wm.get(this).decoder.fatal} get ignorebom() {return _jstds_wm.get(this).decoder.ignorebom} } chaining multiple readablestreams together this is a useful one, where multiple streams can be conjoined. examples include building a pwa with progressive loading and progressive streaming. let responses = [ /* conjoined response tree */ ] let {readable, writable} = new transformstream responses.reduce( (a, res, i, arr) => a.then(() => res.pipeto(writable, {preventclose: (i+1) !== arr.length})), promise.resolve() ) note that this is not resilient to other influences. specifications specification status comment streamsthe d...
URL API - Web APIs
Web › API › URL API
for instance, try https://url-api.glitch.me?from=mdn&excitement=high&likelihood=inconceivable. specifications specification status comment url living standard whatwg specification ...
USBDevice.deviceClass - Web APIs
the other two properties are usbdevice.devicesubclass and usbdevice.deviceprotocol. syntax var number = usbdevice.deviceclass value a number. ...
USBDevice.deviceClass - Web APIs
the other two properties are usbdevice.devicesubclass and usbdevice.deviceprotocol. syntax var number = usbdevice.deviceclass value a number. ...
USBDevice.deviceProtocol - Web APIs
the other two properties are usbdevice.deviceclass and usbdevice.devicesubclass. syntax var number = usbdevice.deviceprotocol value a number. ...
USBDevice.deviceSubclass - Web APIs
the other two properties are usbdevice.deviceclass and usbdevice.deviceprotocol. syntax var serialnumber = usbdevice.devicesubclass value a number. ...
Animating textures in WebGL - Web APIs
rst we create a video element. we set it to autoplay, mute the sound, and loop the video. we then set up two events to make sure the video is playing and the time has been updated. we need both of these checks because it will produce an error if you upload a video to webgl that has no data available yet. checking for both of these events guarantees there is data available and it's safe to start uploading video to a webgl texture. in the code above, we confirm whether we got both of those events; if so, we set a global variable, copyvideo, to true to indicate that it's safe to start copying the video to a texture. and finally, we set the src attribute to start and call play to start loading and playing the video. the video must be loaded from a secure source in order to be used to provide textur...
Movement, orientation, and motion: A WebXR example - Web APIs
omputes the position of each vertex given the initial positions of each vertex and the transforms that need to be applied to convert them to simulate the viewer's current position and orientation. the fragment shader returns the color of each vertex, interpolating as needed from the values found in the texture and applying the lighting effects. starting up and shutting down webxr upon initially loading the script, we install a handler for the load event, so that we can perform initialization. window.addeventlistener("load", onload); function onload() { xrbutton = document.queryselector("#enter-xr"); xrbutton.addeventlistener("click", onxrbuttonclick); projectionmatrixout = document.queryselector("#projection-matrix div"); modelmatrixout = document.queryselector("#model-view-matrix di...
Web Audio API best practices - Web APIs
there's no strict right or wrong way when writing creative code. as long as you consider security, performance, and accessibility, you can adapt to your own style. in this article, we'll share a number of best practices — guidelines, tips, and tricks for working with the web audio api. loading sounds/files there are four main ways to load sound with the web audio api and it can be a little confusing as to which one you should use. when working with files, you are looking at either the grabbing the file from an htmlmediaelement (i.e. an <audio> or <video> element), or you're looking to fetch the file and decode it into a buffer. both are legitimate ways of working, however, it's more common to use the former when you are working with full-length tracks, and the latter when working with short...
Background audio processing using AudioWorklet - Web APIs
new audio worklet processor class by calling registerprocessor(), specifying a name for the audio processor and the class that defines the processor. a single audio worklet processor module may define multiple processor classes, registering each of them with individual calls to registerprocessor(). as long as each has its own unique name, this will work just fine. it's also more efficient than loading multiple modules from over the network or even the user's local disk. basic code framework the barest framework of an audio processor class looks like this: class myaudioprocessor extends audioworkletprocessor { constructor() { super(); } process(inputlist, outputlist, parameters) { /* using the inputs (or not, as needed), write the output into each of the outputs */ ...
Window: DOMContentLoaded event - Web APIs
bubbles yes cancelable yes (although specified as a simple event that isn't cancelable) interface event event handler property none the original target for this event is the document that has loaded. you can listen for this event on the window interface to handle it in the capture or bubbling phases. for full details on this event please see the page on the document: domcontentloaded event. ...
Window.console - Web APIs
Web › API › Window › console
the window.console property returns a reference to the console object, which provides methods for logging information to the browser's console. these methods are intended for debugging purposes only and should not be relied on for presenting information to end users. examples logging to console the first example logs text to the console. console.log("an error occurred while loading the content"); the next example logs an object to the console, with the object's fields expandable using disclosure widgets: console.dir(someobject); see usage in console for more thorough examples. specifications specification status comment console api living standard initial definition. currently there are many implementation differences among browsers, but work i...
window.location - Web APIs
Web › API › Window › location
dow/location" example #1: navigate to a new page whenever a new value is assigned to the location object, a document will be loaded using the url as if location.assign() had been called with the modified url. note that security settings, like cors, may prevent this to effectively happen. ...
Window.ondragdrop - Web APIs
Web › API › Window › ondragdrop
mented in gecko (bug 112288), you have to use addeventlistener. see addeventlistener for details. example fire an alert on dragdrop in this example, an event listener is added to the window (the event target). if, from an external source, a tab, a link, marked text or a file is dragged and dropped onto this window, the alert is fired. note how event.stoppropagation(); prevents the browser from loading the dropped tab, link or file. <html> <head><title>dragdroptest</title> <script type="text/javascript"> window.addeventlistener("dragdrop", testfunc, false); function testfunc(event) { alert("dragdrop!"); event.stoppropagation(); } </script> </head> <body> i am bodytext </body> </html> specification not part of specification. ...
Window.open() - Web APIs
Web › API › Window › open
in the new window. if url is an empty string, then a new blank, empty window (url about:blank) is created with the default toolbars of the main window. note that remote urls won't load immediately. when window.open() returns, the window always contains about:blank. the actual fetching of the url is deferred and starts after the current script block finishes executing. the window creation and the loading of the referenced resource are done asynchronously. examples var windowobjectreference; var windowfeatures = "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes"; function openrequestedpopup() { windowobjectreference = window.open("http://www.cnn.com/", "cnn_windowname", windowfeatures); } var windowobjectreference; function openrequestedpopup() { windowobjectreference = wi...
Window.stop() - Web APIs
Web › API › Window › stop
syntax window.stop() example window.stop(); specification specification status comment html living standardthe definition of 'window.stop()' in that specification. living standard html5the definition of 'window.stop' in that specification. recommendation browser compatibility the compatibility table in this page is generated from structured data. ...
Window: unload event - Web APIs
examples <!doctype html> <html> <head> <title>parent frame</title> <script> window.addeventlistener('beforeunload', function(event) { console.log('i am the 1st one.'); }); window.addeventlistener('unload',...
WindowClient - Web APIs
methods windowclient inherits methods from its parent interface, client. windowclient.focus() gives user input focus to the current client. windowclient.navigate() loads a specified url into a controlled client page. ...
WindowEventHandlers.onbeforeunload - Web APIs
beforeunload event handlers unless the page has been interacted with. moreover, some don't display them at all. syntax window.addeventlistener("beforeunload", function(event) { ... }); window.onbeforeunload = function(event) { ... }; typically, it is better to use window.addeventlistener() and the beforeunload event, instead of onbeforeunload. example this example prompts the user before unloading. the html specification states that authors should use the event.preventdefault() method instead of using event.returnvalue to prompt the user. window.addeventlistener('beforeunload', function (e) { // cancel the event e.preventdefault(); // if you prevent default behavior in mozilla firefox prompt will always be shown // chrome requires returnvalue to be set e.returnvalue = ''; }); g...
WindowEventHandlers.onunload - Web APIs
the resource removal is processed after the unload event occurs. note: browsers equipped with pop-up blockers will ignore all window.open() method calls in onunload event handler functions. syntax window.addeventlistener("unload", function(event) { ... }); window.onunload = function(event) { ... }; typically, it is better to use window.addeventlistener() and the unload event, instead of onunload. ...
WindowOrWorkerGlobalScope.setTimeout() - Web APIs
d with a delay of zero, it's placed on a queue and scheduled to run at the next opportunity; not immediately. currently-executing code must complete before functions on the queue are executed, thus the resulting execution order may not be as expected. deferral of timeouts during pageload starting in firefox 66, firefox will defer firing settimeout and setinterval timers while the current tab is loading. firing is deferred until the mainthread is deemed idle (similar to window.requestidlecallback()), or until the load event is fired. maximum delay value browsers including internet explorer, chrome, safari, and firefox store the delay as a 32-bit signed integer internally. this causes an integer overflow when using delays larger than 2,147,483,647 ms (about 24.8 days), resulting in the timeou...
Worklet.addModule() - Web APIs
Web › API › Worklet › addModule
syntax addpromise = worklet.addmodule(moduleurl); addpromise = worklet.addmodule(moduleurl, options); parameters moduleurl a string containing the url of a javascript file with the module to add. options optional an object with any of the following options: credentials: a requestcredentials value that indicates whether to send credentials (e.g. cookies and http authentification) when loading the module. can be one of "omit", "same-origin", or "include". defaults to "same-origin". see also request.credentials. return value a promise that resolves once the module from the given url has been added. the promise doesn't return any value. exceptions if addmodule() fails, it rejects the promise, delivering one of the following errors to the rejection handler. aborterror the spe...
Synchronous and asynchronous requests - Web APIs
der using the fetch() api with the keepalive flag. when fetch with keepalive isn't available, you can consider using the navigator.sendbeacon() api, which can support these use cases while typically delivering a good ux. the following example shows theoretical analytics code that attempts to submit data to a server by using a synchronous xmlhttprequest in an unload handler. this results in the unloading of the page to be delayed. window.addeventlistener('unload', logdata, false); function logdata() { var client = new xmlhttprequest(); client.open("post", "/log", false); // third parameter indicates sync xhr. :( client.setrequestheader("content-type", "text/plain;charset=utf-8"); client.send(analyticsdata); } using the sendbeacon() method, the data will be transmitted asynchro...
Using XMLHttpRequest - Web APIs
", loadend); function loadend(e) { console.log("the transfer finished (although we don't know if it succeeded or not)."); } note there is no way to be certain, from the information received by the loadend event, as to which condition caused the operation to terminate; however, you can use this to handle tasks that need to be performed in all end-of-transfer scenarios. submitting forms and uploading files instances of xmlhttprequest can be used to submit forms in two ways: using only ajax using the formdata api using the formdata api is the simplest and fastest, but has the disadvantage that data collected can not be stringified. using only ajax is more complex, but typically more flexible and powerful. using nothing but xmlhttprequest submitting forms without the formdata api does...
XMLHttpRequest.abort() - Web APIs
the xmlhttprequest.abort() method aborts the request if it has already been sent. when a request is aborted, its readystate is changed to xmlhttprequest.unsent (0) and the request's status code is set to 0. syntax xmlhttprequest.abort() parameters none. return value undefined example this example begins loading content from the mdn home page, then due to some condition, aborts the transfer by calling abort(). var xhr = new xmlhttprequest(), method = "get", url = "https://developer.mozilla.org/"; xhr.open(method, url, true); xhr.send(); if (oh_noes_we_need_to_cancel_right_now_or_else) { xhr.abort(); } specifications specification status comment xmlhttprequest living standard whatwg living standard ...
XMLHttpRequest.response - Web APIs
setting the value of responsetype after calling open() to initialize the request but before calling send() to send the request to the server. the value is null if the request is not yet complete or was unsuccessful, with the exception that when reading text data using a responsetype of "text" or the empty string (""), the response can contain the response so far while the request is still in the loading readystate (3). the response types are described below. "" an empty responsetype string is treated the same as "text", the default type. arraybuffer the response is a javascript arraybuffer containing binary data. blob the response is a blob object containing the binary data. document the response is an html document or xml xmldocument, as appropriate based on the mime type of the rece...
XMLHttpRequestEventTarget - Web APIs
ains the function to call when a request encounters an error and the error event is received by this object. xmlhttprequesteventtarget.onload contains the function to call when an http request returns after successfully fetching content and the load event is received by this object. xmlhttprequesteventtarget.onloadstart contains the function that gets called when the http request first begins loading data and the loadstart event is received by this object. xmlhttprequesteventtarget.onprogress contains the function that is called periodically with information about the progress of the request and the progress event is received by this object. xmlhttprequesteventtarget.ontimeout contains the function that is called if the event times out and the timeout event is received by this object; thi...
XRSession.requestAnimationFrame() - Web APIs
questanimationframe(onwindowanimationframe) // this may be called while an immersive session is running on some devices, // such as a desktop with a tethered headset. to prevent two loops from // rendering in parallel, skip drawing in this one until the session ends. if (!xrsession) { renderframe(time, null) } } // the window animation loop can be started immediately upon the page loading. window.requestanimationframe(onwindowanimationframe) function onxranimationframe(time, xrframe) { xrsession.requestanimationframe(onxranimationframe) renderframe(time, xrframe) } function renderframe(time, xrframe) { // shared rendering logic. } // assumed to be called by a user gesture event elsewhere in code. function startxrsession() { navigator.xr.requestsession('immersive-vr').th...
XSLTProcessor - Web APIs
s the following properties are [chromeonly] and not exposed to web content: [chromeonly] attribute unsigned long xsltprocessor.flags flags that tweak the behavior of the processor. not reset by calling xsltprocessor.reset(). default value: 0 possible values are: name value effect (none) 0 none disable_all_loads 1 disable loading external documents (via e.g. <xsl:import> and document()) examples basic example advanced example additional example specifications not part of any specification. this is a proprietary interface that originated in gecko. gecko idl xsltprocessor.webidl nsixsltprocessor.idl ...
Web APIs
Web › API
of all the apis and interfaces (object types) that you may be able to use while developing your web app or site. web apis are typically used with javascript, although this doesn't always have to be the case. specifications this is a list of all the apis that are available. ...
Using the alert role - Accessibility
that an alert occurred and what the alert text was. note: opinons may differ on how assistive technology should handle this technique. the information provided above is one of those opinions and therefore not normative. examples example 1: adding the role in the html code the snippet below shows how the alert role is added directly into the html source code. the moment the element finishes loading the screen reader should be notified of the alert. if the element was already in the original source code when the page loaded, the screen reader will announce the error immediately after announcing the page title. <h2 role="alert">your form could not be submitted because of 3 validation errors.</h2> example 2: dynamically adding an element with the alert role this snippet dynamically creates ...
Using the progressbar role - Accessibility
determined, the developer has to indicate this progress using the aria-valuenow, aria-valuemin, and aria-valuemax attributes. if the progress value is indeterminate, the developer should omit the aria-valuenow attribute. as the task progresses, the aria-valuenow value has to be updated dynamically to indicate this progress to assistive technology products. if the progressbar is describing the loading progress of a particular region of a page, the author should use aria-describedby to point to the status, and set the aria-busy attribute to true on the region until it is finished loading. it is not possible for the user to alter the value of a progressbar because it is always readonly. note: assistive technologies generally will render the value of aria-valuenow as a percent of the range betwe...
ARIA: application role - Accessibility
sing on their end. if the web application encompassed by the application role contains parts that should be treated like normal web content, a role of document or article should be used. background for historic reasons, especially on windows, screen readers and some other assistive technologies (at) have traditionally grabbed the whole web content from the browser at once after it had finished loading. the ats build their own representation of it that makes the most sense for a blind user to consume the content. this is often referred to as virtual document, browse mode, or similar terms. the document is streamlined to a single-column view. a keyboard interaction model is generated that is very similar to a word processor where users can read line by line, sentence by sentence, or paragraph by...
WAI-ARIA Roles - Accessibility
des to use the document mode to read the content contained within this element.aria: feed rolea feed is a dynamic scrollable list of articles in which articles are added to or removed from either end of the list as the user scrolls. a feed enables screen readers to use the browse mode reading cursor to both read and scroll through a stream of rich content that may continue scrolling infinitely by loading more content as the user reads.aria: figure rolethe aria figure role can be used to identify a figure inside page content where appropriate semantics do not already exist. a figure is generally considered to be one or more images, code snippets, or other content that puts across information in a different way to a regular flow of text.aria: form rolethe form landmark role can be used to identify ...
Accessibility documentation index - Accessibility
within this element. 61 aria: feed role aria, aria role, reference, feed a feed is a dynamic scrollable list of articles in which articles are added to or removed from either end of the list as the user scrolls. a feed enables screen readers to use the browse mode reading cursor to both read and scroll through a stream of rich content that may continue scrolling infinitely by loading more content as the user reads. 62 aria: figure role aria, aria role, aria figure, accessibility, reference, rôle, figure the aria figure role can be used to identify a figure inside page content where appropriate semantics do not already exist. a figure is generally considered to be one or more images, code snippets, or other content that puts across information in a differ...
:-moz-suppressed - CSS: Cascading Style Sheets
note: this selector is mainly intended to be used by theme developers. ...
:disabled - CSS: Cascading Style Sheets
Web › CSS › :disabled
checkbox">same as shipping address:</label> <input type="checkbox" id="billing-checkbox" checked> <br> <input type="text" placeholder="name" disabled> <input type="text" placeholder="address" disabled> <input type="text" placeholder="zip code" disabled> </fieldset> </form> css input[type="text"]:disabled { background: #ccc; } javascript // wait for the page to finish loading document.addeventlistener('domcontentloaded', function () { // attach `change` event listener to checkbox document.getelementbyid('billing-checkbox').onchange = togglebilling; }, false); function togglebilling() { // select the billing text fields var billingitems = document.queryselectorall('#billing input[type="text"]'); // toggle the billing text fields for (var i = 0; i < billin...
src - CSS: Cascading Style Sheets
Web › CSS › @font-face › src
e"); values <url> [ format( <string># ) ]? specifies an external reference consisting of a <url>, followed by an optional hint using the format() function to describe the format of the font resource referenced by that url. the format hint contains a comma-separated list of format strings that denote well-known font formats. if a user agent doesn't support the specified formats, it skips downloading the font resource. if no format hints are supplied, the font resource is always downloaded. <font-face-name> specifies the name of a locally-installed font face using the local() function, which uniquely identifies a single font face within a larger family. the name can optionally be enclosed in quotes. description the value of this descriptor is a prioritized, comma-separated list of extern...
@font-face - CSS: Cascading Style Sheets
re considered to be universally available). the ability to specify the name of a locally-installed font to look for and use makes it possible to customize the font beyond the basics while making it possible to do so without relying on an internet connection. it's common to use both url() and local() together, so that the user's installed copy of the font is used if available, falling back to downloading a copy of the font if it's not found on the user's device. the @font-face at-rule may be used not only at the top level of a css, but also inside any css conditional-group at-rule. font mime types format mime type truetype font/ttf opentype font/otf web open font format font/woff web open font format 2 font/woff2 notes w...
Using URL values for the cursor property - CSS: Cascading Style Sheets
ax the basic (css 2.1) syntax for this property is: cursor: [ <url> , ]* <keyword> this means that zero or more urls may be specified (comma-separated), which must be followed by one of the keywords defined in the css specification, such as auto or pointer. for example, the following value would be allowed: cursor: url(foo.cur), url(http://www.example.com/bar.gif), auto; this will first try loading foo.cur. if that file does not exist or is not valid for some other reason, bar.gif is tried, and if that can't be used either, auto will be used. support for the css 3 syntax for cursor values got added in gecko 1.8 (firefox 1.5): cursor: [ <uri> [ <x> <y> ]? , ]* <keyword> it allows specifying the coordinates of the cursor's hotspot, which will be clamped to the boundaries of the cursor ima...
Variable fonts guide - CSS: Cascading Style Sheets
nging the text grade doesn't change the overall layout of the text or elements around it. this makes grade a useful axis of variation as it can be varied or animated without causing reflow of the text itself. font-variation-settings: 'grad' 88; the following live example's css can be edited to allow you to play with font grade values. using a variable font: @font-face changes the syntax for loading variable fonts is very similar to any other web font, with a few notable differences, which are provided via upgrades to the traditional @font-face syntax now available in modern browsers. the basic syntax is the same, but the font technology can be specified, and allowable ranges for descriptors like font-weight and font-stretch can be supplied, rather than named according to the font file bein...
Consistent list indentation - CSS: Cascading Style Sheets
internet explorer and opera, the lists are indented by setting a left margin of 40 pixels on the <ul> element. if we apply a background color to the <ul> element and leave the list item and <ul> borders in place, we get the result shown in figure 5. gecko, on the other hand, sets a left padding of 40 pixels for the <ul> element, so given the exact same styles as were used to produce figure 5, loading the example into a gecko-based browser gives us figure 6. as we can see, the markers remain attached to the <li> elements, no matter where they are. the difference is entirely in how the <ul> is styled. we can only see the difference if we try to set a background or border on the <ul> element. finding consistency boil it all down, and what we're left with is this: if you want consistent rend...
Mozilla CSS extensions - CSS: Cascading Style Sheets
and :visited] :-moz-broken ::-moz-canvas ::-moz-color-swatch ::-moz-cell-content :-moz-drag-over f – i :-moz-first-node ::-moz-focus-inner ::-moz-focus-outer :-moz-focusring :-moz-full-screen :-moz-full-screen-ancestor :-moz-handler-blocked :-moz-handler-crashed :-moz-handler-disabled ::-moz-inline-table l :-moz-last-node :-moz-list-bullet :-moz-list-number :-moz-loading :-moz-locale-dir(ltr) :-moz-locale-dir(rtl) :-moz-lwtheme :-moz-lwtheme-brighttext :-moz-lwtheme-darktext n – r :-moz-native-anonymous :-moz-only-whitespace ::-moz-page ::-moz-page-sequence ::-moz-pagebreak ::-moz-pagecontent :-moz-placeholderobsolete since gecko 51 ::-moz-placeholderdeprecated since gecko 51 ::-moz-progress-bar ::-moz-range-progress ::-moz-range-thumb ::...
Ajax - Developer guides
Web › Guide › AJAX
n itself, is a term coined in 2005 by jesse james garrett, that describes a "new" approach to using a number of existing technologies together, including html or xhtml, css, javascript, dom, xml, xslt, and most importantly the xmlhttprequest object. when these technologies are combined in the ajax model, web applications are able to make quick, incremental updates to the user interface without reloading the entire browser page. this makes the application faster and more responsive to user actions. although x in ajax stands for xml, json is used more than xml nowadays because of its many advantages such as being lighter and a part of javascript. both json and xml are used for packaging information in the ajax model. documentation getting started this article guides you through the ajax b...
Guide to Web APIs - Developer guides
Web › Guide › API
t to build increasingly more powerful and capable applications, running either on the web, locally, or through technology such as node.js, on a server. on this page you'll find a complete list of all of the apis provided by the full web technology stack. ...
Live streaming web audio and video - Developer guides
ck here --> </video> media source extensions (mse) media source extensions is a w3c working draft that plans to extend htmlmediaelement to allow javascript to generate media streams for playback. allowing javascript to generate streams facilitates a variety of use cases like adaptive streaming and time shifting live streams. for example, you could implement mpeg-dash using javascript while offloading the decoding to mse. note: time shifting is the process of consuming a live stream sometime after it happened. video streaming file formats a couple of http-based live streaming video formats are beginning to see support across browsers. note: you can find a guide to encoding hls and mpeg-dash for use on the web at setting up adaptive streaming media sources. mpeg-dash dash stands for d...
Audio and Video Delivery - Developer guides
entlistener('click', function() { switchstate(); }, false); window.addeventlistener( "keypress", checkkey, false ); } you can try this example out here. for more information, see creating your own custom audio player. other tips for audio/video stopping the download of media while stopping the playback of media is as easy as calling the element's pause() method, the browser keeps downloading the media until the media element is disposed of through garbage collection. here's a trick that stops the download at once: var mediaelement = document.queryselector("#mymediaelementid"); mediaelement.removeattribute("src"); mediaelement.load(); by removing the media element's src attribute and invoking the load() method, you release the resources associated with the video, which stops the n...
Event developer guide - Developer guides
Web › Guide › Events
its position and orientation in the real world, as discussed partially by the page on orientation coordinate systems and the page on the use of 3d transforms. that is different, but similar, to the change in device vertical orientation. the window in which the browser is displayed can trigger events; for example, change size if the user maximizes the window or otherwise changes it. the process loading of a web page can trigger events in response to the completion of different steps in the downloading, parsing, and rendering of the web page for display to the user. the user interaction with the web page contents can trigger events. the events triggered by user interaction evolved during the early years of browser design and include a complicated system defining the sequence in which events wil...
HTML5 Parser - Developer guides
Web › Guide › HTML › HTML5 › HTML5 Parser
async or defer attributes set. with the html5 parser, calls to document.write() in any other context either are ignored or replace the document. 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. scripts that serve racy code to firefox, perhaps while serving safe code to ie, will see a difference due to this change. firefox writes a warning to the javascript console when it ignores a call to document.write(). lack of reparsing prior to html5, parsers reparsed the document if they...
HTML5 - Developer guides
Web › Guide › HTML › HTML5
etching asynchronously some parts of the page, allowing it to display dynamic content, varying according to the time and user actions. this is the technology behind ajax. jit-compiling javascript engines the new generation of javascript engines is much more powerful, leading to greater performance. history api allows the manipulation of the browser history. this is especially useful for pages loading interactively new information. the contenteditable attribute: transform your website to a wiki! html5 has standardized the contenteditable attribute. learn more about this feature. drag and drop the html5 drag and drop api allows support for dragging and dropping items within and between web sites. this also provides a simpler api for use by extensions and mozilla-based applications. focus m...
Localizations and character encodings - Developer guides
ecoded in the exact same way as windows-1252, but firefox is moving to treating windows-1252 as the preferred label for this encoding in accordance with the encoding standard. for locales where internet explorer has more market share than firefox, the fallback encoding should typically be set to the same value as in internet explorer. you can see the fallback encoding a particular browser has by loading a test page. (be sure to use a browser installation that has its settings left to the defaults when investigating!) for locales where firefox has more market share than internet explorer, it's probably best not to change the fallback encoding even if it doesn't follow the guidance given above. (for example, the fallback encoding for the polish, hungarian and czech locales should probably continu...
Mobile Web Development - Developer guides
Web › Guide › Mobile
ss :hover pseudo-class, and will need to design clickable items like buttons to respect the fact that fingers are fatter than mouse pointers. see this article on designing for touch screens. you can use the pointer or any-pointer media query to load different css on a touch-enabled device. optimizing images to help users whose devices have low or expensive bandwidth, you can optimize images by loading images appropriate to the device screen size and resolution. you do this in css by querying for screen height, width, and pixel ratio. you can also make use of css properties to implement visual effects like gradients and shadows without images. mobile apis finally, you can take advantage of the new possibilities offered by mobile devices, such as orientation and geolocation. cross-browser de...
Developer guides
per guide events refer to two things: a design pattern used for the asynchronous handling of various incidents which occur in the lifetime of a web page; and the naming, characterization, and use of a large number of incidents of different types. ajax ajax is a term that defines a group of technologies allowing web applications to make quick, incremental updates to the user interface without reloading the entire browser page. this makes the application faster and more responsive to user actions. graphics on the web modern web sites and applications often need to present graphics of varying sophistication. guide to web apis a list of all web apis and what they do. javascript javascript is the powerful scripting language used to create applications for the web. localizations and character...
Allowing cross-origin use of images and canvas - HTML: Hypertext Markup Language
ad() { let imageurl = "https://cdn.glitch.com/4c9ebeb9-8b9a-4adc-ad0a-238d9ae00bb5%2fmdn_logo-only_color.svg?1535749917189"; downloadedimg = new image; downloadedimg.crossorigin = "anonymous"; downloadedimg.addeventlistener("load", imagereceived, false); downloadedimg.src = imageurl; } we're using a hard-coded url here (imageurl), but that could easily come from anywhere. to begin downloading the image, we create a new htmlimageelement object by using the image() constructor. the image is then configured to allow cross-origin downloading by setting its crossorigin attribute to "anonymous" (that is, allow non-authenticated downloading of the image cross-origin). an event listener is added for the load event being fired on the image element, which means the image data has been received.
<a>: The Anchor element - HTML: Hypertext Markup Language
Web › HTML › Element › a
...
<area> - HTML: Hypertext Markup Language
Web › HTML › Element › area
t, top, right, bottom. circle: the value is x,y,r where x,y is a pair specifying the center of the circle and r is a value for the radius. poly or polygon: the value is a set of x,y pairs for each point in the polygon: x1,y1,x2,y2,x3,y3, and so on. the values are numbers of css pixels. download this attribute, if present, indicates that the author intends the hyperlink to be used for downloading a resource. see <a> for a full description of the download attribute. href the hyperlink target for the area. its value is a valid url. this attribute may be omitted; if so, the <area> element does not represent a hyperlink. hreflang indicates the language of the linked resource. allowed values are determined by bcp47. use this attribute only if the href attribute is present. ping contains ...
<body>: The Document Body element - HTML: Hypertext Markup Language
Web › HTML › Element › body
n to call when the document fails to load properly. onfocus function to call when the document receives focus. onhashchange function to call when the fragment identifier part (starting with the hash ('#') character) of the document's current address has changed. onlanguagechange function to call when the preferred languages changed. onload function to call when the document has finished loading. onmessage function to call when the document has received a message. onoffline function to call when network communication has failed. ononline function to call when network communication has been restored. onpopstate function to call when the user has navigated session history. onredo function to call when the user has moved forward in undo transaction history. onresize function to ...
<iframe>: The Inline Frame element - HTML: Hypertext Markup Language
Web › HTML › Element › iframe
is 150. importance the download priority of the resource in the <iframe>'s src attribute. allowed values: auto (default) no preference. the browser uses its own heuristics to decide the priority of the resource. high the resource should be downloaded before other lower-priority page resources. low the resource should be downloaded after other higher-priority page resources. loading indicates how the browser should load the iframe: eager: load the iframe immediately, regardless if it is outside the visible viewport (this is the default value). lazy: defer loading of the iframe until it reaches a calculated distance from the viewport, as defined by the browser. name a targetable name for the embedded browsing context. this can be used in the target attribute of...
<input>: The Input (Form Input) element - HTML: Hypertext Markup Language
Web › HTML › Element › input
input types except checkbox, radio, file, or any of the button types. see the html autocomplete attribute for additional information, including information on password security and how autocomplete is slightly different for hidden than for other input types. autofocus a boolean attribute which, if present, indicates that the input should automatically have focus when the page has finished loading (or when the <dialog> containing the element has been displayed). note: an element with the autofocus attribute may gain focus before the domcontentloaded event is fired. no more than one element in the document may have the autofocus attribute. if put on more than one element, the first one with the attribute receives focus. the autofocus attribute cannot be used on inputs of type hidd...
<object> - HTML: Hypertext Markup Language
Web › HTML › Element › object
ment is associated with (its form owner). the value of the attribute must be an id of a <form> element in the same document. height the height of the displayed resource, in css pixels. -- (absolute values only. no percentages) name the name of valid browsing context (html5), or the name of the control (html 4). standbyhtml 4 onlyobsolete since html5 a message that the browser can show while loading the object's implementation and data. tabindexhtml 4 onlyobsolete since html5 the position of the element in the tabbing navigation order for the current document. type the content type of the resource specified by data. at least one of data and type must be defined. typemustmatchhtml5 this boolean attribute indicates if the type attribute and the actual content type of the resource must ma...
<picture>: The Picture element - HTML: Hypertext Markup Language
Web › HTML › Element › picture
layout and capabilities of the display device. the <img> element serves two purposes: it describes the size and other attributes of the image and its presentation. it provides a fallback in case none of the offered <source> elements are able to provide a usable image. common use cases for <picture>: art direction. cropping or modifying images for different media conditions (for example, loading a simpler version of an image which has too many details, on smaller displays). offering alternative image formats, for cases where certain formats are not supported. saving bandwidth and speeding page load times by loading the most appropriate image for the viewer's display. if providing higher-density versions of an image for high-dpi (retina) display, use srcset on the <img> element instea...
<template>: The Content Template element - HTML: Hypertext Markup Language
Web › HTML › Element › template
the html content template (<template>) element is a mechanism for holding html that is not to be rendered immediately when a page is loaded but may be instantiated subsequently during runtime using javascript. think of a template as a content fragment that is being stored for subsequent use in the document. while the parser does process the contents of the <template> element while loading the page, it does so only to ensure that those contents are valid; the element's contents are not rendered, however. content categories metadata content, flow content, phrasing content, script-supporting element permitted content no restrictions tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts metadata...
Link types: preload - HTML: Hypertext Markup Language
specifications specification status comment html living standardthe definition of 'preload' in that specification. living standard ...
Identifying resources on the Web - HTTP
ing to subresources — that is, files that are being loaded as part of a larger document — you should only use the http and https schemes. increasingly, browsers are removing support for using ftp to load subresources, for security reasons. ftp is still acceptable at the top level (such as typed directly into the browser's url bar, or the target of a link), although some browsers may delegate loading ftp content to another application. examples https://developer.mozilla.org/docs/learn tel:+1-816-555-1212 git@github.com:mdn/browser-compat-data.git ftp://example.org/resource.txt urn:isbn:9780141036144 mailto:help@supercyberhelpdesk.info specifications specification title rfc 7230, section 2.7: uniform resource identifiers hypertext transfer protocol (http/1.1): mess...
MIME types (IANA media types) - HTTP
he usual audio codec. multipart/form-data the multipart/form-data type can be used when sending the values of a completed html form from browser to server. as a multipart document format, it consists of different parts, delimited by a boundary (a string starting with a double dash --). each part is its own entity with its own http headers, content-disposition, and content-type for file uploading fields. content-type: multipart/form-data; boundary=aboundarystring (other headers associated with the multipart document as a whole) --aboundarystring content-disposition: form-data; name="myfile"; filename="img.jpg" content-type: image/jpeg (data) --aboundarystring content-disposition: form-data; name="myfield" (data) --aboundarystring (more subparts) --aboundarystring-- the following <f...
Resource URLs - HTTP
lect firefox default preferences by overriding this pref() function and using the script resource:///defaults/preferences/firefox.js. furthermore, some default values of preferences differ between build configurations, such as platform and locale, which means web sites could identify individual users using this information. solution in order to fix this problem, mozilla changed the behavior of loading resource: uris in bug 863246, which landed in firefox 57 (quantum). in the past, web content was able to access whatever resource: uris were desired — not only firefox’s internal resources, but also extensions’ assets. now this behavior is prohibited by default. it is however still necessary for firefox to load resources in web content under certain circumstances. for example, if you op...
Content Security Policy (CSP) - HTTP
Web › HTTP › CSP
r the reports: content-security-policy: default-src 'self'; report-uri http://reportcollector.example.com/collector.cgi then you need to set up your server to receive the reports; it can store or process them in whatever manner you determine is appropriate. violation report syntax the report json object contains the following data: blocked-uri the uri of the resource that was blocked from loading by the content security policy. if the blocked uri is from a different origin than the document-uri, then the blocked uri is truncated to contain just the scheme, host, and port. disposition either "enforce" or "report" depending on whether the content-security-policy-report-only header or the content-security-policy header is used. document-uri the uri of the document in which the violati...
HTTP caching - HTTP
Web › HTTP › Caching
twork traffic and thus lessen the time needed to display a representation of a resource. by making use of http caching, web sites become more responsive. different kinds of caches caching is a technique that stores a copy of a given resource and serves it back when requested. when a web cache has a requested resource in its store, it intercepts the request and returns its copy instead of re-downloading from the originating server. this achieves several goals: it eases the load of the server that doesn’t need to serve all clients itself, and it improves performance by being closer to the client, i.e., it takes less time to transmit the resource back. for a web site, it is a major component in achieving high performance. on the other side, it has to be configured properly as not all resources s...
Configuring servers for Ogg media - HTTP
ay the first video frame, and to determine the media's duration. preload is off by default, so if getting to video is the point of your web page, your users may appreciate it if you include preload in your video elements. using preload="metadata" will preload the media file's metadata and possibly the first few frames of video. setting payload to auto tells the browser to automatically begin downloading the media as soon as the page is loaded, under the assumption that the user will play it. configuration for older firefox versions serve x-content-duration headers note: as of firefox 41, the x-content-duration header is no longer supported. see bug 1160695 for more details. the ogg format doesn't encapsulate the duration of media, so for the progress bar on the video controls to display th...
CSP: block-all-mixed-content - HTTP
all mixed content resource requests are blocked, including both active and passive mixed content. this also applies to <iframe> documents, ensuring the entire page is mixed content-free. the upgrade-insecure-requests directive is evaluated before block-all-mixed-content. if the former is set, the latter does nothing, so set one directive or the other – not both, unless you want to force https on older browsers that do not force it after a redirect to http. ...
CSP: font-src - HTTP
<style> tags and note that capitalization and whitespace matter, including leading or trailing whitespace. see unsafe inline script for an example. in csp 2.0 this applied only to inline scripts. csp 3.0 allows it in the case of script-src for external scripts. examples violation cases given this csp header: content-security-policy: font-src https://example.com/ the following font resource loading is blocked and won't load: <style> @font-face { font-family: "myfont"; src: url("https://not-example.com/font"); } body { font-family: "myfont"; } </style> specifications specification status comment content security policy level 3the definition of 'font-src' in that specification. working draft no changes. content security policy leve...
CSP: frame-ancestors - HTTP
example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme. mail.example.com:443: matches all attempts to access port 443 on mail.example.com. https://store.example.com: matches all attempts to access store.example.com using https:. if no url scheme is specified for a host-source and the iframe is loaded from an https url, the url for the page loading the iframe must also be https, per the w3c spec on matching source expressions. <scheme-source> a scheme such as http: or https:. the colon is required and scheme should not be quoted. you can also specify data schemes (not recommended). data: allows data: uris to be used as a content source. this is insecure; an attacker can also inject arbitrary data: uris. use this sparingly and defi...
CSP: frame-src - HTTP
csp version 1 directive type fetch directive fallback if this directive is absent, the user agent will look for the child-src directive (which falls back to the default-src directive). ...
CSP: media-src - HTTP
csp version 1 directive type fetch directive default-src fallback yes. if this directive is absent, the user agent will look for the default-src directive. syntax one or more sources can be allowed for the media-src policy: content-security-policy: media-src <source>; content-security-policy: media-src <source> <source>; sources <source> can be one of the following: <host-source> internet hosts by name or ip address, as well as an optional url scheme and/or port number. ...
CSP: script-src - HTTP
ecifies that the trust explicitly given to a script present in the markup, by accompanying it with a nonce or a hash, shall be propagated to all the scripts loaded by that root script. at the same time, any whitelist or source expressions such as 'self' or 'unsafe-inline' will be ignored. for example, a policy such as script-src 'strict-dynamic' 'nonce-r4nd0m' https://whitelisted.com/ would allow loading of a root script with <script nonce="r4nd0m" src="https://example.com/loader.js"> and propagate that trust to any script loaded by loader.js, but disallow loading scripts from https://whitelisted.com/ unless accompanied by a nonce or loaded from a trusted script. script-src 'strict-dynamic' 'nonce-somenonce' or script-src 'strict-dynamic' 'sha256-base64encodedhash' it is possible to deploy st...
Content-Security-Policy-Report-Only - HTTP
olation-report-endpoint/ if you still want to receive reporting, but also want to enforce a policy, use the content-security-policy header with the report-uri directive. content-security-policy: default-src https:; report-uri /csp-violation-report-endpoint/ violation report syntax the report json object contains the following data: blocked-uri the uri of the resource that was blocked from loading by the content security policy. if the blocked uri is from a different origin than the document-uri, then the blocked uri is truncated to contain just the scheme, host, and port. disposition either "enforce" or "report" depending on whether the content-security-policy header or the content-security-policy-report-only header is used. document-uri the uri of the document in which the violation ...
Cross-Origin-Embedder-Policy - HTTP
header type response header forbidden header name no syntax cross-origin-embedder-policy: unsafe-none | require-corp directives unsafe-none this is the default value. allows the document to fetch cross-origin resources without giving explicit permission through the cors protocol or the cross-origin-resource-policy header. require-corp a document can only load resources from the same origin, or resources explicitly marked as loadable from another origin. ...
Feature-Policy: unsized-media - HTTP
the http feature-policy header unsized-media directive controls whether the current document is allowed to change the size of media elements after the initial layout is complete. this restriction solves "layout instability" problem caused by providing default dimensions for images whose size is not specified in advance so that image doesn't change size after loading. syntax feature-policy: unsized-media <allowlist>; <allowlist> an allowlist is a list of origins that takes one or more of the following values, separated by spaces: *: the feature will be allowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be allowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (in an ifr...
If-None-Match - HTTP
ntity tags uniquely representing the requested resources. they are a string of ascii characters placed between double quotes (like "675af34563dc-tr34") and may be prefixed by w/ to indicate that the weak comparison algorithm should be used (this is useless with if-none-match as it only uses that algorithm). * the asterisk is a special value representing any resource. they are only useful when uploading a resource, usually with put, to check if another resource with the identity has already been uploaded before. examples if-none-match: "bfc13a64729c4290ef5b2c2730249c88ca92d82d" if-none-match: w/"67ab43", "54ed21", "7892dd" if-none-match: * specifications specification title rfc 7232, section 3.2: if-none-match hypertext transfer protocol (http/1.1): conditional re...
Large-Allocation - HTTP
message means that the browser saw the large-allocation header, and was able to reload the page into a new process which should have more available contiguous memory. a large-allocation header was ignored due to the load being triggered by a non-get request. when a post request is used to load a document, that load cannot currently be redirected into a new process. this error is displayed when loading a document with a large-allocation header with a non-get http method. this could be caused due to the document being loaded by a form submission, for example. a large-allocation header was ignored due to the presence of windows which have a reference to this browsing context through the frame hierarchy or window.opener. this error means that the document was not loaded at the top level of an ...
X-DNS-Prefetch-Control - HTTP
of actual page content. by doing this, the high-latency domain name resolution process doesn't cause any delay while fetching content. page load times – especially on mobile networks – can be measurably improved in this way. if the domain names for images can be resolved in advance of the images being requested, pages that load many images can see an improvement of 5% or more in the time of loading images. configuring prefetching in the browser in general, you don't need to do anything to manage prefetching. however, the user may wish to disable prefetching. on firefox, this can be done by setting the network.dns.disableprefetch preference to true. also, by default, prefetching of embedded link hostnames is not performed on documents loaded over https. on firefox, this can be changed by ...
HTTP headers - HTTP
Web › HTTP › Headers
ed by the origin server to handle the request. range requests accept-ranges indicates if the server supports range requests, and if so in which unit the range can be expressed. range indicates the part of a document that the server should return. if-range creates a conditional range request that is only fulfilled if the given etag or date matches the remote resource. used to prevent downloading two ranges from incompatible version of the resource. content-range indicates where in a full body message a partial message belongs. security cross-origin-embedder-policy (coep) allows a server to declare an embedder policy for a given document. cross-origin-opener-policy (coop) prevents other domains from opening/controlling a window. cross-origin-resource-policy (corp) preven...
HEAD - HTTP
Web › HTTP › Methods › HEAD
a response to a head method should not have a body. ...
HTTP range requests - HTTP
checking if a server supports partial requests if the accept-ranges is present in http responses (and its value isn't "none"), the server supports range requests. you can check this by issuing a head request with curl, for example. curl -i http://i.imgur.com/z4d4kwk.jpg http/1.1 200 ok ... accept-ranges: bytes content-length: 146515 in this response, accept-ranges: bytes indicates that bytes can be used as unit to define a range. ...
103 Early Hints - HTTP
Web › HTTP › Status › 103
syntax 103 early hints specifications specification status comments rfc 8297: 103 early hints ietf rfc initial definition browser compatibility the compatibility table in this page is generated from structured data. ...
409 Conflict - HTTP
Web › HTTP › Status › 409
the http 409 conflict response status code indicates a request conflict with current state of the server. conflicts are most likely to occur in response to a put request. for example, you may get a 409 response when uploading a file which is older than the one already on the server resulting in a version control conflict. status 409 conflict specifications specification title rfc 7231, section 6.5.8: 409 conflict hypertext transfer protocol (http/1.1): semantics and content ...
HTTP response status codes - HTTP
Web › HTTP › Status
tocol this code is sent in response to an upgrade request header from the client, and indicates the protocol the server is switching to. 102 processing (webdav) this code indicates that the server has received and is processing the request, but no response is available yet. 103 early hints this status code is primarily intended to be used with the link header, letting the user agent start preloading resources while the server prepares a response. successful responses 200 ok the request has succeeded. the meaning of the success depends on the http method: get: the resource has been fetched and is transmitted in the message body. head: the entity headers are in the message body. put or post: the resource describing the result of the action is transmitted in the message body. tr...
Introduction - JavaScript
more details on individual objects and statements. what is javascript? javascript is a cross-platform, object-oriented scripting language used to make webpages interactive (e.g., having complex animations, clickable buttons, popup menus, etc.). there are also more advanced server side versions of javascript such as node.js, which allow you to add more functionality to a website than simply downloading files (such as realtime collaboration between multiple computers). inside a host environment (for example, a web browser), javascript can be connected to the objects of its environment to provide programmatic control over them. javascript contains a standard library of objects, such as array, date, and math, and a core set of language elements such as operators, control structures, and statement...
JavaScript Guide - JavaScript
ing object hierarchies inheritance promises guarantees chaining error propagation composition timing iterators and generators iterators iterables generators meta programming proxy handlers and traps revocable proxy reflect javascript modules exporting importing default exports renaming features aggregating modules dynamic module loading next » ...
ReferenceError: "x" is not defined - JavaScript
the javascript exception "variable is not defined" occurs when there is a non-existent variable referenced somewhere. message referenceerror: "x" is not defined error type referenceerror. what went wrong? there is a non-existent variable referenced somewhere. this variable needs to be declared, or you need to make sure it is available in your current script or scope. note: when loading a library (such as jquery), make sure it is loaded before you access library variables, such as "$". put the <script> tag that loads the library before your code that uses it. examples variable not declared foo.substring(1); // referenceerror: foo is not defined the "foo" variable isn't defined anywhere. it needs to be some string, so that the string.prototype.substring() method will work. var foo ...
Promise - JavaScript
se { log = document.getelementbyid('log'); log.innerhtml = "live example not available as your browser doesn't support the <code>promise<code> interface."; } this example is started by clicking the button. (you need a browser that supports promise. ) by clicking the button several times in a short amount of time, you'll even see the different promises being fulfilled one after another. loading an image with xhr another simple example using promise and xmlhttprequest to load an image is available at the mdn github js-examples repository. you can also see it in action. each step is commented and allows you to follow the promise and xhr architecture closely. specifications specification ecmascript (ecma-262)the definition of 'promise' in that specification. ...
WebAssembly - JavaScript
nctionality. unlike most other global objects, webassembly is not a constructor (it is not a function object). you can compare it to math, which is also a namespace object for mathematical constants and functions, or to intl which is the namespace object for internationalization constructors and other language-sensitive functions. description the primary uses for the webassembly object are: loading webassembly code, using the webassembly.instantiate() function. creating new memory and table instances via the webassembly.memory()/webassembly.table() constructors. providing facilities to handle errors that occur in webassembly via the webassembly.compileerror()/webassembly.linkerror()/webassembly.runtimeerror() constructors. constructor properties webassembly.compileerror() indicates ...
eval() - JavaScript
losures are also helpful as a way to create parameterized functions without concatenating strings. parsing json (converting strings to javascript objects) if the string you're calling eval() on contains data (for example, an array: "[1, 2, 3]"), as opposed to code, you should consider switching to json, which allows the string to use a subset of javascript syntax to represent data. see also downloading json and javascript in extensions. note that since json syntax is limited compared to javascript syntax, many valid javascript literals will not parse as json. for example, trailing commas are not allowed in json, and property names (keys) in object literals must be enclosed in quotes. be sure to use a json serializer to generate strings that will be later parsed as json. pass data instead of c...
import.meta - JavaScript
such file-specific argument passing may be complementary to that used in the application-wide location.href (with query strings or hash added after the html file path) (or on node.js, through process.argv). specifications specification import.meta propo...
background_color - Web app manifests
background color for the application page to display before its stylesheet is loaded. this value is used by the user agent to draw the background color of a shortcut when the manifest is available before the stylesheet has loaded. therefore background_color should match the background-color css property in the site’s stylesheet for a smooth transition between launching the web application and loading the site's content. note: the background_color member is only meant to improve the user experience while the main stylesheet is loading from the network or the storage media; it is not used by the user agent as the background-color css property when the progressive web app stylesheet is available. examples "background_color": "red" specification specification status comment ...
Web audio codec guide - Web media technologies
of both audio and video. binaries are available for macos, linux, and windows. handbrake a highly popular open source front-end to ffmpeg which adds a graphical user interface that makes it much easier to control the wide variety of options ffmpeg offers while encoding audio and/or video. binaries are available for macos, linux, and windows. audacity an open source audio editor that supports loading audio from many different formats, editing, filtering, and adjusting the audio, and saving it back out in either the original format or a new format. available for macos, linux, and windows. lame a high quality open source mp3 encoder with support for cbr, abr, and vbr encoding as well as a variety of other options. distributed only in source form by the lame project, but can be installed usin...
Codecs used by WebRTC - Web media technologies
ory video codecs codec name profile(s) browser compatibility vp8 — chrome, edge, firefox, safari (12.1+) avc / h.264 constrained baseline (cb) chrome (52+), edge, firefox[1], safari [1] firefox for android 68 and later do not support avc (h.264) anymore. this is due to a change in google play store requirements that prevent firefox from downloading and installing the openh264 codec needed to handle h.264 in webrtc connections. see this article on sumo for details. for details on webrtc-related considerations for each codec, see the sub-sections below by following the links on each codec's name. complete details of what video codecs and configurations webrtc is required to support can be found in rfc 7742: webrtc video processing and codec...
OpenSearch description format
. troubleshooting tips if there is a mistake in your search plugin xml, you could run into errors when adding a discovered plugin. if the error message isn't be helpful, the following tips could help you find the problem. your server should serve opensearch plugins using content-type: application/opensearchdescription+xml. be sure that your search plugin xml is well formed. you can check by loading the file directly into firefox. ampersands (&) in the template url must be escaped as &amp;, and tags must be closed with a trailing slash or matching end tag. the xmlns attribute is important — without it you could get the error message "firefox could not download the search plugin". you must include a text/html url — search plugins including only atom or rss url types (which is valid, but...
Animation performance and frame rate - Web Performance
as> and webgl, css animation, <video>, animated gifs and even animated pngs and other image types. the performance cost of animating a css property can vary from one property to another, and animating expensive css properties can result in jank as the browser struggles to hit a smooth frame rate. for animated media, such as video and animated gifs, the main performance concern is file size - downloading the file size fast enough to not negatively impact performance is the greatest issue. code based animations, be it css, svg, <canvas>, webgl or other javascript animations, can cause performance issues even if the bandwidth footprint is small. these animations can consume cpu and/or cause jank. while performance is sensitive to the particular system and its load, performance tools can help you u...
Using dns-prefetch - Web Performance
uests a resource from a (third party) server, that cross-origin’s domain name must be resolved to an ip address before the browser can issue the request. this process is known as dns resolution. while dns caching can help to reduce this latency, dns resolution can add significant latency to requests. for websites that open connections to many third parties, this latency can significantly reduce loading performance. dns-prefetch helps developers mask dns resolution latency. the html <link> element offers this functionality by way of a rel attribute value of dns-prefetch. the cross-origin domain is then specified in the href attribute: syntax <link rel="dns-prefetch" href="https://fonts.gstatic.com/" > examples <html> <head> <link rel="dns-prefetch" href="https://fonts.gstatic.com/"> ...
Add to Home screen - Progressive web apps (PWAs)
for any site that has the necessary features in place. tapping this will show a confirmation banner — pressing the big + add to home screen button completes the action, adding the app to the home screen. (note: in android 8 and higher, a system-level "add to home screen" permission dialog will be shown first.) if you have mobile chrome available, the experience is slightly different; upon loading our site, you'll see an install banner pop up asking whether you want to add this app to your home screen. note: you can find out a lot more about chrome install banners from the article web app install banners. if you choose not to add it to your home screen at this point, you can do so later using the add to home screen icon in the main chrome menu. regardless of which browser you are us...
Installing and uninstalling web apps - Progressive web apps (PWAs)
stem-level "add to home screen" permission dialog will be shown first. samsung internet browser if you have samsung internet in your mobile device you will see a different icon. tapping that icon should then take you to the same confirmation banner shown in firefox above. google chrome for android if you have google chrome for android available, the experience is slightly different; upon loading our site, you'll see an install banner pop up asking whether you want to add this app to your home screen. note: you can find out a lot more about chrome install banners from the article web app install banners. if you choose not to add it to your home screen at this point, you can do so later using the "add to home screen" icon in the main chrome menu. safari for ios / iphoneos / ipados ...
How to make PWAs installable - Progressive web apps (PWAs)
manifest file, which lists all the information about the website in a json format. it usually resides in the root folder of a web app. it contains useful information, such as the app’s title, paths to different-sized icons that can be used to represent the app on an os (such as an icon on the home screen, an entry in the start menu, or an icon on the desktop), and a background color to use in loading or splash screens. this information is needed for the browser to present the web app properly during the installation process, as well as within the device's app-launching interface, such as the home screen of a mobile device. the js13kpwa.webmanifest file of the js13kpwa web app is included in the <head> block of the index.html file using the following line of code: <link rel="manifest" href="...
Introduction to progressive web apps - Progressive web apps (PWAs)
parties trying to get access to sensitive data. 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. is it worth doing all that? absolutely! with a relatively small amount of effort required to implement the core pwa features, the benefits are huge. for example: a decrease in loading times after the app has been installed, thanks to caching with service workers, along with saving precious bandwidth and time. pwas have near-instantaneous loading (from the second visit). the ability to update only the content that has changed when an app update is available. in contrast, with a native app, even the slightest modification can force the user to download the entire application ag...
The building blocks of responsive design - Progressive web apps (PWAs)
eate small, medium, and large versions of an image, and then serves the appropriate one according to the browser's resolution and available network speed. mobify.js capturing a very clever technique from mozilla that allows you to capture the source of the page before it's parsed. this way, you can swap out image src values with javascript depending on browser features, circumventing browser preloading issues. this is promising, but doesn't work very well across older browsers. picturefill a javascript-based polyfill for <picture>, which works nicely, but it does require a lot of custom markup. adaptive images a server-side solution, which records the viewport size in a cookie, then resizes images via a combination of php and .htaccess to a more appropriate size, if appropriate. this doesn'...
Introduction - SVG: Scalable Vector Graphics
ines and shapes necessary, by modifying already existing raster images, or by a combination of both. the image and its components can also be transformed, composited together, or filtered to change their appearance completely. svg came about in 1999 after several competing formats had been submitted to the w3c and failed to be fully ratified. svg is supported by all major browsers. a downside is loading svg can be slow. svg does offer benefits, some of which include having a dom interface available for it, and not requiring third-party extensions. whether or not to use it often depends on your specific use case. basic ingredients html provides elements for defining headers, paragraphs, tables, and so on. in much the same way svg provides elements for circles, rectangles, and simple and com...
Mixed content - Web security
chrome allows mixed content on http://127.0.0.1/ and http://localhost/. safari does not allow any mixed content. ...
Tutorials
features such as implementing captions and summaries. advanced level html forms forms are a very important part of the web — these provide much of the functionality you need for interacting with websites, e.g. registering and logging in, sending feedback, buying products, and more. this module gets you started with creating the client-side parts of forms. tips for authoring fast-loading html pages optimize web pages to provide a more responsive site for visitors and reduce the load on your web server and internet connection. css tutorials introductory level css basics css (cascading style sheets) is the code you use to style your webpage. css basics takes you through what you need to get started. we'll answer questions like: how do i make my text black or red? how do...
Index - XSLT: Extensible Stylesheet Language Transformations
Web › XSLT › Index
e xslt/javascript interface in gecko xslt no summary! 6 advanced example xslt this advanced example sorts several divs based on their content. the example allows sorting the content multiple times, alternating between ascending and descending order. the javascript loads the .xsl file only on the first sort and sets the xslloaded variable to true once it has finished loading the file. using the xsltprocessor.getparameter() method, the code can figure whether to sort in ascending or descending order. it defaults to ascending if the parameter is empty (the first time the sorting happens, as there is no value for it in the xslt file). the sorting value is set using xsltprocessor.setparameter(). 7 basic example xslt the basic example will load an xml...
Using the Mozilla JavaScript interface to XSL Transformations - XSLT: Extensible Stylesheet Language Transformations
requires a different syntax as the constructor is not defined inside components. ...
Advanced Example - XSLT: Extensible Stylesheet Language Transformations
using the xsltprocessor.getparameter() method, the code can figure whether to sort in ascending or descending order. ...
Index - WebAssembly
e .wasm assembly format. 7 exported webassembly functions guide, javascript, webassembly, export, exported functions, exported wasm functions, wasm exported webassembly functions are how webassembly functions are represented in javascript. this article describes what they are in a little more detail. 8 index index, webassembly found 12 pages: 9 loading and running webassembly code fetch, javascript, webassembly, xmlhttprequest, bytecode to use webassembly in javascript, you first need to pull your module into memory before compilation/instantiation. this article provides a reference for the different mechanisms that can be used to fetch webassembly bytecode, as well as how to compile/instantiate then run it. 10 understandin...
Using the WebAssembly JavaScript API - WebAssembly
supports webassembly, you’ll see this in action! note: this is a convoluted, longwinded example that achieves very little, but it does serve to illustrate what is possible — using webassembly code alongside javascript in your web applications. as we’ve said elsewhere, webassembly doesn’t aim to replace javascript; the two instead can work together, drawing on each other’s strengths. loading our wasm module without streaming if you can't or don't want to use the streaming methods as described above, you can use the non-streaming methods webassembly.compile / webassembly.instantiate instead. these methods don't directly access the byte code, so require an extra step to turn the response into an arraybuffer before compiling/instantiating the wasm module. the equivalent code would lo...
WebAssembly
iling an existing c module to webassembly a core use-case for webassembly is to take the existing ecosystem of c libraries and allow developers to use them on the web. compiling from rust to webassembly if you've written some rust code, you can compile it into webassembly! this tutorial takes you through all you need to know to compile a rust project to wasm and use it in an existing web app. loading and running webassembly code after you have a .wasm, this article covers how to fetch, compile and instantiate it, combining the webassembly javascript api with the fetch or xhr apis. using the webassembly javascript api once you've loaded a .wasm module, you'll want to use it. in this article we show you how to use webassembly via the webassembly javascript api. exported webassembly function...