Search completed in 1.04 seconds.
1243 results for "loaded":
Your results are loading. Please wait...
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. ...
... 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 they're loaded in parallel, "stealing" traffic from the main html document. ...
...script 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 they're loaded in parallel, "stealing" traffic from the main html document. examples basic usage document.addeventlistener('domcontentloaded', (event) => { 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. </script> ...
...And 8 more matches
PerformanceNavigationTiming.domContentLoadedEventEnd - Web APIs
example the following example illustrates this property's usage. ...
... example the following example illustrates this property's usage. ...
... example the following example illustrates this property's usage. ...
...And 5 more matches
PerformanceNavigationTiming.domContentLoadedEventStart - Web APIs
example the following example illustrates this property's usage. ...
... example the following example illustrates this property's usage. ...
... example the following example illustrates this property's usage. ...
...And 5 more matches
HTMLMediaElement: loadeddata event - Web APIs
the loadeddata event is fired when the frame at the current playback position of the media has finished loading; often the first frame. 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. ...
...tion 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. ...
...an event listener for the htmlmediaelement's loadeddata event, then post a message when that event handler has reacted to the event firing. using addeventlistener(): const video = document.queryselector('video'); video.addeventlistener('loadeddata', (event) => { console.log('yay! the readystate just increased to ' + 'have_current_data or greater for the first time.'); }); using the onloadeddata event handler property: const video = document.queryselector('video'); video.onloadeddata = (event) => { console.log('yay! the readystate just increased to ' + 'have_current_data or greater for the first time.'); }; specifications specification status html living standardthe definition of 'loadeddata media event' in that specification. living standard ...
... const video = document.queryselector('video'); video.onloadeddata = (event) => { console.log('yay! the readystate just increased to ' + 'have_current_data or greater for the first time.'); }; specifications specification status html living standardthe definition of 'loadeddata media event' in that specification. living standard html5the definition of 'loadeddata media event' in that specification. recommendation ...
HTMLMediaElement: loadedmetadata event - Web APIs
the loadedmetadata event is fired when the metadata has been loaded. bubbles no cancelable no interface event target element default action none event handler property globaleventhandlers.onloadedmetadata specification html5 media additional properties property type description mozchannels read only int the number of channels. mozsamplerate read only int the sample rate per second. mozframebufferlength read only int the number of samples collected in all channels. ...
...media additional properties property type description mozchannels read only int the number of channels. mozsamplerate read only int the sample rate per second. mozframebufferlength read only int the number of samples collected in all channels. ...
...le rate per second. mozframebufferlength read only int the number of samples collected in all channels. examples these examples add an event listener for the htmlmediaelement's loadedmetadata event, then post a message when that event handler has reacted to the event firing. using addeventlistener(): const video = document.queryselector('video'); video.addeventlistener('loadedmetadata', (event) => { console.log('the duration and dimensions ' + ' of the media and tracks are now known. '); }); using the onloadedmetadata event handler property: const video = document.queryselector('video'); video.onloadedmetadata = (event) => { console.log('the duration and dimensions ' + ' of the media and tracks are now known. '); }; specifications specific...
...ns ' + ' of the media and tracks are now known. '); }); using the onloadedmetadata event handler property: const video = document.queryselector('video'); video.onloadedmetadata = (event) => { console.log('the duration and dimensions ' + ' of the media and tracks are now known. '); }; specifications specification status html living standardthe definition of 'loadedmetadata media event' in that specification. living standard html5the definition of 'canplay media event' in that specification. recommendation ...
FontFace.loaded - Web APIs
Web › API › FontFace › loaded
working draft initial definition. ...
... working draft initial definition. ...
...nterface 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. ...
Window: 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 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. 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. examples basic...
...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. 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. ...
...it in the capture or bubbling phases. for full details on this event please see the page on the document: domcontentloaded event. 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. ...
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.onloadedmetadata - Web APIs
the onloadedmetadata property of the globaleventhandlers mixin is the eventhandler for processing loadedmetadata events. the loadedmetadata event is fired when the metadata has been loaded. syntax element.onloadedmetadata = handlerfunction; var handlerfunction = element.onloadedmetadata; handlerfunction should be either null or a javascript function specifying the handler for the event. specification specification status comment html living standardthe definition of 'onloadedmetadata' in that specification. living standard ...
PerformanceTiming.domContentLoadedEventEnd - 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.domcontentloadedeventend read-only property returns an unsigned long long representing the moment, in milliseconds since the unix epoch, right after all the scripts that need to be executed as soon as possible, in order or not, has been executed. syntax time = performancetiming.domcontentloadedeventend; specifications specification status comment navigation timingthe definition of 'performancetiming.domcontentloadedeventend' in that specification. recommendation initial definition. ...
PerformanceTiming.domContentLoadedEventStart - 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.domcontentloadedeventstart read-only property returns an unsigned long long representing the moment, in miliseconds since the unix epoch, right before the parser sent the domcontentloaded event, that is right after all the scripts that need to be executed right after parsing has been executed. syntax time = performancetiming.domcontentloadedeventstart; specifications specification status comment navigation timingthe definition of 'performancetiming.domcontentloadedeventstart' in that specification. recommendation initial definition. ...
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 ...
Index - Web APIs
Web › API › Index
nts occur when the battery level is updated. 273 beacon api guide, overview, web performance, user behavior tracker, user tracker the beacon interface is used to schedule an asynchronous and non-blocking request to a web server. beacon requests use the http post method and requests typically do not require a response. requests are guaranteed to be initiated before a page is unloaded and they are run to completion, without requiring a blocking request (for example xmlhttprequest). 274 using the beacon api guide, web performance the beacon interface schedules an asynchronous and non-blocking request to a web server. 275 beforeinstallpromptevent api, beforeinstallpromptevent, event, experimental, interface, reference the beforeinstallpr...
...promptevent.prompt() api, beforeinstallpromptevent, experimental, method, reference, prompt the prompt() method of the beforeinstallpromptevent interface allows a developer to show the install prompt at a time of their own choosing. 277 beforeunloadevent api, reference the beforeunload event is fired when the window, the document and its resources are about to be unloaded. 278 biquadfilternode api, biquadfilternode, interface, reference, web audio api the biquadfilternode interface represents a simple low-order filter, and is created using the audiocontext.createbiquadfilter() method. it is an audionode that can represent different kinds of filters, tone control devices, and graphic equalizers. 279 biquadfilternode() api, audio,...
...edia, property, reference, screen capture, screen capture api, screen sharing, sharing, video, display, getdisplaymedia, screen the displaymediastreamconstraints dictionary's video property is used to configure the video track in the stream returned by getdisplaymedia(). 860 document api, dom, document, interface, reference the document interface represents any web page loaded in the browser and serves as an entry point into the web page's content, which is the dom tree. 861 document() api, constructor, dom, document, reference the document constructor creates a new document object that is a web page loaded in the browser and serving as an entry point into the page's content. 862 document.url api, document, html dom, property, refere...
...And 51 more matches
Index - Archive of obsolete content
d content scripts to communicate with each other, each end of the conversation has access to a 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 p...
... 99 platform/xpcom implement xpcom objects, factories, and services. 100 preferences/event-target add-on sdk listen to changes to the preferences system in firefox. 101 preferences/service add-on sdk, jetpack, sdk access the preferences system in firefox. 102 remote/child module, reference, sdk enables an sdk module loaded into a child process to access web content in the child process and communicate with modules in the main process. 103 remote/parent reference, sdk enables you to load modules, and privileged parts of your add-on in general, into child processes. 104 stylesheet/style modify styles using stylesheet files or css rules. 105 stylesheet/utils ...
...s child_process api. 107 system/environment access, set and clear environment variables. 108 system/events api for working with the application observer service. 109 system/runtime access to information about firefox's runtime environment. 110 system/unload register callbacks that are called when a module is unloaded. 111 system/xul-app information about the application on which your add-on is running. 112 tabs/utils functions for working with xul tabs and the xul tabbrowser object. 113 test/assert add-on sdk, jpm implements the assert interface defined in the commonjs unit testing specification version 1.1. 114 test/harness ...
...And 22 more matches
Appendix D: Loading Scripts - Archive of obsolete content
ry. 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 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 ...
...ments, 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 nature of these tags make them easy to find and understand at a glance. speed: script tags may or may not be loaded from pre-compiled bytecode in the fastload cache (gecko 1.x) or startup cache (gecko 2), which means they don't necessarily need to read as source and compiled with each restart. flexibility: script tags provide a means to specify the character set and javascript version of the scripts to be loaded, which many other methods do not. debuggable: development tools support debugging javascript load...
...ko 1.x) or startup cache (gecko 2), which means they don't necessarily need to read as source and compiled with each restart. flexibility: script tags provide a means to specify the character set and javascript version of the scripts to be loaded, which many other methods do not. debuggable: development tools support debugging javascript loaded by script tags disadvantages scoping: scripts loaded via script tags share the global scope with all other scripts loaded into the same window. these tags provide no means to load scripts into a private or otherwise specific scope. speed: even if these scripts are loaded from a cache, only read and compile time are reduced. the scripts still need to execute all of their initialization code and allocate and initialize all of their data structures e...
...And 20 more matches
page-mod - Archive of obsolete content
./my-script.js" }); unless your content script is extremely simple and consists only of a static string, don't use contentscript: if you do, you may have problems getting your add-on approved on amo. instead, keep the script in a separate file and load it using contentscriptfile. this makes your code easier to maintain, secure, debug and review. a page-mod only attaches scripts to documents loaded in tabs. it will not attach scripts to add-on panels, page-workers, sidebars, or firefox hidden windows. to stop a page-mod from making any more modifications, call its destroy() method. the pagemod constructor takes a number of other options to control its behavior: contentstyle lists stylesheets to attach, supplied as strings. contentstylefile lists stylesheets to att...
...age to the content script, and then adds a listener to the gotelement message. the content script receives the getelements message, retrieves all elements of that type, and for each element sends a gotelement message containing the element's innerhtml. the "main.js" code receives each gotelement message and logs the contents. if multiple documents that match the page-mod's include pattern are loaded, then each document is loaded into its own execution context with its own copy of the content scripts. in this case the listener assigned to onattach is called once for each loaded document, and the add-on code will have a separate worker for each document. to learn much more about communicating with content scripts, see the guide to content scripts and in particular the chapter on communicating...
... currently active tab when the user clicks a button: to block certain content, to change the font style, or to display the document's dom structure. using the attach method of the tab object, you can attach a set of content scripts to a particular tab. the scripts are executed immediately. ...
...And 12 more matches
tabs - Archive of obsolete content
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) console.log(tab.title); you can also access individual tabs by index: var tabs = require('sdk/tabs'); tabs.on('ready', function () { console.log('first: ' + tabs[0].title); conso...
...0].title); console.log('last: ' + tabs[tabs.length-1].title); }); you can access the currently active tab: var tabs = require('sdk/tabs'); tabs.on('activate', function () { console.log('active: ' + tabs.activetab.url); }); track a single tab given a tab, you can register event listeners to be notified when the tab is closed, activated or deactivated, or when the page hosted by the tab is loaded or retrieved from the "back-forward cache": var tabs = require("sdk/tabs"); function onopen(tab) { console.log(tab.url + " is open"); tab.on("pageshow", logshow); tab.on("activate", logactivate); tab.on("deactivate", logdeactivate); tab.on("close", logclose); } function logshow(tab) { console.log(tab.url + " is loaded"); } function logactivate(tab) { console.log(tab.url + " is a...
...e tab in the active window. this property is read-only. to activate a tab object, call its activate method. example // get the active tab's title. var tabs = require("sdk/tabs"); console.log("title of active tab is " + tabs.activetab.title); length the number of open tabs across all windows. events open this event is emitted when a new tab is opened. this does not mean that the content has loaded, only that the browser tab itself is fully visible to the user. properties relating to the tab's content (for example: title, favicon, and url) will not be correct at this point. if you need to access these properties, listen for the ready event: var tabs = require("sdk/tabs"); tabs.on('open', function(tab){ tab.on('ready', function(tab){ console.log(tab.url); }); }); arguments tab : ...
...And 12 more matches
RDF in Mozilla FAQ - Archive of obsolete content
he "shortcut keyword" that you can type to reach that website comes from the "browser bookmarks" datasource. both datasources refer to "website" by url: this is the "key" that allows the datasources to be "merged" effectively. for a more detailed account of how to write a datasource, refer to the rdf datasource how-to. how does mozilla manage datasources? the rdf service manages a table of all loaded datasources. the table is keyed by the datasource's "uri", which is either the url of an rdf/xml file, or a "special" uri starting with rdf: that refers to a built-in datasource. datasources may be loaded via the rdf service using the getdatasource() method. if the uri argument refers to an rdf/xml file's url, then the rdf service will create an rdf/xml datasource and asynchronously parse it. th...
...o reload using the refresh() method of nsirdfremotedatasource. refresh() takes a single parameter that indicates whether you'd like it to perform its operation synchronously ("blocking") or asynchrounously ("non-blocking"). you should never do a synchronous load unless you really know what you're doing: this will freeze the ui until the load completes! how can i tell if an rdf/xml datasource has loaded? using the nsirdfremotedatasource interface, it is possible to immediately query the loaded property to determine if the datasource has loaded or not: // get the rdf service var rdf = components .classes["@mozilla.org/rdf/rdf-service;1"] .getservice(components.interfaces.nsirdfservice); // get the datasource. var ds = rdf.getdatasource("http://www.mozilla.org/some-rdf-file.rdf"); // now s...
...e nsirdfremotedatasource interface, it is possible to immediately query the loaded property to determine if the datasource has loaded or not: // get the rdf service var rdf = components .classes["@mozilla.org/rdf/rdf-service;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 continual...
...And 10 more matches
nsIDocShell
e type description allowauth boolean certain dochshells (like the message pane) should not throw up auth dialogs because it can act as a password trojan. allowdnsprefetch boolean attribute that determines whether dns prefetch is allowed for this subtree of the docshell tree. defaults to true. setting this will make it take effect starting with the next document loaded in the docshell. allowimages boolean attribute stating whether or not images should be loaded. allowjavascript boolean whether to allow javascript execution. allowmedia boolean attribute stating whether or not media (audio/video) should be loaded. allowmetaredirects boolean attribute stating if refresh based redirects can be allowed. ...
...shell having a document that is in design mode. in that case, we explicitly allow scripting on the current docshell. read only. canvashasfocus boolean tells the docshell whether the canvas should have focus. called by the focus manager when the user tabs to the frame rather than an element. obsolete since gecko 1.9.2 channelisunsafe boolean find out if the currently loaded document came from a suspicious channel (such as a jar channel where the server-returned content type is not a known jar type). read only. charset string the converter to use when reading the document's data. in mozilla code, all text is encoded as unicode. when reading a document, a converter is used to translate the text from its original format into unicode. this attri...
...target events generated in the frame bubble up to its chromeeventhandler. in the case of a content frame or subframe this is the containing chrome frame. in the case of a chrome frame this is the same as the frame element. this attribute allows chrome to tie in to handle dom events that may be of interest to chrome. contentviewer nsicontentviewer content viewer that is currently loaded for this docshell. this may change as the underlying content changes. read only. currentdocumentchannel nsichannel gets the channel for the currently loaded document, if any. for a new document load, this will be the channel of the previous document until after onlocationchange fires. read only. documentcharsetinfo nsidocumentcharsetinfo the document character ...
...And 10 more matches
Modules - Archive of obsolete content
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 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, jav...
...components is out of scope for this document. however, the following example shows how it can be used to load scripts from other locations: const { classes: cc interfaces: ci } = components; var instance = cc["@mozilla.org/moz/jssubscript-loader;1"]; var loader = instance.getservice(ci.mozijssubscriptloader); function loadscript(url) { loader.loadsubscript(url); } when a script is loaded, it is evaluated in the scope of the global object of the script that loaded it. any property defined on the global object will be accessible from both scripts: // index.js: loadscript("www.foo.com/a.js"); foo; // => 3 // a.js: foo = 3; exporting names the script loader we obtained from the components object allows us load scripts from other locations, but its api is rather limited. for insta...
...h the loadscript function, however, is that it evaluates all scripts in the scope of the same global object. ...
...And 9 more matches
/loader - Archive of obsolete content
create commonjs module loaders. usage the code is intentionally authored so that it can be loaded in several ways. it can be loaded as a regular script tag in documents that have system principals (note: this does not appear to work as of 02.2016 due to "use strict" being added to the file): <script type='application/javascript' src='resource://gre/modules/commonjs/toolkit/loader.js'></script> this will expose a single loader object containing all of the api functions described in this document. ...
... loaded as a regular script tag in documents that have system principals (note: this does not appear to work as of 02.2016 due to "use strict" being added to the file): <script type='application/javascript' src='resource://gre/modules/commonjs/toolkit/loader.js'></script> this will expose a single loader object containing all of the api functions described in this document. ...
...rc='resource://gre/modules/commonjs/toolkit/loader.js'></script> this will expose a single loader object containing all of the api functions described in this document. it can be loaded as a javascript code module: let { loader, require, 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...
...And 9 more matches
Event reference
can use them to interact with the browser. most common categories resource events event name fired when error a resource failed to load. abort the loading of a resource has been aborted. load a resource and its dependent resources have finished loading. beforeunload the window, the document and its resources are about to be unloaded. unload the document or a dependent resource is being unloaded. network events event name fired when online the browser has gained access to the network. offline the browser has lost access to the network. focus events event name fired when focus an element has received focus (does not bubble).
...lection is being dragged over a valid drop target (fired continuously every 350ms). drop an element is dropped on a valid drop target. media events event name fired when audioprocess the input buffer of a scriptprocessornode is ready to be processed. canplay the browser can play the media, but estimates that not enough data has been loaded to play the media up to its end without having to stop for further buffering of content. canplaythrough the browser estimates it can play the media up to its end without stopping for content buffering. complete the rendering of an offlineaudiocontext is terminated. durationchange the duration attribute has been updated. emptied the media has become ...
...uffering of content. canplaythrough the browser estimates it can play the media up to its end without stopping for content buffering. complete the rendering of an offlineaudiocontext is terminated. 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...
...And 9 more matches
Content Scripts - Archive of obsolete content
jpm doesn't make a "data" directory by default, so you must add it and put your content scripts in there. a message-passing api allows the main code and content scripts to communicate with each other this complete add-on illustrates all of these principles. its "main.js" attaches a content script to...
...this enables you to load a javascript library like jquery by url, then pass in a simple script inline that can use jquery: // main.js var data = require("sdk/self").data; var pagemod = require("sdk/...
...require("sdk/page-mod"); pagemod.pagemod({ include: "*.mozilla.org", contentscriptfile: [data.url("jquery.min.js"), data.url("my-content-script.js")] }); if you do this, the scripts can interact directly with each other, just like scripts loaded by the same web page. you can also use contentscript and contentscriptfile together. if you do this, scripts specified using contentscriptfile are loaded before those specified using contentscript. this enables you to load a javascript library like jquery by url, then pass in a simple script inline that can use jquery: // main.js var data = require("sdk/self").data; var pagemod = require("sdk/page-mod"); var contentscriptstring = '$("body").html("<h1>page matches ruleset</h1>");'; pagemod.pagemod({ include: "*.mozilla.org", contentscript: ...
...And 8 more matches
panel - Archive of obsolete content
using html, css, and javascript. the screenshot below shows a panel whose content is built from the list of currently open tabs: panels are useful for presenting temporary interfaces to users in a way that is easier for users to ignore and dismiss than a modal dialog, since panels are hidden the moment users interact with parts of the application interface outside them. a panel's content is loaded as soon as it is created, before the panel is shown, and the content remains loaded when a panel is hidden, so it is possible to keep a panel around in the background, updating its content as appropriate in preparation for the next time it is shown. your add-on can receive notifications when a panel is shown or hidden by listening to its show and hide events. opening a panel will close any pane...
...hidden by listening to its show and hide events. opening a panel will close any panel created by the panel() constructor that is already open, even if that panel was opened by a different add-on sdk based extension. if you want to close an existing panel without opening a new one, you can call the hide() or the destroy() method. panel content the panel's content is specified as html, which is loaded from the url supplied in the contenturl option to the panel's constructor. you can load remote html into the panel: var mypanel = require("sdk/panel").panel({ width: 180, height: 180, contenturl: "https://en.wikipedia.org/w/index.php?title=jetpack&useformat=mobile" }); mypanel.show(); you can also load html that's been packaged with your add-on, and this is most probably how you will ...
...de() { button.state('window', {checked: false}); } updating panel content you can update the panel's content by: sending a message to a content script that updates the dom in the same document. this is usually the best approach. embedding an iframe in the panel, and changing its document setting the panel's contenturl property. however, doing this will cause any content scripts to be unloaded and then reloaded, so it may be less efficient, and you'll lose any state associated with the scripts. scripting panel content you can't directly access your panel's content from your main add-on code. to access the panel's content, you need to load a script into the panel. in the sdk these scripts are called "content scripts" because they're explicitly used for interacting with web content. ...
...And 8 more matches
ui/sidebar - Archive of obsolete content
the sidebar generates a show event when it is shown and a hide event when it is hidden. once you've finished using the sidebar you can destroy it by calling its dispose() method. ...
... it by calling its dispose() method. to show what a sidebar looks like, here's a sidebar that displays the results of running the w3c validator on the current page: specifying sidebar content the content of a sidebar is specified using html, which is loaded from the url supplied in the url option to the sidebar's constructor. unlike modules such as panel, the content must be local, typically loaded from the add-on's data directory via a url constructed using self.data.url(): var sidebar = require("sdk/ui/sidebar").sidebar({ id: 'my-sidebar', title: 'my sidebar', url: require("sdk/self").data.url("sidebar.html") }); from firefox 34, you can use "./sidebar.html" as an alias for self.data.url("sidebar.html"). so you can rewrite the above code like this: var sidebar = require("sdk/ui/...
...y> <script type="text/javascript" src="stuff.js"></script> </body> </html> you can update the sidebar's content by setting the sidebar's url property. this will change the sidebar's content across all windows. communicating with sidebar scripts you can't directly access your sidebar's content from your main add-on code, but you can send messages between your main add-on code and scripts loaded into your sidebar. on the sidebar end of the conversation, sidebar scripts get a global variable addon that contains a port for sending and receiving messages. on the add-on side, you need to get a worker object for the sidebar before you can send or receive messages. there are two events emitted by the sidebar which will give you a worker: attach and ready. listen to attach if the first messag...
...And 8 more matches
Intercepting Page Loads - Archive of obsolete content
also, the different techniques tap into different steps of the load process. ...
...also, the different techniques tap into different steps of the load process. ...
...also, the different techniques tap into different steps of the load process. ...
...And 8 more matches
Index - MDN Web Docs Glossary: Definitions of Web-related terms
ist of device and agent specific preferences. 80 closure codingscripting, glossary the binding which defines the scope of execution. in javascript, functions create a closure context. 81 code splitting glossary, reference, web performance, code splitting, latency code splitting is the splitting of code into various bundles or components which can then be loaded on demand or in parallel. 82 codec glossary, webmechanics a codec (a blend word derived from "coder-decoder") is a program, algorithm, or device that encodes or decodes a data stream. a given codec knows how to handle a specific encoding or compression technology. 83 compile codingscripting, glossary compiling is the process of transforming a computer pro...
...into an equivalent program of another language. a compiler is a software to execute this task. sometimes, this task is also referred to as "assembling" or "build", which typically indiciates more than just compilation is done, e.g. packaging it in a binary format. 84 compile time codingscripting, glossary, javascript the compile time is the time from when the program is first loaded until the program is parsed. 85 computer programming codingscripting, computer programming, programming language, programming computer programming is a process of composing and organizing a collection of instructions. these tell a computer/software program what to do in a language which the computer understands. these instructions come in the form of many different languages ...
...al and decentralized naming system for internet connected resources. dns maintains a list of domain names along with the resources, such as ip addresses, that are associated with them. 102 dom (document object model) codingscripting, dom, glossary the dom (document object model) is an api that represents and interacts with any html or xml document. the dom is a document model loaded in the browser and representing the document as a node tree, where each node represents part of the document (e.g. an element, text string, or comment). 103 dtls (datagram transport layer security) dtls, intro datagram transport layer security (dtls) is a protocol used to secure datagram-based communications. it's based on the stream-focused transport layer security (tls), pr...
...And 8 more matches
What is JavaScript? - Learn web development
code (the html, css, and javascript) inside an execution environment (the browser tab). this is like a factory that takes in raw materials (the code) and outputs a product (the web page). a very common use of javascript is to dynamically 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...
...at run time, rather than ahead of time. there are advantages to both types of language, but we won't discuss them right now. server-side versus client-side code you might also hear the terms server-side and client-side code, especially in the context of web development. client-side code is code that is run on the user's computer — when a web page is viewed, the page's client-side code is downloaded, then run and displayed by the browser. in this module we are explicitly talking about client-side javascript. server-side code on the other hand is run on the server, then its results are downloaded and displayed in the browser. examples of popular server-side web languages include php, python, ruby, asp.net and... javascript! javascript can also be used as a server-side language, for example i...
...ng a clickable button. ...
...And 8 more matches
Venkman Introduction - Archive of obsolete content
mes from a counter built in to the application. for more information about this counter and the data, see item 2.2 in the venkman faq.) when you first 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 v...
...ed function. this is the same text you would get from the tosource method of the function prototype. if the source text you are debugging is poorly formatted, pretty print can help make it easier to read by inserting line breaks and whitespace in appropriate places. when pretty print is enabled you will see a green check mark on the toolbar button, and the menu item will be checked as well. the loaded scripts view the loaded scripts view is in the top left portion of the window. when a file is loaded by the browser it will appear in this view, and when unloaded it will be removed. files are listed in alphabetical order, grouped by file type. file names are displayed after a color coded, single letter icon representing the file extension. figure 6 shows the table of icon and file types. at t...
...is interrupted by the debugger, the line of the file where the interruption occurred is automatically displayed in the source code view. the line in question will be highlighted in yellow to make it easy to spot. clicking in the left margin of this view will set a breakpoint at that line. if the breakpoint is successfully set, the margin will show the letter "b" on a red background, and both the loaded scripts view and interactive session view will provide feedback. the breakpoint can be cleared by clicking in the margin again (on the letter "b"). breakpoints cannot be set on lines which do not contain executable code, such as blank and comment lines. for these lines, the interactive session view will display an error message explaining why the breakpoint could not be set. breakpoints can also...
...And 7 more matches
nsIContentPolicy - Archive of obsolete content
rface used to implement a content policy mechanism. implementations of this interface can be used to control the loading of various types of out-of-line content, or the processing of certain types of inline 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. this interface can be very useful if you are developing a content-aware plugin (blocking ads or altering the look of content, for example), or if you want to stop or allow user-browsed urls. warning: do not block the caller in your implementations of shouldload() or shouldprocess() (for example, by launching a dialog to prompt the user for som...
...s type_internal_frame and type_internal_iframe in order to discern the difference internally. these types are mapped to type_subdocument before being passed into the implementation of the content policy and should not be used outside gecko code. type_refresh 8 indicates a timed refresh. shouldload() will never get this, because it does not represent content to be loaded (the actual load triggered by the refresh will go through shouldload() as expected). shouldprocess() will get this for, for example <meta> refresh elements and http refresh headers. type_xbl 9 indicates an xbl binding request, triggered either by -moz-binding css property or the document.addbinding() method. type_ping 10 indicates a ping triggered by a click on a...
...ed either by -moz-binding css property or the document.addbinding() method. type_ping 10 indicates a ping triggered by a click on an <a> element using the ping attribute. type_xmlhttprequest 11 indicates an xmlhttprequest. also used for document.load() type_object_subrequest 12 indicates a request by a plugin. type_dtd 13 indicates a dtd loaded by an xml document. type_font 14 indicates a font loaded via @font-face rule. type_media 15 indicates a video or audio load. type_websocket 16 indicates a websocket load. type_csp_report 17 indicates a content security policy report. type_xslt 18 indicates a style sheet transformation. type_beacon 19 indicat...
...And 7 more matches
DevTools API - Firefox Developer Tools
. if unspecified the previously active tool is shown. hosttype {string} - the position the toolbox will be placed. one of bottom, side, window, custom. see hosttype for details. hostoptions {object} - an options object passed to the selected host. see hosttype for details. return value: a promise that is fulfilled with the toolbox instance once it has been initialized and the selected tool is loaded. gettoolbox(target) fetch the toolbox object for the given target. parameters: target {target} - the target the toolbox is debugging. return value: toolbox object or undefined if there's no toolbox for the given target.. closetoolbox(target) closes the toolbox for given target. parameters: target {target} - the target of the toolbox that should be closed. return value: a...
... the toolpanel object 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:notif...
... selectnexttool() selects the next tool in the toolbox. ...
...And 7 more matches
Introducing the Audio API extension - Archive of obsolete content
f possible; see the compatibility table at the bottom of this page to guide your decision. be aware that this feature may cease to work at any time. please note that this document describes a non-standard experimental api. this api has been deprecated since gecko 22, disabled since gecko 28, and removed from gecko 31. you should use the web audio api instead. reading audio streams the loadedmetadata event when the metadata of the media element is available, it triggers a loadedmetadata event. this event has the following attributes: mozchannels: number of channels mozsamplerate: sample rate per second mozframebufferlength: number of samples collected in all channels this information is needed later to decode the audio data stream. the following example extracts the data from ...
...l channels this information is needed later to decode the audio data stream. ...
... src="song.ogg" controls="true" style="width: 512px;"> </audio> <script> function loadedmetadata() { channels = audio.mozchannels; rate = audio.mozsamplerate; framebufferlength = audio.mozframebufferlength; } var audio = document.getelementbyid('audio-element'); audio.addeventlistener('loadedmetadata', loadedmetadata, false); </script> </body> </html> the mozaudioavailable event as the audio is played, sample data is made available to the audio layer and the audio buffer (size defined in mozframebufferlength) gets filled with those samples. once the buffer is full, the event mozaudioavailable is triggered. this event therefore contains the raw samples of a period of time. tho...
...And 6 more matches
browser - Archive of obsolete content
home page. you can switch to this home page using the gohome method. showcaret type: boolean whether or not to cause a typing caret to be visible in the content area. default is false. src type: uri the uri of the content to appear in the element. type type: one of the values below. the type of browser, which can be used to set access of the document loaded inside the browser. if this is not set, the loaded document has the same access as the window containing the browser. more precisely: the document loaded into a chrome window is always of chrome type. subdocuments of chrome documents are of chrome type, unless the container element (one of iframe, browser or editor) has one of the special type attribute values (the common ones are content, conten...
...wser is added to a chrome document), and preventing documents from inheriting the principal of the parent document. the type attribute on all frames in content documents is ignored; subdocuments of content documents are always content documents. warning: the type attribute must be set before the element is inserted into the document. content a browser for content. the content that is loaded inside the browser is not allowed to access the chrome above it. content-primary the primary browser for content. the content that is loaded inside the browser is not allowed to access the chrome above it. for instance, in a web browser, this would be the element that displays the web page. the window for the primary content can be retrieved more conveniently using window.content. content-t...
...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. ...
...And 6 more matches
tabbrowser - Archive of obsolete content
icontentvieweredit which handles clipboard operations on the document. contentviewerfile type: nsicontentviewerfile reference to the nsicontentviewerfile interface for the document. contentwindow type: todo use the contentwindow.wrappedjsobject to obtain a dom(html) window object currenturi type: nsiuri this read-only property contains the currently loaded url. to change the url, use the loaduri method. docshell type: nsidocshell this read-only property contains the nsidocshell object for the document. documentcharsetinfo obsolete since gecko 12.0 type: nsidocumentcharsetinfo this read-only property contains the nsidocumentcharsetinfo object for the document which is used to handle which character set s...
...this property holds the value of the user's home page setting. markupdocumentviewer type: nsimarkupdocumentviewer this read-only property contains the nsimarkupdocumentviewer which is responsible for drawing the document. securityui type: nsisecurebrowserui the read-only property holds an object which may be used to determine the security level of the loaded document. selectedbrowser type: browser element this read-only property returns the currently displayed browser element. selectedtab type: tab element a reference to the currently selected tab, which will always be one of the tab elements in the tabs element. assign a value to this property to modify the currently selected tab. sessionhistory type: nsishistory t...
...the progress listener should implement the nsiwebprogresslistener interface. addtab( url, referreruri, charset, postdata, owner, allowthirdpartyfixup ) addtab( url, {referreruri: ..., charset: ..., postdata: ..., owner: ..., allowthirdpartyfixup: ..., relatedtocurrent: ... }) return type: tab element opens a new tab that loads a page with the specified url. the rest of the paramet...
...And 6 more matches
Frame script loading and lifetime
with an extension, use a "chrome.manifest" file to register a chrome url: // chrome.manifest content my-e10s-extension chrome/content/ // chrome script mm.loadframescript("chrome://my-e10s-extension/content/content.js", true); allowdelayedload if the message manager is a global frame message manager or a window message manager then: if allowdelayedload is true, the frame script will be loaded into any new frame, which has opened after the loadframescript() call. for example: var mm = window.messagemanager; mm.loadframescript("chrome://my-e10s-extension/content/frame-script.js", true); the script will be loaded into all tabs currently open in this window, and all new tabs opened afterwards. if allowdelayedload is false, the script will only be loaded into frames which are open...
...e, the script will only be loaded into frames which are open when the call was made. if the message manager is a browser message manager, you should always pass true here. because a browser message manager only corresponds to a single browser tab, its loadframescript() function will only ever 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. ...
...t 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 stay loaded until the tab is closed, even if you reload the document or navigate. if you want to limit a...
...And 6 more matches
Index
-libfile library-file [-ciphers cipher-enable-list] [-mechanisms mechanism-list] for example: modutil -dbdir sql:/home/my/sharednssdb -add "example pkcs #11 module" -libfile "/tmp/crypto.so" -mechanisms rsa:dsa:rc2:random using database directory ... module "example pkcs #11 module" added to database. installing a cryptographic module from a jar file pkcs #11 modules can also be loaded using a jar file, which contains all of the required libraries and an installation script that describes how to install the module. the jar install script is described in more detail in [1]the section called “jar installation file format”. the jar installation script defines the setup information for each platform that the module can be installed on. for example: platforms {...
...lename] -dbdir [sql:]directory listing the modules shows the module name, their status, and other associated security databases for certificates and keys. for example: modutil -list -dbdir sql:/home/my/sharednssdb listing of pkcs #11 modules ----------------------------------------------------------- 1. ...
...for example: modutil -list "nss internal pkcs #11 module" -dbdir sql:/home/my/sharednssdb ----------------------------------------------------------- name: nss internal pkcs #11 module library file: **internal only module** manufacturer: mozilla foundation description: nss internal crypto services pkcs #11 version 2.20 library version: 3.11 cipher enable flags: none default mecha...
...And 6 more matches
HTTP Index - HTTP
Web › HTTP › Index
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 requests are treated as fatal network errors ...
...the apis that are restricted are: 81 csp: default-src csp, content-security-policy, directive, http, reference, security, default, default-src, source the http content-security-policy (csp) default-src directive serves as a fallback for the other csp fetch directives. ...
... a fallback for the other csp fetch directives. for each of the following directives that are absent, the user agent will look for the default-src directive and will use this value for it: 82 csp: font-src csp, content-security-policy, directive, http, reference, security, font, source the http content-security-policy (csp) font-src directive specifies valid sources for fonts loaded using @font-face. 83 csp: form-action csp, content-security-policy, directive, http, security, action, form, form-action the http content-security-policy (csp) form-action directive restricts the urls which can be used as the target of a form submissions from a given context. 84 csp: frame-ancestors ancestors, csp, content-security-policy, directive, frame, htt...
...And 6 more matches
Modifying Web Pages Based on URL - Archive of obsolete content
to follow this tutorial you'll need to have learned the basics of jpm. to modify any pages that match a particular pattern (for example, "http://example.org/") as they are loaded, use page-mod module. to create a page-mod, you need to specify two things: one or more content scripts to run whose job is to interact with web content. one or more patterns to match urls for the pages you want to modify. ...
...ts to run whose job is to interact with web content. one or more patterns to match urls for the pages you want to modify. a simple code snippet where content script is supplied as contentscript option and url pattern is given as include option is as follows: // import the page-mod api var pagemod = require("sdk/page-mod"); // create a page-mod // it will run a script whenever a ".org" url is loaded // the script replaces the page contents with a message pagemod.pagemod({ include: "*.org", contentscript: 'document.body.innerhtml = ' + ' "<h1>page matches ruleset</h1>";' }); do as follows: create a new directory and navigate to it. run jpm init, accepting all the defaults open the file index.js and add the code above run jpm run open ietf.org in the browser windo...
...self.data.url("my-script.js"). from firefox 34 onwards, you can just use "./my-script.js" instead. ...
...And 5 more matches
How to convert an overlay extension to restartless - Archive of obsolete content
convert an old overlay-based extension into a restartless (bootstrapped) extension that is also extractionless. requirements first off, what kind of add-on are we talking about here? well, xul overlays and windows, jsm files, chrome & resource mappings with localization, default preferences, but no xpcom components of your own. some of that will have to be replaced and the rest will need to be loaded differently. next, what's the minimum version of firefox we should require (preferably an esr)? this guide targets firefox 17 esr or later (or anything else gecko 17+, such as seamonkey 2.14+). this is two esrs back (as of this writing), which should be plenty. using the current firefox esr, stable version, or nightly is generally a better idea if given the option, but some users take forever to...
...just stuck with that forever. it does still work if you don't have restartlessness to worry about, though the protocol (or scheme, or whatever term you prefer) really should be avoided at this point. the resource:// protocol actually bleeds into content which allows webpages to detect installed add-ons using the protocol, which is not particularly fantastic (just the static file contents, not any loaded script/data). step 2a: load your jsm from chrome:// now with that preface out of the way, this part is easy: drop support for firefox 3.x if you haven't already, move your jsm files to wherever you've got your chrome mapping to for your xul overlay and/or windows, import your files from that new chrome mapped path instead of the old resource one, and remove your "resource" line from your chrome...
...th instead of the old resource one, and remove your "resource" line from your chrome.manifest file. it's probably a good idea to do this even if you aren't going fully restartless / extractionless due to the previously mentioned exposure to content of resource mappings. also, drop support for firefox 4 through 9 while you're at it. prior to firefox 10, the chrome.manifest file you rely on wasn't loaded automatically for restartless add-ons. hacks were required, and 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 ...
...And 5 more matches
Inner-browsing extending the browser navigation paradigm - Archive of obsolete content
in this process: data load: acquisition of information data acquisition can be implemented using javascript and remote procedure calls using soap-based rpc mechanism or using interfaces like xmlhttprequest (currently offered in netscape 7 and internet explorer 6). data bind: mutation in the current document this step takes care of applying the changes into the current document, based on the data loaded, and uses dom interfaces. the mechanism can be as simple as copying new content to the current document, or as complex as performing dynamic transformations on the data source before applying the changes into the current document. for example, if a given web site's framework uses xslt to format xml contents as html, would be appropriate to reuse xslt to format new data that is about to be part of...
...ain xml documents. the xml document is an excellent structure for storing data. the following picture shows the model that is the essence of this technote. the idea is to use iframes only for the communication channel and use the dom and javascript to bind the content with the document in the main working page. ...
...n iframe \_________ content is loaded -> call data binder data binder \_____ load xml||html data from iframe "container" \_____ send content to proper layout components the method presented here separates data request from data binding. this approach allows us to untie from the traditional navigation model. a request to a web server no longer requires a new page to be loaded, in order to update information in a page seamlessly. as a general approach, the main steps to the iframe-based implementation can be represented as follows: create a hidden iframe in the page; when a new content is required, ask for the content to the iframe; the iframe will load the content and callback a function in the main page; update the main page. of course, specific implementat...
...And 5 more matches
Index - Archive of obsolete content
Archive › Mozilla › XUL › Index
31 browserid xul, xul reference no summary! 32 button.type xul attributes, xul reference no summary! 33 buttonaccesskeyaccept xul attributes, xul reference no summary! 34 buttonaccesskeycancel xul attributes, xul reference no summary! 35 buttonaccesskeydisclosure xul attributes, ...
...ueryprocessor interface and follow some conventions for when registering the component. 436 index found 1218 pages: 437 international characters in xul javascript firefox, gecko, guide, internationalization, javascript, mozilla, xpcom, xul gecko 1.8, as used in firefox 1.5 and other applications, added support for non-ascii characters in javascript files loaded from xul files. 438 introduction to xul guide, xul mozilla has configurable, downloadable chrome, meaning that the arrangement and even presence or absence of controls in the main window is not hardwired into the application, but loaded from a separate ui description. in fact, most of mozilla's windows (and dialogs) will be described using this mechanism. xul (pronounced "zoo...
...ons and xul applications can modify the way command line parameters are handled by writing a component that implements the nsicommandlinehandler interface and registering it in a category. 891 notes no summary! 892 sorting and filtering a custom tree view this is example code for sorting and filtering a custom tree view, that is, a tree whose values are loaded via javascript. this will not work for other types of trees, for example rdf-backed or ones created with dom methods. 893 style classes xul reference, xul_style_classes no summary! 894 alert-icon xul reference, xul_style_classes no summary! 895 chromeclass-toolbar xul reference, xul_style_classes no summary! 896 error-icon ...
...And 5 more matches
Storage access policy: Block cookies from trackers
t. when the list is applied in firefox, we make two important changes: first, we only use the "basic protection" version of the list, which excludes some categories of trackers. in the future, we may expand our protections to use the "strict protection" version of the list. second, firefox uses an additional "entity list", which prevents domains from being classified as trackers when they are loaded on a top-level site owned by the same organization. firefox uses the built-in tracking protection url classifier to determine which resources match the tracking protection list. domains are matched against the list in accordance with the safebrowsing v4 specification. specifically, we check the exact hostname of the resource against the list, as well as the last four hostnames formed by startin...
...this prevents those resources from retrieving tracking identifiers stored in cookies or site storage and using them to identify users across visits to multiple first parties. specifically, firefox does this by imposing the following restrictions: cookies: block cookie request headers and ignore set-cookie response headers. return an empty string for calls to documen...
... apply additional restrictions to third-party storage access in the future. the restrictions applied by the policy will not prevent third-party scripts classified as tracking resources from accessing storage in the main context of the page. these scripts can continue to use storage scoped to the top-level origin. origins classified as trackers will have access to their own storage when they are loaded in a first-party context. cross-origin resources loaded from the same etld+1 as the top-level context will still have access to their storage. origins normally classified as trackers will not be blocked if the top-level page origin is determined to be from the same organization as them. storage access grants in order to improve web compatibility and permit third-party integrations that requi...
...And 5 more matches
MediaDevices.getUserMedia() - Web APIs
see security for more information on this and other security issues related to using getusermedia(). syntax var promise = navigator.mediadevices.getusermedia(constraints); parameters constraints a mediastreamconstraints object specifying the types of media to request, along with any requirements for ...
... aborterror although the user and operating system both granted access to the hardware device, and no hardware issues occurred that would cause a notreadableerror, some problem occurred which prevented the device from being used. notallowederror one or more of the requested source devices cannot be used at this time. this will happen if the browsing context is insecure (that is, the page was loaded using http rather than https). it also happens if the user has specified that the current browsing instance is not permitted access to the device, the user has denied access for the current session, or the user has denied all access to user media devices globally. on browsers that support managing media permissions with feature policy, this error is returned if feature policy is not configured to...
... as an api that may involve significant privacy concerns, getusermedia()'s specification lays out a wide array of privacy and security requirements that browsers are obligated to meet. getusermedia() is a powerful feature which can only be used in secure contexts; in insecure contexts, navigator.mediadevices is undefined, preventing access to getusermedia(). a secure context is, in short, a page loaded using https or the file:/// url scheme, or a page loaded from localhost. in addition, user permission is always required to access the user's audio and video inputs. only a window's top-level document context for a valid origin can even request permission to use getusermedia(), unless the top-level context expressly grants permission for a given <iframe> to do so using feature policy. otherwise,...
...And 5 more matches
page-worker - Archive of obsolete content
turl: "./myfile.html" }); you can load a new page by setting the page worker's contenturl property. in this example we fetch the first paragraph of a page from wikipedia, then the first paragraph of a different page: var getfirstparagraph = "var paras = document.getelementsbytagname('p');" + "console.log(paras[0].textcontent);" + "self.port.emit('loaded');" pageworker = require("sdk/page-worker").page({ contentscript: getfirstparagraph, contenturl: "http://en.wikipedia.org/wiki/chalk" }); pageworker.port.on("loaded", function() { pageworker.contenturl = "http://en.wikipedia.org/wiki/cheese" }); scripting page content to access the page's dom you need to attach a script to it. in the sdk these scripts are called "content scripts" becaus...
...and load it using contentscriptfile. this makes your code easier to maintain, secure, debug and review. to learn much more about content scripts, see the working with content scripts guide. scripting trusted page content we've already seen that you can package html files in your add-on's data directory and load them using page-worker. we can call this "trusted" content, because unlike content loaded from a source outside the add-on, the add-on author knows exactly what it's doing. to interact with trusted content you don't need to use content scripts: you can just include a script from the html file in the normal way, using <script> tags. like a content script, these scripts can communicate with the add-on code using the postmessage() api or the port api. the crucial difference is that thes...
...ttern strings. these define the documents to which the page-worker's content worker applies. at least one match pattern must be supplied. see the match-pattern module for a detailed description of match pattern syntax. contentscriptfile string,array a local file url or an array of local file urls of content scripts to load. content scripts specified by this option are loaded before those specified by the contentscript option. see working with content scripts for help on setting this property. contentscript string,array a string or an array of strings containing the texts of content scripts to load. content scripts specified by this option are loaded after those specified by the contentscriptfile option. contentscriptwhen string...
...And 4 more matches
widget - Archive of obsolete content
le.log("pausing"); }); player.port.on("stop", function() { console.log("stopping"); }); to learn much more about content scripts, see the working with content scripts guide. scripting trusted widget content we've already seen that you can package html files in your add-on's data directory and use them to define the widget's content. we can call this "trusted" content, because unlike content loaded from a source outside the add-on, the add-on author knows exactly what it's doing. to interact with trusted content you don't need to use content scripts: you can just include a script from the html file in the normal way, using script tags. like a content script, these scripts can communicate with the add-on code using the postmessage() api or the port api. the crucial difference is that these ...
... an optional object describing permissions for the content. it should contain a single key named script whose value is a boolean that indicates whether or not to execute script in the content. script defaults to true. contentscriptfile string,array a local file url or an array of local file urls of content scripts to load. content scripts specified by this property are loaded before those specified by the contentscript property. contentscript string,array a string or an array of strings containing the texts of content scripts to load. content scripts specified by this property are loaded after those specified by the contentscriptfile property. contentscriptwhen string when to load the content scripts. this may take one o...
...ontent scripts specified by this property are loaded after those specified by the contentscriptfile property. contentscriptwhen string when to load the content scripts. this may take one of the following values: "start": load content scripts immediately after the document element for the widget is inserted into the dom, but before the dom content itself has been loaded "ready": load content scripts once dom content has been loaded, corresponding to the domcontentloaded event "end": load content scripts once all the content (dom, js, css, images) for the widget has been loaded, at the time the window.onload event fires this property is optional and defaults to "end". contentscriptoptions object read-only value exposed ...
...And 4 more matches
ui/frame - Archive of obsolete content
/script> as usual, the path to the script is relative to the html file's location. messages logged from a frame script using the console will not appear in the terminal when you run the add-on using jpm run. however, they will appear in the browser console. this issue is being tracked as bug 982385. communicating with frames you can exchange messages between the main add-on code and scripts loaded into the frame using an api modeled on window.postmessage(). a frame creates a separate iframe instance for each browser window. so there are three cases to consider: sending messages from a frame script to the main add-on code sending messages from the main add-on code to all instances of a frame, across all browser windows sending messages from the main add-on code to a single instance of ...
... assign a listener to the frame's detach event. onload function assign a listener to the frame's load event. onready function assign a listener to the frame's ready event. onmessage function assign a listener to the frame's message event. frame methods postmessage(message, targetorigin) send a message to scripts loaded into the frame. this will send the message to message is all viewport documents (one per browser window) of the frame: var { frame } = require("sdk/ui/frame"); var { toolbar } = require("sdk/ui/toolbar"); var frame = new frame({ url: "./frame.html" }); var toolbar = toolbar({ name: "my-toolbar", title: "my toolbar", items: [frame] }); frame.postmessage("ping", frame.url); frame scrip...
...ameters event : string the event the listener is listening for. frame supports the following events: attach, detach, load, ready, and message. listener : function the listener to remove. destroy() destroy the frame. after calling this function, the frame will no longer appear in the ui, and accessing any of its properties or methods will throw an error. properties url url for the content loaded into the frame. this is read-only. it's only accessible after the attach event has occurred for this frame. events attach this event is emitted whenever a new frame instance is constructed and the browser has started to load its document: for example, when the user opens a new browser window, if that window has a toolbar containing this frame. since the event is dispatched asynchronously, the ...
...And 4 more matches
On page load - Archive of obsolete content
if you need finer control over custom code execution—for example, as documents are loading or when tabs are switched—see progress listeners. progress listeners allow extensions to be notified of events associated with documents loading in the browser and with tab switching events. progress listeners implement the nsiwebprogresslistener interface. ...
...element (browsers) or messagepane (mail): window.addeventlistener("load", function load(event){ window.removeeventlistener("load", load, false); //remove listener, no longer needed myextension.init(); },false); var myextension = { init: function() { var appcontent = document.getelementbyid("appcontent"); // browser if(appcontent){ appcontent.addeventlistener("domcontentloaded", myextension.onpageload, true); } var messagepane = document.getelementbyid("messagepane"); // mail if(messagepane){ messagepane.addeventlistener("load", function(event) { myextension.onpageload(event); }, true); } }, onpageload: function(aevent) { var doc = aevent.originaltarget; // doc is document that triggered "onload" event // do something with the loaded ...
...t); }, true); } }, onpageload: function(aevent) { 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.location.href.search("forum") > -1) alert("a forum page is loaded"); // add event listener for page unload aevent.originaltarget.defaultview.addeventlistener("unload", function(event){ myextension.onpageunload(event); }, true); }, onpageunload: function(aevent) { // do something } }; current firefox trunk nightlies will fire the onpageload function for not only documents, but xul:images (favicons in tabbrowser). if you only want to handle ...
...And 4 more matches
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 continu...
... 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 in __sigsuspend (set=0xbf5ffbc0) at ../sysdeps/unix/sysv/linux/sigsuspend.c:48 48 ../sysdeps/unix/sysv/linux/sigsuspend.c: no such file or directory. current language: auto; currently c (gdb) shar glib reading symbols from /usr/lib/libglib-1.2.so.0...done. (gdb) here...
...5.x of the debugger ( yet unreleased ): ^c program received signal sigint, interrupt. [switching to thread 2051 (runnable)] 0x404ccdeb in __sigsuspend (set=0xbf5ffbac) at ../sysdeps/unix/sysv/linux/sigsuspend.c:48 48 ../sysdeps/unix/sysv/linux/sigsuspend.c: no such file or directory. current language: auto; currently c (gdb) shar gtk reading symbols from /usr/lib/libgtk-1.2.so.0...done. ...
...And 4 more matches
Common causes of memory leaks in extensions - Extensions
ables can be avoided by using ecmascript 5's strict mode. strict mode also excludes several other error-prone code patterns. for some examples found in real-world add-ons, see bug 712733, bug 725875, and bug 727552. ...
...n an object which is specific to that document, and cleaned up when the document is unloaded, or stored as weak references. be careful with setinterval/settimeout using window.setinterval() or window.settimeout() can be problematic, too, when it comes to zombie compartments. consider the following example code that could be part of your browser.xul overlay: gbrowser.addeventlistener("domcontentloaded", function(evt) { var contentdoc = evt.originaltarget; var i = 0; // refresh the title once each second setinterval(function() { contentdoc.title = ++i; }, 1000); }, false); one would normally expect that the interval (or timer) would be destroyed as soon as the document unloads, in the same way that event listeners are automatically destroyed. however, while this is still true, ...
...would normally expect that the interval (or timer) would be destroyed as soon as the document unloads, in the same way that event listeners are automatically destroyed. however, while this is still true, the window.setinterval() in the example originates from the outer chrome window (browser.xul) and not from the content window. hence the interval will only be destroyed when the outer window is unloaded (i.e. when the user closes the whole browser window) but not when the content window unloads (i.e. when the user closes the tab). the interval function in the example would still hold a reference to contentdoc, therefore leaking the content document and the associated window and compartment. if your add-on makes use of long-lived timeouts or uses window.setinterval(), you need to take special ca...
...And 4 more matches
Tips for authoring fast-loading HTML pages - Learn web development
mber of files referenced in a web page lowers the number of http connections required to download a page, thereby reducing the time for these requests to be sent, and for their responses to be received. depending on a browser's cache settings, it may send a request with the if-modified-since header for each referenced file, asking whether the file has been modified since the last time it was downloaded. too much time spent querying the last modified time of the referenced files can delay the initial display of the web page, since the browser must check the modification time for each of these files, before rendering the page. if you use background images a lot in your css, you can reduce the number of http lookups needed by combining the images into one, known as an image sprite. then you just ...
...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 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 o...
...y of the page but prevents annoying changes in a page's layout when the page completes loading. for this reason, height and width should be specified for images, whenever possible. tables should use the css selector: property combination: table-layout: fixed; and should specify widths of columns using the <col> and the <colgroup> elements. use lazy loading for images by default, imags are loaded eagerly; that is, the image is fetched and rendered as soon as it's processed in the html. all eagerly loaded images are rendered before the document's load event is sent. switching to lazy loading of images tells the browser to hold off on loading images until they're about to be needed to draw the visual viewport. to mark an image for lazy loading, specify its loading attribute with a value of...
...And 4 more matches
Index
Mozilla › Tech › XPCOM › Index
framechanged() method. 186 imgidecoder this interface is the base class for decoders for specific image formats. 187 imgidecoderobserver interfaces, interfaces:scriptable, needscontent, reference, xpcom interface reference, needsattention 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. if an image is decoded on load and not visibly discarded, decode notifications are nested logically inside load notifications as one might expect. however, with decode-on-draw, the set of decode notifications can come completely after the load notifications, and can come multiple times if the image is discarda...
...able, offline_resources, xpcom, xpcom interface reference flags the specified key as one that should be cached opportunistically. 335 nsiapplicationupdateservice interfaces, interfaces:scriptable, update service, xpcom, xpcom api reference, xpcom interface reference 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. 336 nsiarray interfaces, interfaces:scriptable, xpcom, xpcom api reference, xpcom interface reference an indexed collection of elements. provides basic functionality for retrieving elements at a specific position, searching for elements. indexes are zero-bas...
...sicontainerboxobject interfaces, interfaces:scriptable, needscontent, xpcom, xpcom interface reference the boxobject belonging to a xul browser, editor or iframe element implements this interface. 433 nsicontentframemessagemanager interface reference, interfaces:scriptable, xpcom, xpcom interface reference this interface provides the environment for scripts that are loaded into content frames using the nsiframescriptloader interface. it enables these scripts to receive messages from the chrome process and send messages back to the chrome process. 434 nsicontentpref preferences, xpcom no summary! 435 nsicontentprefcallback2 preferences, xpcom, xpcom interface reference called when the method finishes. this will be called exa...
...And 4 more matches
nsIFrameScriptLoader
ace is used to load frame scripts. methods void loadframescript(in astring aurl, in boolean aallowdelayedload, [optional] in boolean aruninglobalscope) void removedelayedframescript(in astring aurl); jsval getdelayedframescripts(); loadframescript() load a script in the remote frame. frame scripts are loaded as soon as loadframescript() is called. if this function is called on a chromemessagebroadcaster (for example, a global frame message manager or a window message manager) then: loadframescript() will load the frame script independently into each applicable frame: every open frame in the given window for the window message manager, or every frame in every window for the global message manager ...
... if this function is called on a chromemessagesender: it will load the frame script only into this chromemessagesender's frame aallowdelayedload should always be true. it's possible that the frame for this chromemessagesender is not yet avai...
...anager) then: loadframescript() will load the frame script independently into each applicable frame: every open frame in the given window for the window message manager, or every frame in every window for the global message manager if aallowdelayedload is true, then the script will also be loaded into any applicable new frames opened after the loadframescript() call. otherwise it will only be loaded into frames that exist at the time of the call. if this function is called on a chromemessagesender: it will load the frame script only into this chromemessagesender's frame aallowdelayedload should always be true. it's possible that the frame for this chromemessagesender is not yet available at the time of the loadframescript() call, and if you pass false in this situation, your process sc...
...And 4 more matches
nsIWebNavigation
try should be replaced. this flag is only applicable to loaduri. load_flags_bypass_cache 256 this flag specifies that the local web cache should be bypassed, but an intermediate proxy cache could still be used to satisfy the load. load_flags_bypass_proxy 512 this flag specifies that any intermediate proxy caches should be bypassed (that is, that the content should be loaded from the origin server). load_flags_charset_change 1024 this flag specifies that a reload was triggered as a result of detecting an incorrect character encoding while parsing a previously loaded document. load_flags_stop_content 2048 if this flag is set, stop() will be called before the load starts and will stop both content and network activity (the default is ...
...oad_flags_allow_third_party_fixup 8192 this flag specifies that the uri may be submitted to a third-party server for correction. this should only be applied to non-sensitive uris entered by users. load_flags_first_load 16384 this flag specifies that this is the first load in this object. set with care, since setting incorrectly can cause us to assume that nothing was actually loaded in this object if the load ends up being handled by an external application. load_flags_allow_popups 32768 this flag specifies that the load should not be subject to popup blocking checks. note for valid load flag combinations look here nsdocshellloadtypes.h stop flags constant value description stop_network 1 this flag specifies that all net...
... description cangoback prbool indicates if the object can go back. if true this indicates that there is back session history available for navigation. read only. cangoforward prbool indicates if the object can go forward. if true this indicates that there is forward session history available for navigation. read only. currenturi nsiuri the currently loaded uri or null. read only. document nsidomdocument retrieves the current dom document for the frame, or lazily creates a blank document if there is none. this attribute never returns null except for unexpected error situations. read only. referringuri nsiuri the referring uri for the currently loaded uri or null. read only. sessionhistory nsishistory the ...
...And 4 more matches
Plug-in Basics - Plugins
d adobe acrobat utilities that provide object embedding and compression/decompression services applications that range from personal information managers to games the range of possibilities for using plug-in technology seems boundless, as shown by the growing numbers of independent software vendors who are creating new and innovative plug-ins. ...
...ng a page that has several embedded realaudio clips, for example, the browser will create as many instances of the realplayer plug-in as are needed (though of course playing several realaudio files at the same time would seldom be a good idea). when the user leaves the page or closes the window, the plug-in instance is deleted. when the last instance of a plug-in is deleted, the plug-in code is unloaded from memory. a plug-in consumes no resources other than disk space when it is not loaded. the next section, understanding the runtime model, describes these stages in more detail. understanding the 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)...
...s 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 specific functions have the prefix "npp", and all of the browser-specific functions have the prefix "npn". note: np_initialize and np_shutdown are not technically a part of the function table that the plug-in hands t...
...And 4 more matches
Using files from web applications - Web APIs
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 to the loaded image which results in the image appearing in the thumbnail on the user's screen. using object urls the dom url.createobjecturl() and url.revokeobjecturl() methods let you create simple url strings that can be used to reference any da...
...rl from html, you can create an object url for it like this: const objecturl = window.url.createobjecturl(fileobj); the object url is a string identifying the file object. each time you call url.createobjecturl(), a unique object url is created even if you've created an object url for that file already. each of these must be released. while they are released automatically when the document is unloaded, if your page uses them dynamically you should release them explicitly by calling url.revokeobjecturl(): url.revokeobjecturl(objecturl); example: using object urls to display images this example uses object urls to display image thumbnails. in addition, it displays other file information including their names and sizes. the html that presents the interface looks like this: <input type="file"...
... files: create a new list item (<li>) element and insert it into the list. create a new image (<img>) element. set the image's source to a new object url representing the file, using url.createobjecturl() to create the 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 s...
...And 4 more matches
HTMLMediaElement - Web APIs
otal for all channels, and by default is set to be the number of channels * 1024 (e.g., 2 channels * 1024 samples = 2048 total). the mozframebufferlength property can be set to a new value for lower latency, larger amounts of data, etc. the size given must be a number between 512 and 16384. using any other size results in an exception being thrown. the best time to set a new length is after the loadedmetadata event fires, when the audio info is known, but before the audio has started or mozaudioavailable events have begun firing. htmlmediaelement.mozsamplerate read only returns a double representing the number of samples per second that will be played. for example, 44100 samples per second is the sample rate used by cd audio. htmlmediaelement.muted is a boolean that determines wheth...
... media element is paused. htmlmediaelement.playbackrate is a double that indicates the rate at which the media is being played back. htmlmediaelement.played read only returns a timeranges object that contains the ranges of the media source that the browser has played, if any. htmlmediaelement.preload is a domstring that reflects the preload html attribute, indicating what data should be preloaded, if any. possible values are: none, metadata, auto. htmlmediaelement.preservespitch is a boolean that determines if the pitch of the sound will be preserved. if set to false, the pitch will adjust to the speed of the audio. this is implemented with prefixes in firefox (mozpreservespitch) and webkit (webkitpreservespitch). htmlmediaelement.readystate read only returns a unsigned short (enum...
.... htmlmediaelement.mozcapturestream() [enter description] htmlmediaelement.mozcapturestreamuntilended() [enter description] htmlmediaelement.mozgetmetadata() returns object, which contains properties that represent metadata from the playing media resource as {key: value} pairs. a separate copy of the data is returned each time the method is called. this method must be called after the loadedmetadata event fires. htmlmediaelement.pause() pauses the media playback. htmlmediaelement.play() begins playback of the media. htmlmediaelement.seektonextframe() seeks to the next frame in the media. this non-standard, experimental method makes it possible to manually drive reading and rendering of media at a custom speed, or to move through the media frame-by-frame to perform filtering...
...And 4 more matches
Cross-browser audio basics - Developer guides
efine an <audio> element with multiple sources — we do this as not all browsers support the same audio formats. to ensure reasonable coverage, we should specify at least two different formats. the two formats that will give maximum coverage are mp3 and ogg vorbis. we do this using the <source> element, which takes the attributes src and type. src contains the path to the audio file to be loaded (relative or absolute). type is used to inform the browser of the file type. if omitted, most browsers will attempt to guess this from the file extension. if the <audio> element is not supported then <audio> and <source> will be ignored. however any supported text or elements that you define within <audio> will be displayed or acted upon. so the ideal place to create a fallback or infor...
..., function() { //grabbing the file }); durationchange if you just want to know as soon as the duration of your media is established, this is the event for you. this can be useful because the initial value for duration is nan (not a number), which you probably don't want to display to your users. myaudio.addeventlistener("durationchange", function() { //you can display the duration now }); loadedmetadata metadata can consist of more than just duration — if you want to wait for all the metadata to download before doing something, you can detect the loadedmetadata event. myaudio.addeventlistener("loadedmetadata", function() { //you can display the duration now }); loadeddata the loadeddata event is fired when the first bit of media arrives. the playhead is in position but not quite ...
...it is good practice to display some kind of 'loader' at this point. ...
...And 4 more matches
Allowing cross-origin use of images and canvas - HTML: Hypertext Markup Language
html provides a crossorigin attribute for images that, in combination with an appropriate cors header, allows images defined by the <img> element that are loaded from foreign origins to be used in a <canvas> as if they had been loaded from the current origin. see cors settings attributes for details on how the crossorigin attribute is used. security and tainted canvases because the pixels in a canvas's bitmap can come from a variety of sources, including images or videos retrieved from other hosts, it's inevitable that security problems may arise. as soon as you draw into a canvas any data that was loaded from another origin without cors approval, the canvas becomes tainted. a tainted canvas is one which is no longer considered secure, and any attempts to retrieve image data back fro...
... implementing the save feature now that the server has been configured to allow retrieval of the images cross-origin, we can write the code that allows the user to save them to local local storage, just as if they were being served from the same domain the code is running on. the key is to use the crossorigin attribute by setting crossorigin on the htmlimageelement into which the image will be loaded. ...
...to begin downloading the image, we create a new htmlimageelement object by using the image() constructor. ...
...And 4 more matches
<link>: The External Resource Link element - HTML: Hypertext Markup Language
Web › HTML › Element › link
ouch-icon-precomposed" sizes="114x114" href="apple-icon-114.png" type="image/png"> the sizes attribute indicates the icon size, while the type contains the mime type of the resource being linked. these provide useful hints to allow the browser to choose the most appropriate icon available. you can also provide a media type or query inside a media attribute; this resource will then only be loaded if the media condition is true. for example: <link href="print.css" rel="stylesheet" media="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"> ...
...uld 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 series. attributes this element includes the global attributes. as this attribute is only used when rel="preload" or rel="prefetch" has been set on the <link> element. it specifies the type of content being loaded by the <link>, which is necessary for request matching, application of correct content security policy, and setting of correct accept request header. furthermore, rel="preload" uses this as a signal for request prioritization. the table below lists the valid values for this attribute and the elements or resources they apply to. value applies to audio <audi...
...present, the resource is fetched without a cors request (i.e. without sending the origin http header), preventing its non-tainted usage. if invalid, it is handled as if the enumerated keyword anonymous was used. see cors settings attributes for additional information. disabled for rel="stylesheet" only, the disabled boolean attribute indicates whether or not the described stylesheet should be loaded and applied to the document. if disabled is specified in the html when it is loaded, the stylesheet will not be loaded during page load. instead, the stylesheet will be loaded on-demand, if and when the disabled attribute is changed to false or removed. setting the disabled property in the dom causes the stylesheet to be removed from the document's document.stylesheets list. href this attri...
...And 4 more matches
Progressive loading - Progressive web apps (PWAs)
ading its resources. first meaningful paint it's important to deliver something meaningful to the user as soon as possible — the longer they wait for the page to load, the bigger the chance they will leave before waiting for everything to finish. we should be able to show them at least the basic view of the page they want to see, with placeholders in the places more content will eventually be loaded. this could be achieved by progressive loading — also known as lazy loading. this is all about deferring loading of as many resources as possible (html, css, javascript), and only loading those immediately that are really needed for the 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 fea...
...dling 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="stylesheet" href="print.css" media="print"> this will tell the browser to load them only when the condition is met. in our js13kpwa demo app, the css is simple enough to leave it all...
... go even further and move everything from style.css to the <style> tag in the <head> of index.html — this would improve performance even more, but for the readability of the example we will skip that approach too. images besides javascript and css, websites will likely contain a number of images. when you include <img> elements in your html, then every referenced image will be fetched and downloaded during initial website access. it's not unusual to have megabytes of image data to download before announcing the site is ready, but this again creates a bad perception of performance. we don't need all of the images in the best possible quality at the very beginning of viewing the site. this can be optimized. first of all, you should use tools or services similar to tinypng, which will reduce t...
...And 4 more matches
Modularization techniques - Archive of obsolete content
than the ones provided here. the basics interfaces the basic building blocks of modules are c++ pure virtual interfaces. a pure virtual interface is simply a class where every method is defined as pure virtual, that is: virtual int foo(int bar) = 0; pure virtual interfaces provide an easy mechanism for passing function tables between modules that may reside in separate, possibly dynamically loaded, libraries. each interface is assigned a unique interface identifier, or iid. nsisupports the key interface in our model is the nsisupports interface, our equivalent to com's iunknown interface. nsisupports provides two key features, interface interrogation and reference counting. interface interrogation is a simple, uniform mechanism for determining which interfaces a object supports, and for ...
... const nsiid &aiid, nsisupports *adelegate, void **aresult); // manually registry a factory for a class static nsresult registerfactory(const nscid &aclass, nsifactory *afactory, prbool areplace); // manually registry a dynamically loaded factory for a class static nsresult registerfactory(const nscid &aclass, const char *alibrary, prbool areplace, prbool apersist); // manually unregister a factory for a class static nsresult unregisterfactory(const nscid &aclass, nsifactory *afactory); ...
...the most direct is through registerfactory(). registerfactory() supports two different regi...
...And 3 more matches
Message manager overview
re's a hierarchy of frame message managers: the global frame message manager, window message managers, and browser message managers. global frame message manager description there's a single global frame message manager in the chrome process. this operates on all frames, in all content tabs. if you load a frame script using the global frame message manager, the script gets loaded separately into every open tab: three times, in the diagram above. similarly, if you send a message using the global frame message manager, it's received by all content tabs, and is then delivered to any frame scripts that are listening for it. its most important functions and attributes are: childcount : contains the number of children (typically, browser windows) getchildat() : g...
...nsimessagelistenermanager); you can also access it as the mm property of services.jsm, if you are in the parent process. window message manager description there's a window message manager for every browser window: two, in the diagram above. it operates on all content tabs in a given window. if you load a frame script using the window message manager it gets loaded separately into each tab open in that particular window. if you send a message using the window message manager, it gets sent to all content tabs in that window. its most important functions and attributes are: childcount : contains the number of children (typically, browser tabs) getchildat() : get the child at the given index loadframescript() : load a frame script into ever...
...xt, "browser" refers to the xul <browser> object, which is a frame that hosts a single web document. it does not refer to the more general sense of a web browser. description finally, there's a browser message manager for every open content tab: three, in the diagram above. this corresponds one-to-one with a content tab. scripts you load using a browser message manager are loaded only into that content tab, and messages you send are delivered only to that content tab. you can mix and match: so for example, you could load a script into every tab using the global message manager, but then send a message to the script instance loaded into a specific tab by using the browser message manager. its most important functions are: loadframescript() : load a frame scr...
...And 3 more matches
WebRequest.jsm
ples of canceling requests. listener argument name type description url string target of the request. windowid number the id of the window making the request, as an outerwindowid. parentwindowid number type string the resource type. browser object the xul browser into which the resource will be loaded, or null if the resource will not be loaded into a xul browser. onbeforesendheaders this event is triggered before sending any http data, but after all http headers are available. this is a good place to listen if you want to modify http headers. opt_extrainfospec values name description "blocking" make the browser wait until the listener returns. use this if...
... for an example using this. listener argument name type description url string target of the request. windowid number the id of the window making the request, as an outerwindowid. parentwindowid number type string the resource type. browser object the xul browser into which the resource will be loaded, or null if the resource will not be loaded into a xul browser. method string the http method to be used (get, post, etc). requestheaders array of http headers. the http request headers that will be sent. this is only included if you set "requestheaders" in the opt_extrainfospec argument. onsendheaders triggered just before sending headers. if y...
...ent passed to the listener. listener argument name type description url string target of the request. windowid number the id of the window making the request, as an outerwindowid. parentwindowid number type string the resource type. browser object the xul browser into which the resource will be loaded, or null if the resource will not be loaded into a xul browser. method string the http method to be used (get, post, etc). requestheaders array of http headers. the http request headers that will be sent. this is only included if you set "requestheaders" in the opt_extrainfospec argument. onheadersreceived triggered once response headers have be...
...And 3 more matches
Scripting Java
a.io.file("test.txt") test.txt js> f.exists() true js> f.getname() test.txt static methods and fields can be accessed from the class object itself: js> java.lang.math.pi 3.141592653589793 js> java.lang.math.cos(0) 1 in javascript, unlike java, the method by itself is an object and can be evaluated as well as being called. if we just view the method object by itself we can see the various overloaded forms of the method: js> f.listfiles function listfiles() {/* java.io.file[] listfiles() java.io.file[] listfiles(java.io.filenamefilter) java.io.file[] listfiles(java.io.filefilter) */} this output shows that the file class defines three overloaded methods listfiles: one that takes no arguments, another with a filenamefilter argument, and a third with a filefilter argument. all the methods re...
...ience by allowing properties of javabeans to be accessed directly by their property names. a javabean property foo is defined by the methods getfoo and setfoo. additionally, a boolean property of the same name can be defined by an isfoo method. for example, the following code actually calls the file object's getname and isdirectory methods. js> f.name test.txt js> f.directory false calling overloaded methods the process of choosing a method to call based upon the types of the arguments is called overload resolution. in java, overload resolution is performed at compile time, while in rhino it occurs at runtime. this difference is inevitable given javascript's use of dynamic typing as was discussed in chapter 2: since the type of a variable is not known until runtime, only then can overload re...
...led overload resolution. in java, overload resolution is performed at compile time, while in rhino it occurs at runtime. this difference is inevitable given javascript's use of dynamic typing as was discussed in chapter 2: since the type of a variable is not known until runtime, only then can overload resolution occur. as an example, consider the following java class that defines a number of overloaded methods and calls them. public class overload { public string f(object o) { return "f(object)"; } public string f(string s) { return "f(string)"; } public string f(int i) { return "f(int)"; } public string g(string s, int i) { return "g(string,int)"; } public string g(int i, string s) { return "g(int,string)"; } public static void main(string[] args) { overl...
...And 3 more matches
nsIIOService
the spec for the desired uri. aorigincharset the charset for the uri. may be null. abaseuri the base uri for the spec. may be null. if aspec is an absolute url, this parameter is ignored. aloadingnode the loadingdocument of the channel. this is the document/element that will get access to the result of this request. for example for an image load, it's the document in which the image will be loaded. and for a css stylesheet it's the document whose rendering will be affected by the stylesheet. if possible, pass in the element which is performing the load. but if the load is coming from a js api (such as xmlhttprequest) or if the load might be coalesced across multiple elements (such as for ) then pass in the document node instead. for loads that are not related to any document, such as loads...
...pass the principal of that worker. for loads from an addon or from internal browser features, pass the system principal. this principal should almost always be the system principal if aloadingnode is null. the only exception to this is for loads from webworkers since they don't have any nodes to be passed as aloadingnode. please note, aloadingprincipal is *not* the principal of the resource being loaded. but rather the principal of the context where the resource will be used. atriggeringprincipal the triggeringprincipal of the load. the triggeringprincipal is the principal of the resource that caused this particular url to be loaded. most likely the triggeringprincipal and the loadingprincipal are identical, in which case the triggeringprincipal can be left out. in some cases the loadingprinci...
...uld never use the systemprincipal as the loadingprincipal. parameters auri an nsiuri from which to make a channel. aloadingnode the loadingdocument of the channel. the element or document where the result of this request will be used. this is the document/element that will get access to the result of this request. for example for an image load, it's the document in which the image will be loaded. and for a css stylesheet it's the document whose rendering will be affected by the stylesheet. if possible, pass in the element which is performing the load. but if the load is coming from a js api (such as xmlhttprequest) or if the load might be coalesced across multiple elements (such as for <img>) then pass in the document node instead. for loads that are not related to any document, such ...
...And 3 more matches
Events
e-window-close a compose window gets closed compose-window-init a compose window has been opened compose-window-reopen a cached compose window has been reopened. no load event is fired in this case. folders event name event type fired when... msgcreatedbview onactivecreatedview onactivemessagesloaded 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. ondisplayingfolder a folder gets displayed onfolderloading ...
...essages 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. ...
...ew 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. ...
...And 3 more matches
nsIMsgCloudFileProvider
ternal web content. managementurl acstring readonly: a chrome url for an xhtml page displayed within the filelink preferences dialog, used for displaying and setting provider-specific settings once the account has already been set up. this url should not point to external web content. fileuploadsizelimit long readonly: the upper size limit in bytes for a file to be uploaded. if this value is not known, returns -1. remainingfilespace long long readonly: the remaining storage space available for this account in bytes. if this value is not known, returns -1. filespaceused long long readonly: the total amount of space used by this account. if this value is not known, returns -1. lasterror acstring readonly: the last error mes...
...utherr 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 associated with a particular account. this should probably be called immediately after instantiation. void init(in string aaccountkey); parameters uploadfile() starts a file...
...hould probably be called immediately after instantiation. void init(in string aaccountkey); parameters uploadfile() starts a file upload for this account. aaccountkey the account key that this instance of the nsimsgcloudfileprovider should be associated with. void uploadfile(in nsilocalfile afile, in nsirequestobserver acallback); parameters afile the file to be uploaded. ...
...And 3 more matches
Using Service Workers - Web APIs
worker is installed, it then receives an activate event. the primary use of onactivate is for cleanup of resources used in previous versions of a service worker script. the service worker will now control pages, but only those opened after the register() is successful. i.e. a document starts life with or without a service worker and maintains that for its lifetime. so documents will have to be reloaded to actually be controlled. the below graphic shows a summary of the available service worker events: promises promises are a great mechanism for running async operations, with success dependant on one another. this is central to the way service workers work. promises can do a variety of things, but all you need to know for now is that if something returns a promise, you can attach .the...
... to wait for myfunction() to run and return value before any more of the code can execute. in the second example, myfunction() returns a promise for value, then the rest of the code can carry on running. when the promise resolves, the code inside then will be run, asynchronously. ...
... of the code can carry on running. when the promise resolves, the code inside then will be run, asynchronously. now for a real example — what if we wanted to load images dynamically, but we wanted to make sure the images were loaded before we tried to display them? this is a standard thing to want to do, but it can be a bit of a pain. we can use .onload to only display the image after it’s loaded, but what about events that start happening before we start listening to them? we could try to work around this using .complete, but it’s still not foolproof, and what about multiple images? and, ummm, it’s still synchronous, so blocks the main thread. instead, we could build our own promise to handle this kind of case. (see our promises test example for the source code, or look at it runn...
...And 3 more matches
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. ...
...e 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. ...
...s is in contrast to domcontentloaded, which is fired as soon as the page dom has been loaded, without waiting for resources to finish loading. ...
...And 3 more matches
Window.open() - Web APIs
Web › API › Window › open
the window interface's open() method loads the specified resource into the new or existing browsing context (window, <iframe> or tab) with the specified name. if the name doesn't exist, then a new browsing context is opened in a new tab or a new window, and the specified resource is loaded into it. syntax var window = window.open(url, windowname, [windowfeatures]); parameters url a domstring indicating the url of the resource to be loaded. this can be a path or url to an html page, image file, or any other resource that is supported by the browser. if the empty string ("") is specified as url, a blank page is opened into the targeted browsing context. windowname optional a domstring specifying the name of the browsing context (window, <iframe> or tab) into which to load the specified r...
...the window couldn't be opened, the returned value is instead null. the returned reference can be used to access properties and methods of the new window as long as it complies with same-origin policy security requirements. description the open() method creates a new secondary browser window, similar to choosing new window from the file menu. the url parameter specifies the url to be fetched and loaded in the new window. if url is an empty string, then a new blank, empty window (url about:blank) is created with the default toolbars of the main window. note that remote urls won't load immediately. when window.open() returns, the window always contains about:blank. the actual fetching of the url is deferred and starts after the current script block finishes executing. the window creation and the...
...in this case the return value of the method is the existing window and windowfeatures is ignored. providing an empty string for url is a way to get a reference to an open window by its name without changing the window's location. on firefox and chrome (at least), this only works from the same parent, ie. if the current window is the opener of the window you try to get an...
...And 3 more matches
Window - Web APIs
Web › API › Window
a window for a given document can be obtained using the document.defaultview property. a global variable, window, representing the window in which the script is running, is exposed to javascript code. the window interface is home to a variety of functions, namespaces, objects, and constructors which are not necessarily directly associated with the concept of a user interface window. however, the window interface is a suitable place to include these items that need to be globally available. ...
...globaleventhandlers.onkeypress called when a key (except shift, fn, and capslock) is in pressed position. see keypress event. globaleventhandlers.onkeyup called when you finish releasing any key. see keyup event. windoweventhandlers.onlanguagechange an event handler property for languagechange events on the window. globaleventhandlers.onload called after all resources and the dom are fully loaded. will not get called when the page is loaded from cache, such as with back button. windoweventhandlers.onmessage is an eventhandler representing the code to be called when the message event is raised. globaleventhandlers.onmousedown called when any mouse button is pressed. globaleventhandlers.onmousemove called continously when the mouse is moved inside the window. globaleventhandlers.onmo...
... windoweventhandlers.onoffline called when network connection is lost. see offline event. windoweventhandlers.ononline called when network connection is established. see online event. windoweventhandlers.onpagehide called when the user navigates away from the page, before the onunload event. see pagehide event. windoweventhandlers.onpageshow called after all resources and the dom are fully loaded. see pageshow event. windoweventhandlers.onpopstate called when a back button is pressed. globaleventhandlers.onreset called when a form is reset globaleventhandlers.onresize called continuously as you are resizing the window. globaleventhandlers.onscroll called when the scroll bar is moved via any means. if the resource fully fits in the window, then this event cannot be invoked globale...
...And 3 more matches
Media buffering, seeking, and time ranges - Developer guides
this is usually contiguous but if the user jumps about while media is buffering, it may contain holes. ...
...this is usually contiguous but if the user jumps about while media is buffering, it may contain holes. ...
...s playable without delay — a good example of this is the buffered progress bar of an audio or video player. this article discusses how to build a buffer/seek bar using timeranges, and other features of the media api. buffered the buffered attribute will tell us which parts of the media has been downloaded. it returns a timeranges object, which will tell us which chunks of media have been downloaded. this is usually contiguous but if the user jumps about while media is buffering, it may contain holes. this will work with <audio> or <video>; for now let's consider a simple audio example: <audio id="my-audio" controls src="music.mp3"> </audio> we can access these attributes like so: var myaudio = document.getelementbyid('my-audio'); var bufferedtimeranges = myaudio.buffered; timeranges o...
...And 3 more matches
Content Security Policy (CSP) - HTTP
Web › HTTP › CSP
ictim's browser because the browser trusts the source of the content, even when it's not coming from where it seems to be coming from. csp makes it possible for server administrators to reduce or eliminate the vectors by which xss can occur by specifying the domains that the browser should consider to be valid sources of executable scripts. ...
...scripts loaded in source files received from those allowlisted domains, ignoring all other script (including inline scripts and event-handling html attributes). as an ultimate form of protection, sites that want to never allow scripts to be executed can opt to globally disallow script execution. mitigating packet sniffing attacks in addition to restricting the domains from which content can be loaded, the server can specify which protocols are allowed to be used; for example (and ideally, from a security standpoint), a server can specify that all content must be loaded using https. a complete data transmission security strategy includes not only enforcing https for data transfer, but also marking all cookies with the secure attribute and providing automatic redirects from http pages to their ...
...s only permitted from the document's origin, with the following exceptions: images may load from anywhere (note the "*" wildcard). media is only allowed from media1.com and media2.com (and not from subdomains of those sites). executable script is only allowed from userscripts.example.com. ...
...And 3 more matches
Index - HTTP
Web › HTTP › Headers › Index
cument'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 errors by the user agent. 32 csp: co...
...the apis that are restricted are: 33 csp: default-src csp, directive, http, reference, security the http content-security-policy (csp) default-src directive serves as a fallback for the other csp fetch directives. ...
...y (csp) default-src directive serves as a fallback for the other csp fetch directives. for each of the following directives that are absent, the user agent will look for the default-src directive and will use this value for it: 34 csp: font-src csp, directive, http, reference, security the http content-security-policy (csp) font-src directive specifies valid sources for fonts loaded using @font-face. 35 csp: form-action csp, directive, http, security the http content-security-policy (csp) form-action directive restricts the urls which can be used as the target of a form submissions from a given context. 36 csp: frame-ancestors csp, directive, http, security the http content-security-policy (csp) frame-ancestors directive specifies va...
...And 3 more matches
Large-Allocation - HTTP
the non-standard large-allocation response header tells the browser that the page being loaded is going to want to perform a large allocation. it is currently only implemented in firefox, but is harmless to send to every browser. webassembly or asm.js applications can use large contiguous blocks of allocated memory. for complex games, for example, these allocations can be quite large, sometimes as large as 1gb. the large-allocation tells the browser that the web content in the to-be-loaded page is going to want to perform a large contiguous memory allocation and the browser can react to this header by starting a dedicated process for the to-be-loaded document, for example. header type response header forbidden header name no syntax large-allocation: 0 large-all...
...0 0 is a special value which represents uncertainty as to what the size of the allocation is. <megabytes> the expected size of the allocation to be performed, in megabytes. examples large-allocation: 0 large-allocation: 500 troubleshooting errors the large-allocation header throws warnings or error messages when used incorrectly. you'll encounter them in the web console. this page was loaded in a new process due to a large-allocation header. this 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 red...
...uld 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 user-opened or noopener-opened tab or window. it can occur in these situations: the document with the large-allocation ...
...And 3 more matches
Mapping the width and height attributes of media container elements to their aspect-ratio - Web media technologies
this article explains a change that has occured 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 attribu...
...den 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 the image finally loaded you would get a noticeable jank in the page layout. this wasn't an attractive thing for your users to see, and could also result in performance issues due to the repainting required after each image loads, hence adding the attributes being a good idea. let’s move forward a few years to the era of responsive design. to keep images from breaking out of their containers when the container becomes...
...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 lev...
...And 3 more matches
Performance fundamentals - Web Performance
an the rule for rich applications. rich applications use dynamic content with animation and transition effects. transitions and animations are particularly important to applications: developers can use css to declare complicated behaviour with a simple, high-level syntax. in turn, gecko's graphics pipeline is highly optimized to render common animations efficiently. common-case animations are "offloaded" to the system compositor, which can render them in a performant, power-efficient fashion. an app's startup performance matters just as much as its runtime performance. gecko is optimized to load a wide variety of content efficiently: the entire web! many years of improvements targeting this content, like parallel html parsing, intelligent scheduling of reflows and image decoding, clever layout ...
...translate just as well to improving web applications on firefox. ...
...matters, and there's a "critical path" to each user-perceived event above. the critical path is exactly and only the code that must run to produce the event. for example, to paint an application's first frame that comprises visually some html and css to style that html: the html must be parsed the dom for that html must be constructed resources like images in that part of the dom have to be loaded and decoded the css styles must be applied to that dom the styled document has to be reflowed nowhere in that list is "load the js file needed for an uncommon menu"; "fetch and decode the image for the 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" ...
...And 3 more matches
Navigation and resource timings - Web Performance
describing at what time each point in the page loading process was reached. as displayed in the image below, the navigation process goes from navigationstart, unloadeventstart, unloadeventend, redirectstart, redirectend, fetchstart, domainlookupstart, domainlookupend, connectstart , connectend, secureconnectionstart, requeststart, responsestart, responseend, domloading, dominteractive, domcontentloadedeventstart, domcontentloadedeventend, domcomplete, loadeventstart, and loadeventend. with the metrics above, and a little bit of math, we can calculate many important metrics like time to first byte, page load time, dns lookup, and whether the connection is secure. to help measure the time it takes to complete all the steps, the performance timing api provides read only measurements of naviga...
...e unload event handler finishes. if there is no previous document, or if the previous document, or one of the needed redirects, is not of the same origin, the value returned is 0. dominteractive when the parser finished its work on the main document, that is when its document.readystate changes to 'interactive' and the corresponding readystatechange event is thrown. domcontentloadedeventstart right before the parser sent the domcontentloaded event, that is right after all the scripts that need to be executed right after parsing have been executed. domcontentloadedeventend right after all the scripts that need to be executed as soon as possible, in order or not, have been executed. domcomplete when the parser finished its work on the main document, ...
...akes the actual request and the servers return the requested assets. the browser then parses the content received, builds the dom, cssom, accessibility, and render trees, eventually rendering the page. once the user agent stops parsing the document, the user agent sets the document readiness to interactive. if there are deferred scripts needing to be parsed, it will do so, then fire the domcontentloaded, after which the readiness is set to complete. the document can now handle post-load tasks, after which point the document is marked as completely loaded. let navigationtimings = performance.getentriesbytype('navigation'); the performance.getentriesbytype('navigation')a returns an array of performanceentry objects for the navigation type. a lot can be garnered from these timing. in the above...
...And 3 more matches
content/symbiont - Archive of obsolete content
ns to load and configure content scripts from the loader, and functions to exchange messages between content scripts and the main add-on code from the worker. var { symbiont } = require('sdk/content/content'); var thing = symbiont.resolve({ constructor: '_init' }).compose({ constructor: function thing(options) { // `getmyframe` returns the host application frame in which // the page is loaded. this._frame = getmyframe(); this._init(options) } }); see the panel module for a real-world example of usage of this module. globals constructors symbiont(options) creates a content symbiont. parameters options : object optional options: name type frame object the host application frame in which the page is loaded. if frame is not provi...
... the host application frame in which the page is loaded. if frame is not provided hidden one will be created. contentscriptwhen string when to load the content scripts. this may take one of the following values: "start": load content scripts immediately after the document element for the page is inserted into the dom, but before the dom content itself has been loaded "ready": load content scripts once dom content has been loaded, corresponding to the domcontentloaded event "end": load content scripts once all the content (dom, js, css, images) for the page has been loaded, at the time the window.onload event fires this property is optional and defaults to "end". contentscriptoptions object read-only value exposed to...
.... defaults to true. optional. optional. symbiont symbiont is composed from the worker trait, therefore instances of symbiont and their descendants expose all the public properties exposed by worker along with additional public properties that are listed below: properties contentscriptfile the local file urls of content scripts to load. content scripts specified by this property are loaded before those specified by the contentscript property. contentscript the texts of content scripts to load. content scripts specified by this property are loaded after those specified by the contentscriptfile property. contentscriptwhen when to load the content scripts. this may have one of the following values: "start": load content scripts immediately after the document element for the pag...
...And 2 more matches
Listening to events in Firefox extensions - Archive of obsolete content
may come from any frame within the browser or, for a tabbrowser, any of the browsers within it. some of the more interesting dom events you may wish to monitor are listed here: event description domlinkadded dispatched when a new html <link> element is detected in the document. domtitlechanged dispatched when the title of the page changes. domcontentloaded dispatched when the initial dom for the page is completely loaded. load dispatched after the page—including images—has first finished loading. unload dispatched when the user has navigated away from the page. pageshow dispatched when a page is newly displayed. pagehide dispatched when a page is hidden. standard behavior for web pages i...
...spatched 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. if a page 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 pres...
...o 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 event this event works the same as the load event, except that it fires every time the page is loaded (whereas the load event doesn't fire in firefox 1.5 when the page is loaded from cache). the first time the page loads, the pageshow event fires just after the firing of the load event. the pageshow event uses a boolean property called persisted that is set to false on the initial load. it is set to true if it is not the initial load (in other words, it is set to true when the page is cached). s...
...And 2 more matches
Creating a Help Content Pack - Archive of obsolete content
the content pack descriptor file is written using rdf. if you don't know rdf, that's okay - for our purposes, you won't need to learn very much. if you understand the basics of html or (preferably) xml, you'll understand the 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 ...
...nt in order to query for further information (stored in child elements) about the content pack being parsed. nc:title is where you specify the title (e.g., "mozilla firefox help") for the help window. this attribute is required. nc:defaulttopic will hold the rdf:id of the topic you want displayed when the viewer first loads if none has been specified. this attribute also specifies what topic is loaded when the user hits the home button in the viewer. we'll get to exactly how to fill in this attribute later. this attribute is optional, with fallback to the value welcome. nc:base contains the base url relative to which the help content referenced in the descriptor file is located. for example, if your glossary, index, and table of contents rdf files are all located at chrome://myapp/locale/help...
...ame no matter which type you're defining, and the syntax is pretty simple. each panel is specified by one rdf:description element with the following attributes: nc:panelid specifies the name of the panel, which may be any one of glossary, search, toc, or index. the data source specified by toc will always be displayed, while the other data sources may only be available by searching through the loaded content pack. nc:datasources is a space-separated list of rdf datasources used in construction of the structure of referenced topics. generally, each item in the list will be a uri to an rdf file, but if you're more familiar with rdf you can also refer to a specific node within the rdf file using its rdf:id attribute. nc:platform (added in mozilla 1.8b2/firefox 1.1) when present specifies the p...
...And 2 more matches
New Security Model for Web Services - Archive of obsolete content
resources against requests from sandboxed scripts. this should especially be implemented for soap calls by untrusted scripts. when an attempt is made to access a resource at a previously-unknown uri, the sandbox reads a file at that domain with declarations to determine whether access is permitted to the script. if the file is not there, access is denied. the problem external untrusted scripts loaded behind a firewall are executed in a sandbox. these scripts may legitimately require access to external resources, but permitting them to access internal resources permits the compromise of these resources that would normally not be available to applications outside of the firewall. the sandbox must distinguish and protect internal resources. client-controlled solutions several client-controlled...
...legitimately require access to external resources, but permitting them to access internal resources permits the compromise of these resources that would normally not be available to applications outside of the firewall. the sandbox must distinguish and protect internal resources. client-controlled solutions several client-controlled solutions have been designed to prevent sandboxed applications loaded behind a firewall from compromising other resources protected behind the firewall. same source restriction by restricting sandboxed scripts to access only resources in the domain from which they were loaded, any script loaded from one domain into another is prevented from accessing resources in the domain into which it has been loaded. this policy has generally been successful in sandboxing jav...
... also, this technique prevents the script from accessing many legitimate external resources not provided in the same domain as the script. this prevents a script from accessing web services and data published from any domain besides its own. ...
...And 2 more matches
Binding Attachment and Detachment - Archive of obsolete content
on the element determines that a different binding should be attached, the old binding (and all bindings that it explicitly extends in its inheritance chain) will be detached. no bindings will be attached to elements that match the style rule, but are inside an element that has style display:none set. see bug 307098. whenever an element is removed from a document, any bindings attached via css loaded by the document will be detached. attachment using element.style property none of the xbl inheritance properties of element.style.mozbinding described here are implemented (if ever). bindings can be attached to elements through the scripting by assigning the element.style.mozbinding property. respectively bindings can be detached by setting element.style.mozbinding to empty string. note: so...
...in of s1 -> s2 -> s3 the resulting binding chain following the addition of the binding is d1 -> d2 -> d3 -> s1 -> s2 -> s3 the inheritance between d3 and s1 is implicit, meaning that there is no connection in the xbl documents between the two bindings. the inheritance link has been forged dynamically through the invocation of the element.style.mozbinding. <constructor> call as a document is loaded and style rules are matched for elements, any binding documents that are encountered will load as needed. binding document loads suppress the firing of the dom load event for the bound document. when the load event fires, and if all binding documents loaded successfully, it can be assumed that all bindings are attached to all elements in the page. for elements that are created during or after the...
... only fetched if no binding from the binding document has been used before in the bound document. a given bound document has a unique copy of each separate binding document that it uses. all bindings from the same binding document url that are used in a bound document will share the same binding document. ...
...And 2 more matches
A XUL Bestiary - Archive of obsolete content
s concept of a chrome as an integrated, dynamic thing in some way divorced from the "appcore" is realized in the use of the chrome url to point to chunks of xul and their related files. ...
...alized in the use of the chrome url to point to chunks of xul and their related files. the chrome url, which appears in place of the http url in pointers like the following global skin processing instruction: <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> specifies a chrome to be loaded by the gecko rendering engine. ...
... us-en/ navigator.dtd the default directory underneath each of these main package subdirectories is assumed in the chrome url (i.e. chrome://help/content/help.xul does not include a default directory as part of the url, though that directory exists in the actual structure). when you create different chrome for a package, you can create a subdirectory underneath content whose contents are loaded instead of default. for example, if you want to create a different skin for the navigator package, you can create a subdirectory underneath navigator/skin/ whose contents will be loaded instead of default's. so the following structure obtains: navigator/ content/ default/ navigator.xul ... skin/ default/ navigator.css nav-icon.gif ... mynewskin/ ...
...And 2 more matches
XUL Structure - Archive of obsolete content
and extensions. we'll look more at the syntax of a chrome url in the next section. it is important to note that when accessing content through a chrome url, it gains the enhanced privileges described above that other kinds of urls do not. for instance, an http url does not have any special privileges, and an error will occur if a web page tries, for example, to read a local file. however, a file loaded via a chrome url will be able to read files with the same access privileges as the installed extension. this distinction is important. this means that there are certain things that content of web pages cannot do, such as read the user's bookmarks. this distinction is not based on the kind of content being displayed; only on the type of url used. both html and xul placed on a web site have no ext...
...es with the same access privileges as the installed extension. this distinction is important. this means that there are certain things that content of web pages cannot do, such as read the user's bookmarks. this distinction is not based on the kind of content being displayed; only on the type of url used. both html and xul placed on a web site have no extra permissions; however both html and xul loaded through a chrome url have enhanced permissions. remote xul was disabled in firefox 8, so the following is of historic interest only. if you are going to use xul on a web site, you can just put the xul file on the web site as you would an html file, and then load its url in a browser http://localhost/xul.php. ensure that your web server is configured to send xul files with the content type of ap...
...documents since they aren't document type specific; however other features require the right kind of document. for instance, you can use the xul layout types in other documents since they don't rely on the xul document type to function. to summarize the points made above: mozilla renders both html and xul using the same underlying engine and uses css to specify their presentation. xul may be loaded from a remote site, from the local file system, or installed as a package and accessed using a chrome url. this last option is what browser extensions do. chrome urls may be used to access installed packages and open them with enhanced privileges. html, xml, and xul each have a different document type. some features may be used in any document type whereas some features are specific to one kind...
...And 2 more matches
Responsive images - Learn web development
uery. load the image referenced in the srcset list that has the same size as the slot or, if there isn't one, the first image that is bigger than the chosen slot size. and that's it! at this point, if a supporting browser with a viewport width of 480px loads the page, the (max-width: 600px) media condition will be true, and so the browser chooses the 480px slot. the elva-fairy-480w.jpg will be loaded, as its inherent width (480w) is closest to the slot size. the 800px picture is 128kb on disk, whereas the 480px version is only 63kb — a saving of 65kb. now, imagine if this was a page that had many pictures on it. using this technique could save mobile users a lot of bandwidth. note: when testing this with a desktop browser, if the browser fails to load the narrower images when you've got i...
...ook at what the viewport is (you can approximate it by going into the browser's javascript console and typing in document.queryselector('html').clientwidth). different browsers have minimum sizes that they'll let you reduce the window width to, and they might be wider than you'd think. when testing it with a mobile browser, you can use tools like firefox's about:debugging page to inspect the page loaded on the mobile using the desktop developer tools. to see which images were loaded, you can use firefox 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="view...
...o 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 allow the browser to choose an appropriate resolution image by using srcset with x-descriptors and without sizes — a somewhat easier synt...
...And 2 more matches
Client-side storage - Learn web development
the name item returned. now close down the browser and open it up again. enter the following lines again: let myname = localstorage.getitem('name'); myname you should see that the value is still available, even though the browser has been closed and then opened again. separate storage for each domain there is a separate data store for each domain (each separate web address loaded in the browser). you will see that if you load two websites (say google.com and amazon.com) and try storing an item on one website, it won't be available to the other website. this makes sense — you can imagine the security issues that would arise if websites could see each other's data! a more involved example let's apply this new-found knowledge by writing a simple working example to give ...
... h1.textcontent = 'welcome to our website '; personalgreeting.textcontent = 'welcome to our website. we hope you have fun while you are here.'; // hide the 'forget' part of the form and show the 'remember' part forgetdiv.style.display = 'none'; rememberdiv.style.display = 'block'; } } last but not least, we need to run the namedisplaycheck() function every time the page is loaded. if we don't do this, then the personalized greeting will not persist across page reloads. add the following to the bottom of your code: document.body.onload = namedisplaycheck; your example is finished — well done! all that remains now is to save your code and test your html page in a browser. you can see our finished version running live here. note: there is another, slightly more co...
...= webmurl; source2.type = 'video/webm'; ... } offline asset storage the above example already shows how to create an app that will store large assets in an indexeddb database, avoiding the need to download them more than once. this is already a great improvement to the user experience, but there is still one thing missing — the main html, css, and javascript files still need to be downloaded each time the site is accessed, meaning that it won't work when there is no network connection. this is where service workers and the closely-related cache api come in. a service worker is a javascript file that, simply put, is registered against a particular origin (web site, or part of a web site at a certain domain) when it is accessed by a browser. when registered, it can control pages av...
...And 2 more matches
Multimedia: Images - Learn web development
in terms of download performance, eliminating media, and reducing file size is the low-hanging fruit. this article looks at optimizing image and video to improve web performance. prerequisites: basic computer literacy, basic software installed, and basic knowledge of client-side web technologies. objective: to learn about the various image formats, their impact on performance, and how to reduce the impact of images on overall page load time. ...
...nt. you need to be considerate of data usage. many people are on capped data plans or even pay-as-you-go where they are literally paying by the megabyte. this isn't an emerging market problem either. as of 2018, 24% of the united kingdom still use pay-as-you-go. you also need to be considerate of memory as many mobile devices have limited ram. it's important to remember that when images are downloaded, they need 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 exper...
...ange 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 and nowadays supported by all major browsers except safari. supports transparency and...
...And 2 more matches
Tracking Protection
if blocked content is part of the page layout, users may notice layout issues where firefox blocked these loads. sometimes users won’t notice at all, if the page grid works such that other page elements slide in to fill holes left by blocked elements. ...
...elements slide in to fill holes left by blocked elements. when firefox blocks content, it logs a message to the web console like this: the resource at "http://some/url" was blocked because tracking protection is enabled. note that with firefox for android, you can access console output using the remote debugger. click the ⓘ symbol in the address bar to view information about the currently loaded page. the popup that appears will notify you when content has been blocked. you will also be able to disable tracking protection entirely if you choose by accessing the tracking settings. if tracking cookies were present, you would be able to view the list by clicking on "blocking tracking cookies" in the above image to view the following popup: you can click "manage content blocking" to cha...
...ntirely if you choose by accessing the tracking settings. if tracking cookies were present, you would be able to view the list by clicking on "blocking tracking cookies" in the above image to view the following popup: you can click "manage content blocking" to change the blocking settings: how does firefox choose what to block? content is blocked based on the domain from which it is to be loaded. firefox ships with a list of sites which have been identified as engaging in cross-site tracking of users. when tracking protection is enabled, firefox blocks content from sites in the list. sites that track users are most commonly third-party advertising and analytics sites. what does this mean for your website? most obviously, it means that when tracking protection is enabled: content s...
...And 2 more matches
HTTP Cache
. this consumer, from the point of view the cache, takes a role of the writer. other parallel consumers, if any, are blocked until the writer calls setvalid on the cache entry. the consumer is then responsible to validate the partial content cache entry with the network server. the server responses with a 200 response which means the cached content is no longer valid and a new version must be loaded from the network. the writer then calls recreate on the cache entry. this returns a new empty entry to write the meta data and data to, the writer exchanges its cache entry by this new one and handles it as a new one. the writer then (in this order) fills the necessary meta data of the cache entry, opens the output stream on it and calls metadataready on it. any other pending openers, if any, ...
...loadcontextinfo 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...
...ck keeps a strong reference to the opener plus the opening flags. ...
...And 2 more matches
AddonManager
lback() 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. state_installed an install that has successfully been inst...
...ocess of being installed. state_installed an install that has successfully been installed. state_install_failed an install that has failed to install. state_cancelled an install that has been canceled. addoninstall errors constant description error_network_failure a network error occurred. error_incorrect_hash the downloaded file did not match the expected hash. error_corrupt_file the file appears to be corrupt. error_file_access there was an error accessing the filesystem. error_signedstate_required the addon must be signed and isn't. update check reasons constant description update_when_user_requested an update check performed at the explicit reque...
... promise? getinstallforfile( in nsifile file, in installcallback? callback, in stri...
...And 2 more matches
Application Translation with Mercurial
and then the directory structure like on windows, but using slashes (/) instead of backslashes (\). so let's go to c:\mozilla by typing cd /c/mozilla/ create a new directory for the source code: mkdir mozilla-aurora initialize the new directory as new repository: hg init mozilla-aurora go into the new directory: cd mozilla-aurora unpack the source code: hg unbundle /path/to/the/downloaded/mozilla-aurora.hg this can take some time, mostly depending on the performance of the hard drive. extract the files: hg update obtaining the texts of your localization go back to the parent folder of mozilla-aurora: cd .. find the localization repository for your branch and language on http://hg.mozilla.org/ e.g. for aurora and german (language code 'de'), it is http://hg.mozilla.org...
... lastname <mynick@example.com> merge = internal:merge [alias] qexport = export -g -r qtip qexportall = diff -r qparent [defaults] commit = -v diff = -p -u 8 qdiff = -p -u 8 qnew = -u [diff] git = 1 showfunc = 1 unified = 8 [extensions] hgext.mq = progress = [hooks] put in your name and email address which later will be public on the internet after your translation patch got accepted and uploaded. save the file and close it. enabling mercurial queues (revertable patches) some time will pass between the moment in which you start the localization, finish it, test it, improve it, upload it for review and get review (maybe not approved on first try). other localizers will likely have done changes to the translation, either adding new texts, removing obsolete ones or improving the current te...
...d your locale and have the same text, and how many are missing in your local. the interesting part follows below as list of missing texts. the first line shows the locale for which the texts are being translated (in this example: de - german). with the second line start the file paths of the files which require changes. the file paths follow the directory structure of the locale repository downloaded for translation. in this example, the file aboutdialog can be found in the folder browser/chrome/browser/. the text striked through are texts which have been removed in the english version and can also be removed from the locale being worked on. in this example we will translate the one new text with the id privatebrowsingpage.howtostart4 in the file aboutprivatebrowsing.dtd. tips for finding fi...
...And 2 more matches
NSS Certificate Download Specification
scribed above can contain several certificates. when nss's certificate decoder encounters one of these collections of multiple certificates they are handled in the following way: the first certificate is processed in a context specific manner, depending upon how it is being imported. for mozilla browsers, this handling will depend upon the mime content-type that is used on the object being downloaded. for nss-based servers it will depend upon the options selected in the server's administration interface. subsequent certificates are all treated the same. if the certificates contain a basicconstraints certificate extension that indicates they are ca certificates, and do not already exist in the local certificate database, they are added as untrusted cas. in this way they may be used for cer...
... chain validation, as long as there is a trusted ca somewhere along the chain. importing certificates into mozilla browsers mozilla browsers import certificates found in http protocol responses. there are several mime content types that are used to indicate to the browser what type of certificate is being imported. these mime types are: application/x-x509-user-cert the certificate being downloaded is a user certificate belonging to the user operating the browser. if the private key associated with the certificate does not exist in the user's local key database, then an error dialog is generated and the certificate is not imported. if a certificate chain is being imported then the first certificate in the chain must be the user certificate, and any subsequent certificates will be added as u...
... the certificate does not exist in the user's local key database, then an error dialog is generated and the certificate is not imported. if a certificate chain is being imported then the first certificate in the chain must be the user certificate, and any subsequent certificates will be added as untrusted ca certificates to the local database. application/x-x509-ca-cert the certificate being downloaded represents a certificate authority. when it is downloaded the user will be shown a sequence of dialogs that will guide them through the process of accepting the certificate authority and deciding if they wish to trust sites certified by the ca. if a certificate chain is being imported then the first certificate in the chain must be the ca certificate, and any subsequent certificates will be added...
...And 2 more matches
PKCS11 FAQ
Mozilla › Projects › NSS › PKCS11 › FAQ
ertificates. if your token is read/write and has only one session, nss will open that one initial session read/write. what permanent pkcs #11 objects are used by nss or read from the token? example: rsa private key, ca certificate, user's own certificate, user's name. private keys (rsa and dsa) and the corresponding certificates are read from the token. other certificates on the token are also loaded (to allow building certificate chains), but it's not necessary to include the full chain, as long as the full chain is available in the regular certificate database. for the sake of completeness, it's also a good idea to expose public key objects. nss falls back to looking for for the existance of public keys to determine if the token may have the corresponding private key while the token is not ...
...erate all the permanment certificates in a token (cka_token set to true). private keys must have the same cka_id value as their corresponding certificate, and this value must be unique on the token. orphaned keys have a cka_id generated from some part of the public key. this value is set when the key is generated, so that nss will be able to find the key when the certificate for that key is loaded. this case is interesting only for read/write tokens. what labels does nss use to identify certificates? nss can use the cka_label attribute to identify user certificates (see previous question) and presents this label to the user. therefore, each user certificate must have some label associated with it. the label for a token certificate is presented to the user as follows:token label :ce...
...your token implements. if you do not actually do the operation specified by that function, you can return ckr_function_not_supported. will nss get the user's ca certificate via pkcs #11 and push it into the ca certificate database or is the ca certificate database expected to obtain the ca certificate by some other means? pkcs #11 certificates that have private keys associated with them are are loaded into the temporary database (in memory) and marked as user certificates. all other certificates in the module are loaded into the temporary database with no special trust bits associated with them. nss is perfectly capable of using token certificates in place. which function does nss use to get login state information? nss calls c_getsessioninfo to get the login/logout state. nss never attempts...
...And 2 more matches
NSS tools : signtool
rds you can use the -m option to list the pkcs #11 modules, including smart cards, that are available to signtool: signtool -d "c:\netscape\users\jsmith" -m using certificate directory: c:\netscape\users\username listing of pkcs11 modules ----------------------------------------------- 1. netscape internal pkcs #11 module (this module is internally loaded) slots: 2 slots attached status: loaded slot: communicator internal cryptographic services version 4.0 token: communicator generic crypto svcs slot: communicator user private key and certificate services token: communicator certificate db 2. cryptos (this is an exter...
...to sign with a smart card, you supply only the fully qualified name of the certificate. ...
... signtool -k "mycard:my signing cert" directory verifying fips mode use the -m option to verify that you are using the fips-140-1 module. signtool -d "c:\netscape\users\jsmith" -m using certificate directory: c:\netscape\users\jsmith listing of pkcs11 modules ----------------------------------------------- 1. ...
...And 2 more matches
nsIUpdatePrompt
eservice.idlscriptable this interface describes an object that can be used to show various update-related notifications to the user. 1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) method overview void checkforupdates(); void showupdateavailable(in nsiupdate update); void showupdatedownloaded(in nsiupdate update, [optional] in boolean background); void showupdateerror(in nsiupdate update); void showupdatehistory(in nsidomwindow parent); void showupdateinstalled(); methods checkforupdates() presents a user interface that checks for and displays the available updates. void checkforupdates(); parameters none. showupdateavailable() shows a message advising the user that an updat...
...tional] in boolean background); void showupdateerror(in nsiupdate update); void showupdatehistory(in nsidomwindow parent); void showupdateinstalled(); methods checkforupdates() presents a user interface that checks for and displays the available updates. void checkforupdates(); parameters none. ...
...forupdates(); parameters none. showupdateavailable() shows a message advising the user that an update is available to be downloaded and installed. if the app.update.silent preference is true or the user interface is already displayed the call will be a no-op. void showupdateavailable( in nsiupdate update ); parameters update an nsiupdate describing the update that's available. showupdatedownloaded() shows a message advising the user that an update has been downloaded, and that the user should restart the application in order to install it. ...
...And 2 more matches
nsIWebProgressListener
void onstatechange(in nsiwebprogress awebprogress, in nsirequest arequest, in unsigned long astateflags, in nsresult astatus); void onstatuschange(in nsiwebprogress awebprogress, in nsirequest arequest, in nsresult astatus, in wstring amessage); constants state transition flags these flags indicate the various states that requests may transition through as they are being loaded. these flags are mutually exclusive. for any given request, onstatechange() is called once with the state_start flag, zero or more times with the state_transferring flag or once with the state_redirecting flag, and then finally once with the state_stop flag. note: for document requests, a second state_stop is generated (see the description of state_is_window for more details). constan...
...of these flags). constant value description state_restoring 0x01000000 this flag indicates that the state transition corresponds to the start or stop of activity for restoring a previously-rendered presentation. as such, there is no actual network activity associated with this request, and any modifications made to the document or presentation when it was originally loaded will still be present. state security flags these flags describe the security state reported by a call to the onsecuritychange() method. these flags are mutually exclusive. constant value description state_is_insecure 0x00000004 this flag indicates that the data corresponding to the request was received over an insecure channel. state_is_broken ...
...d by a call to the onsecuritychange() method. these flags are mutually exclusive. constant value description state_is_insecure 0x00000004 this flag indicates that the data corresponding to the request was received over an insecure channel. state_is_broken 0x00000001 this flag indicates an unknown security 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. state_is_secure 0x00000002 this flag indicates that the data corresponding to the request was received over a secure channel. the degree of security is expressed by state_secure_high, state_secure_med, or state_secure_low. security strength flags these flags describe the security strength and acc...
...And 2 more matches
about:debugging - Firefox Developer Tools
type about:debugging in the firefox url bar. in the tools > web developer menu, click remote debugging. when about:debugging opens, on the left-hand side, you'll see a sidebar with two options and information about your remote debugging setup: setup use the setup tab to configure the connection to your remote device. this firefox provides information about temporary extensions you have loaded for debugging, extensions that are installed in firefox, the tabs that you currently have open, and service workers running on firefox. if your about:debugging page is different from the one displayed here, go to about:config, find and set the option devtools.aboutdebugging.new-enabled to true. setup tab connecting to a remote device firefox supports debugging over usb with android devices...
...out:debugging page. enter the location and port on which the debugger server is running. when you do, it is added to the network locations list along with the devices, as shown below: this firefox the this firefox tab combines the features of extensions, tabs, and workers into a single tab with the following sections: temporary extensions displays a list of the extensions that you have loaded using the load temporary add-on button. extensions this section lists information about the extensions that you have installed on your system. service workers, shared workers, 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 de...
...eader. you don't have to package or sign the extension before loading it, and it stays installed until you restart firefox. 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. once you have loaded a temporary extension, you can see information about it and perform operations on it. you can use the following buttons: inspect loads the extension in the debugger. reload reloads the temporary extension. this is handy when you have made changes to the extension. remove unloads the temporary extension. other information about the extension is displayed: location the location of ...
...And 2 more matches
HTMLImageElement.complete - Web APIs
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 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 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. ...
...And 2 more matches
HTML attribute reference - HTML: Hypertext Markup Language
obal attribute sets whether input is automatically capitalized when entered by user autocomplete <form>, <input>, <select>, <textarea> indicates whether controls in this form can by default have their values automatically completed by the browser. autofocus <button>, <input>, <keygen>, <select>, <textarea> the element should be automatically focused after the page loaded. autoplay <audio>, <video> the audio or video should play as soon as possible. background <body>, <table>, <td>, <th> specifies the url of an image file. note: although browsers and email clients may still support this attribute, it is obsolete. use css background-image instead. bgcolor <body>, <col>, <colgroup>, <marquee>, <table>, <tbody>, <tfoo...
... checked <command>, <input> indicates whether the element should be checked on page load. cite <blockquote>, <del>, <ins>, <q> contains a uri which points to the source of the quote or change. class global attribute often used with css to style elements with common properties. code <applet> specifies the url of the applet's class file to be loaded and executed. codebase <applet> this attribute gives the absolute or relative url of the directory where applets' .class files referenced by the code attribute are stored. color <basefont>, <font>, <hr> this attribute sets the text color using either a named color or a color specified in the hexadecimal #rrggbb format. note: this is a legacy attribute.
.... 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. low <meter> indicates the upper bound of the lower ran...
...And 2 more matches
Using the application cache - HTML: Hypertext Markup Language
for each file fetched into this temporary cache, the browser sends a progress event to the applicationcache object. if any errors occur, the browser sends an error event, and the update halts. once all the files have been successfully retrieved, they are moved into the real offline cache automatically, and a cached event is sent to the applicationcache object. since the document has already been loaded into the browser from the cache, the updated document will not be rendered until the document is reloaded (either manually or programatically). storage location and clearing the offline cache in chrome you can clear the offline cache by selecting "clear browsing data..." in the preferences or by visiting chrome://appcache-internals/. safari has a similar "empty cache" setting in its preference...
...o inform the browser a new manifest is available. sections in a cache manifest file: cache, network, and fallback a manifest can have three distinct sections: cache, network, and fallback. cache: this is the default section for entries in a cache manifest file. files listed under the cache: section header (or immediately after the cache manifest line) are explicitly cached after they're downloaded for the first time. network: files listed under the network: section header in the cache manifest file are white-listed resources that require a connection to the server. all requests to such resources bypass the cache, even if the user is offline. the wildcard character * can be used once. most sites need *. fallback: the fallback: section specifies fallback pages the browser should use if a...
...as a master entry. explicit entries explicit entries are resources that are explicitly listed in the cache section of a cache manifest file. network entries the network section of a cache manifest file specifies resources for which a web application requires online access. network entries in an application cache are essentially an "online whitelist"—uris specified in the network section are loaded from the server instead of the cache. this lets the browser's security model protect the user from potential security breaches by limiting access to approved resources. as an example, you can use network entries to load and execute scripts and other code from the server instead of the cache: cache manifest network: /api the cache manifest section listed above ensures that requests to load res...
...And 2 more matches
CSP: script-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. ...
...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. 'strict-dynamic' the strict-dynamic source expression specifies 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 allow-list or source expressions such as 'self' or 'unsafe-inline' are ignored. see script-src for an example. 'report-sample' requires a sample of the violating code to be included in the violation report. examples violation case given this csp header: content-security-policy: script-src https://example.com/ the following script is blocked...
...script. at the same time, any allow-list or source expressions such as 'self' or 'unsafe-inline' are ignored. see script-src for an example. 'report-sample' requires a sample of the violating code to be included in the violation report. ...
...And 2 more matches
Content-Security-Policy - HTTP
article on content security policy (csp). header type response header forbidden header name no syntax content-security-policy: <policy-directive>; <policy-directive> where <policy-directive> consists of: <directive> <value> with no internal punctuation. directives fetch directives fetch directives control the locations from which certain resource types may be loaded. ...
...bidden header name no syntax content-security-policy: <policy-directive>; <policy-directive> where <policy-directive> consists of: <directive> <value> with no internal punctuation. directives fetch directives fetch directives control the locations from which certain resource types may be loaded. child-src defines the valid sources for web workers and nested browsing contexts loaded using elements such as <frame> and <iframe>. instead of child-src, if you want to 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 loa...
... sources for worker, sharedworker, or serviceworker scripts. document directives document directives govern the properties of a document or worker environment to which a policy applies. base-uri restricts the urls which can be used in a document's <base> element. plugin-types restricts the set of plugins that can be embedded into a document by limiting the types of resources which can be loaded. sandbox enables a sandbox for the requested resource similar to the <iframe> sandbox attribute. navigation directives navigation directives govern to which locations a user can navigate or submit a form, for example. form-action restricts the urls which can be used as the target of a form submissions from a given context. frame-ancestors specifies valid parents that may embed a page u...
...And 2 more matches
Communicating With Other Scripts - Archive of obsolete content
this page is now obsolete, and its content has been incorporated into the main page on content scripts. ...
...scripts (that is, scripts embedded in the web page or included using <script> tags) main.js your content scripts can communicate with your add-on's "main.js" (or any other modules you're written for your add-on) by sending it messages, using either the port.emit() api or the postmessage() api. see the articles on using postmessage() and using port for details. ...
...e written for your add-on) by sending it messages, using either the port.emit() api or the postmessage() api. see the articles on using postmessage() and using port for details. content scripts content scripts loaded into the same document at the same time using the same method can interact with each other directly as well as with the web content itself. however, content scripts which have been loaded into different documents cannot interact directly with each other. content scripts that have been loaded into the same document by different methods, or the same method called more than once, can pass messages directly to each other using the dom postmessage() api or a customevent. any two content scripts can communicate by using the main add-on script to manually relay messages between the cont...
...ds a script into each one, they can't interact with each other. but, they can each communicate with the main add-on script which could be written to relay messages between them. if an add-on creates a single page-mod object and loads several content scripts into the page mod, then only content scripts associated with the same page can interact with each other: if two different matching pages are loaded, content scripts attached to page a cannot interact with those attached to page b. if an add-on loads two or more content scripts into the same page, or panel, using two different method (e.g. a page-mod and a context-menu) they can directly communicate by dispatching and listening for customevents on dom objects they can access (e.g. the window object). this is true as long as both context scri...
Loading Content Scripts - Archive of obsolete content
ing, array contentscriptwhen string contentscriptoptions object we have already seen the contentscript option, which enables you to pass in the text of the script itself as a string literal. this version of the api avoids the need to maintain a separate file for the content script. the contentscriptfile option enables you to pass in the local file url from which the content script will be loaded. to supply the file "my-content-script.js", located in the /data subdirectory under your add-on's root directory, use a line like: // "data" is supplied by the "self" module var data = require("sdk/self").data; ... contentscriptfile: data.url("my-content-script.js") both contentscript and contentscriptfile accept an array of strings, so you can load multiple scripts, which can also interact di...
...both contentscript and contentscriptfile accept an array of strings, so you can load multiple scripts, which can also interact directly with each other in the content process: // "data" is supplied by the "self" module var data = require("sdk/self").data; ... contentscriptfile: [data.url("jquery-1.4.2.min.js"), data.url("my-content-script.js")] scripts specified using contentscriptfile are loaded before those specified using contentscript. this enables you to load a javascript library like jquery by url, then pass in a simple script inline that can use jquery. unless your content script is extremely simple and consists only of a static string, don't use contentscript: if you do, you may have problems getting your add-on approved on amo. instead, keep the script in a separate file and l...
...your content script is extremely simple and consists only of a static string, don't use contentscript: if you do, you may have problems getting your add-on approved on amo. instead, keep the script in a separate file and load it using contentscriptfile. this makes your code easier to maintain, secure, debug and review. the contentscriptwhen option specifies when the content script(s) should be loaded. it takes one of three possible values: "start" loads the scripts immediately after the document element for the page is inserted into the dom. at this point the dom content hasn't been loaded yet, so the script won't be able to interact with it. "ready" loads the scripts after the dom for the page has been loaded: that is, at the point the domcontentloaded event fires. at this point,...
... 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. ...
Content Processes - Archive of obsolete content
es, and scripts in one process cannot interact directly with scripts in another. we can, however, pass json messages between scripts in different processes. the solution we've come up with is to introduce the notion of content scripts. a content script is a script that is injected into a content process by the main script running in the add-on process. content scripts differ from scripts that are loaded by the page itself in that they are provided with a messaging api that can be used to send messages back to the add-on script. event emitters the messaging api we use to send json messages between scripts in different processes is based on the use of event emitters. an event emitter maintains a list of callbacks (or listeners) for one or more named events. each event emitter has several methods...
...ker is an object that is used to inject content scripts into a content process, and to provide a pipe between each content script and the main add-on script. the idea is to use a single content worker for each content process. the constructor for the content worker takes an object containing one or more named options. among other things, this allows us to specify one or more content scripts to be loaded. when a content script is first loaded, the content worker automatically imports a messaging api that allows it to emit messages over a pipe. on the add-on side, this pipe is exposed via the the port property on the worker. in addition to the port property, workers also support the web worker api, which allows scripts to send messages to each other using the postmessage function. this function u...
...the worker. in addition to the port property, workers also support the web worker api, which allows scripts to send messages to each other using the postmessage function. this function uses the same pipe internally, and causes a 'message' event to be emitted on the other side. as explained earlier, firefox doesn't yet use separate processes for tabs or add-ons, so instead, each content script is loaded in a sandbox. sandboxes were explained this article. accessing the dom the global for the content sandbox has the window object as its prototype. this allows the content script to access any property on the window object, even though that object lives outside the sandbox. recall that the window object inside the sandbox is actually a wrapper to the real object. a potential problem with the...
...e property is defined on the underlying object, rather than the wrapper itself. this feature should only be used when you really need it, however. a few notes on security as we stated earlier, the sdk was designed with multiprocess support in mind, despite the fact that work on implementing this in firefox has currently been suspended. since both add-on modules and content scripts are currently loaded in sandboxes rather than separate processes, and sandboxes can communicate with each other directly (using imports/exports), you might be wondering why we have to go through all the trouble of passing messages between add-on and content scripts. the reason for this extra complexity is that the code for add-on modules and content scripts have different privileges. every add-on module can get chrom...
Porting the Library Detector - Archive of obsolete content
d candidate for porting because there are suitable sdk apis for all its features. the add-on is paul bakaus's library detector. the library detector tells you which javascript frameworks the current web page is using. it does this by checking whether particular objects that those libraries add to the global window object are defined. for example, if window.jquery is defined, then the page has loaded jquery. for each library that it finds, the library detector adds an icon representing that library to the status bar. it adds a tooltip to each icon, which contains the library name and version. you can browse and run the ported version in the sdk's examples directory. how the library detector works all the work is done inside a single file, librarydetector.xul this contains: a xul overla...
...script is an array of test objects, one for each library. each test object contains a function called test(): if the function finds the library, it defines various additional properties for the test object, such as a version property containing the library version. each test also contains a chrome:// url pointing to the icon associated with its library. the script listens to gbrowser's domcontentloaded event. when this is triggered, the testlibraries() function builds an array of libraries by iterating through the tests and adding an entry for each library which passes. once the list is built, the switchlibraries() function constructs a xul statusbarpanel element for each library it found, populates it with the icon at the corresponding chrome:// url, and adds it to the box. finally, it liste...
...erimental unsafewindow. the main add-on script, main.js, will use a page-mod to inject the content script into every new page. the content script, which we'll call library-detector.js, will keep most of the logic of the test functions intact. ...
...h(function(library) { if (worker.tab.libraries.indexof(library) == -1) { worker.tab.libraries.push(library); } }); if (worker.tab == tabs.activetab) { updatewidgetview(worker.tab); } }); } }); the content script is executed once for every window.onload event, so it will run multiple times when a single page containing multiple iframes is loaded. so main.js needs to filter out any duplicates, in case a page contains more than one iframe, and those iframes use the same library. implementing the user interface showing the library array the widget module is a natural fit for displaying the library list. we'll specify its content using html, so we can display an array of icons. the widget must be able to display different content for diff...
content/worker - Archive of obsolete content
worker. parameters options : object required options: name type window object the content window to create javascript sandbox for communication with. optional options: name type contentscriptfile string,array the local file urls of content scripts to load. content scripts specified by this option are loaded before those specified by the contentscript option. optional. contentscript string,array the texts of content scripts to load. content scripts specified by this option are loaded after those specified by the contentscriptfile option. optional. onmessage function functions that will registered as a listener to a 'message' events. onerror...
...gistered as a listener to an 'error' events. worker worker is composed from the eventemitter trait, therefore instances of worker and their descendants expose all the public properties exposed by eventemitter along with additional public properties that are listed below. methods postmessage(data) asynchronously emits "message" events in the enclosed worker, where content script was loaded. parameters data : number,string,json the data to send. must be stringifiable to json. destroy() destroy the worker by removing the content script from the page and removing all registered listeners. a detach event is fired just before removal. properties port object that allows you to: send customized messages to the worker using the port.emit function receive events from the worker ...
... value : the event listener is passed the message, which must be a json-serializable value. error this event allows the content worker to react to an uncaught runtime script error that occurs in one of the content scripts. arguments error : the event listener is passed a single argument which is an error object. ...
...ich is an error object. detach this event is emitted when the document associated with this worker is unloaded or the worker's destroy() method is called. note that you can't communicate with the content script in response to this event. if you try, you'll see this error: error: couldn't find the worker to receive this message. ...
loader/sandbox - Archive of obsolete content
experimental create javascript sandboxes and execute scripts in them. usage create a sandbox to create a sandbox: const { sandbox, evaluate, load } = require("sdk/loader/sandbox"); let scope = sandbox('http://example.com'); the argument passed to the sandbox defines its privileges. the argument may be: a url string, in which case the sandbox will get the same privileges as a script loaded from that url a dom window object, to inherit privileges from the window being passed. omitted or null: then the sandbox will have chrome privileges giving it access to all the xpcom components. optionally the sandbox function can be passed a second argument (see sandbox documentation on mdn for details). evaluate code module provides evaluate function that lets you execute code in the given s...
...ox function can be passed a second argument (see sandbox documentation on mdn for details). evaluate code module provides evaluate function that lets you execute code in the given sandbox: evaluate(scope, 'var a = 5;'); evaluate(scope, 'a + 2;'); //=> 7 more details about evaluated script may be passed via optional arguments that may improve 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...
...th/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 argument can be: a uri string, giving the sandbox the same privileges as a script loaded from that url a dom window object, giving the sandbox the same privileges as the dom window null, to give the sandbox chrome privileges. returns sandbox : a sandbox in which you can evaluate and load javascript. evaluate(sandbox, code, uri, line, version) evaluate code in sandbox, and return the result. parameters sandbox : sandbox the sandbox to use. code : string the code to execute...
... the same privileges as the dom window null, to give the sandbox chrome privileges. returns sandbox : a sandbox in which you can evaluate and load javascript. evaluate(sandbox, code, uri, line, version) evaluate code in sandbox, and return the result. parameters sandbox : sandbox the sandbox to use. code : string the code to execute. uri : string evaluate the code as if it were being loaded from the given uri. optional. line : number evaluate the code starting at this line. optional, defaults to 1. version : string evaluate the code using this version of javascript. defaults to 1.8. returns result : returns whatever the evaluated code returns. load(sandbox, uri) evaluate code from uri in sandbox. parameters sandbox : sandbox the sandbox to use. uri : string the url poin...
platform/xpcom - Archive of obsolete content
ogger = wrapper.wrappedjsobject; logger.log('a timestamped message'); by default, services are registered and unregistered automatically. to learn more about this, see registering and unregistering. registering and unregistering by default, factories and services are registered with xpcom automatically when they are created, and unregistered automatically when the add-on that created them is unloaded. you can override this behavior using the register and unregister options to the factory or service constructor: var xpcom = require('sdk/platform/xpcom'); var factory = xpcom.factory({ contract: contractid, component: helloworld, register: false, unregister: false, }); if you disable automatic registration in this way, you can use the register() function to register factories and ser...
...s id property. register boolean by default, the factory is registered as soon as it is constructed. by including this option, set to false, the factory is not automatically registered and you must register it manually using the register() function. unregister boolean by default, the factory is unregistered as soon as the add-on which created it is unloaded. by including this option, set to false, the factory is not automatically unregistered and you must unregister it manually using the unregister() function. functions register(factory) register the factory or service supplied. if the factory or service is already registered, this function throws components.results.ns_error_factory_exists. by default, factories and services are regist...
...lly, so you should only call register() if you have overridden the default behavior. parameters factory : object the factory or service to register. unregister(factory) unregister the factory or service supplied. if the factory or service is not registered, this function does nothing. by default, factories and services are unregistered automatically when the add-on that registered them is unloaded. parameters factory : object the factory or service to unregister. isregistered(factory) find out whether a factory or service is registered. parameters factory : object returns boolean : true if the factory or service is registered, false otherwise. autoregister(path) register a component (.manifest) file or all component files in a directory. see nsicomponentregistrar.autoregister() ...
...satisfies the nsisupports interface. the contract id and/or class id may be used by xpcom clients to retrieve the factory. if a class id is not given, a new one will be generated. the contract id and class id are accessible as the values of the contract and id properties, respectively. by default, the factory is registered when it is created and unregistered when the add-on that created it is unloaded. to override this behavior, you can pass register and/or unregister options, set to false. if you do this, you can use the register() and unregister() functions to register and unregister. methods createinstance(outer, iid) creates an instance of the component associated with this factory. parameters outer : null this argument must be null, or the function throws cr.ns_error_no_aggregation...
remote/parent - Archive of obsolete content
r own module loader so they can load other sdk modules. its primary purpose is to help build apis. if you just need to access a web page, use sdk/page-mod to load a content script instead. terms process every application has at least one process running, the main process that displays the ui. multiprocess applications 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. 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 chang...
...ads 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 those used for communication with content scripts. the sdk/remote/parent module provides port objects for the parent's end of the conversation, and the sdk/remote/child module provides port objects for the child's end. // remote.js const ...
...multiprocess firefox restricts the things that code running in child processes is allowed to do. for example, when the child process is sandboxed, modules won't be able to access the file system. we don't yet have a full list of all the modules that a module in the child process can't load, but the ...
.../ main.js const { processes, remoterequire } = require("sdk/remote/parent"); remoterequire("./remote.js", module); processes.port.emit("message-from-main", "hello from main"); processes.port.on("message-from-remote", function(process, message) { console.log("remote says: " + message); }); child process privileges a module loaded into a child process can't do everything that the same module loaded into the parent process can. multiprocess firefox restricts the things that code running in child processes is allowed to do. for example, when the child process is sandboxed, modules won't be able to access the file system. we don't yet have a full list of all the modules that a module in the child process can't load, but the sorts of things listed in limitations of frame scripts broadly apply.
window/utils - Archive of obsolete content
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'); this function wraps nsiwindowwatcher.openwindow. parameters uri : string uri of the document to be loaded into the window. only chrome, resource, and data schemes are accepted. options : object options for the function, with the following properties: name type parent nsidomwindow parent for the new window. optional, defaults to null. name string name that is assigned to the window. optional, defaults to null. features object m...
...uments property. returns nsidomwindow opendialog(options) opens a top level window and returns its nsidomwindow representation. this is the same as open, but you can supply more features. it wraps window.opendialog. parameters options : object options for the function, with the following properties: name type url string uri of the document to be loaded into the window. defaults to "chrome://browser/content/browser.xul". name string optional name that is assigned to the window. defaults to "_blank". features string map of features to set for the window, defined like: { width: 10, height: 15, chrome: true }. for the set of features you can set, see the window.opendialog documentation. optional, default...
...ns, you can omit this, and it's the same as passing null. options : object options object containing the following property: name type includeprivate boolean whether to include private windows. defaults to false. the add-on must also have opted into private windows for this to have an effect. returns array: array of nsidomwindow instances. isdocumentloaded(window) check if the given window's document is completely loaded. this means that its "load" event has been fired and all content is loaded, including the whole dom document, images, and any other sub-resources. parameters window : nsidomwindow returns boolean: true if the document is completely loaded. isbrowser(window) returns true if the given window is a firefox browser window: that i...
...e. isxulbrowser(window) returns true if the given window is a xul window. parameters window : nsidomwindow returns boolean getfocusedwindow() gets the child window within the topmost browser window that is focused. see nsifocusmanager for more details. returns nsidomwindow getfocusedelement() get the element that is currently focused. this will always be an element within the document loaded in the focused window, or null if no element in that document is focused. returns nsidomelement getframes(window) get the frames contained by the given window. parameters window : nsidomwindow returns array: array of frames. ...
Listening for Load and Unload - Archive of obsolete content
to follow this tutorial you'll need to have learned the basics of jpm. if your add-on exports a function called main(), then that function will be called whenever the add-on is loaded, and it will be passed an object containing a string describing the reason it was loaded as well as any arguments passed to it. if your add-on exports a function called onunload(), then that function will be called when the add-on is unloaded, and it will be passed a string describing the reason it was unloaded. you don't have to use exports.main() or exports.onunload(). you can just place your add-on's code at the top level instead of wrapping it in a function assigned to exports.main(). it will be loaded in the same circumstances, but you won't get access to the load/unload reason or arguments. exports.mai...
...cribing the reason it was unloaded. you don't have to use exports.main() or exports.onunload(). you can just place your add-on's code at the top level instead of wrapping it in a function assigned to exports.main(). it will be loaded in the same circumstances, but you won't get access to the load/unload reason or arguments. exports.main() your add-on's main.js code is executed as soon as it is loaded. it is loaded when it is installed, when it is enabled, or when firefox starts. if your add-on exports a function called main(), that function will be called immediately after the overall main.js is evaluated, and after all top-level require() statements have run (so generally after all dependent modules have been loaded). exports.main = function (options, callbacks) {}; options is an obje...
... or when firefox starts. if your add-on exports a function called main(), that function will be called immediately after the overall main.js is evaluated, and after all top-level require() statements have run (so generally after all dependent modules have been loaded). exports.main = function (options, callbacks) {}; options is an object describing the parameters with which your add-on was loaded. options.loadreason options.loadreason is one of the following strings describing the reason your add-on was loaded: install enable startup upgrade downgrade exports.onunload() if your add-on exports a function called onunload(), that function will be called when the add-on is unloaded. exports.onunload = function (reason) {}; reason reason is one of the following strings describing ...
...this happens because disabling an add-on also disables its onunload listeners, so there is no listener remaining when the add-on is uninstalled. ...
HTML to DOM - Archive of obsolete content
='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 = document.implementation.createhtmldocument("example")...
...let's take a look at the donkeyfire.donkeybrowser_onpageload() handler: donkeybrowser_onpageload: function(aevent) { var doc = a...
...wmetaredirects = true; donkeybrowser.webnavigation.allowplugins = false; donkeybrowser.webnavigation.allowsubframes = false; donkeybrowser.addeventlistener("domcontentloaded", function (e) { donkeyfire.donkeybrowser_onpageload(e); }, true); } with that code, we obtain a reference to the iframe element we declared in the .xul file. the most interesting piece of code here is the domcontentloaded event listener we define for the element. let's take a look at the donkeyfire.donkeybrowser_onpageload() handler: donkeybrowser_onpageload: function(aevent) { var doc = aevent.originaltarget; var url = doc.location.href; if (aevent.originaltarget.nodename == "#document") { // ok, it's a real page, let's do our magic dump("[df] url = "+url+"\n"); var text = doc.evaluate("/html/body/h1",doc...
...in the example, we dump() to the console the page's url and the text contained in the first h1 tag of the page's <body>. but, we still need to see how to execute the famous loaduri() method using our iframe: donkeybrowser.webnavigation.loaduri("http://developer.mozilla.org", components.interfaces.nsiwebnavigation, null, nu...
Tabbed browser - Archive of obsolete content
extensions that overlay into browser.xul, can access the tabbrowser element using the global variable gbrowser. // gbrowser is only accessible from the scope of // the browser window (browser.xul) gbrowser.addtab(...); if gbrowser isn't defined your code is either not running in the scope of the browser window or running too early. you can access gbrowser only after the browser window is fully loaded. if you need to do something with gbrowser right after the window is opened, listen for the load event and use gbrowser in the event listener. if your code does not have access to the main window because it is run in a sidebar or dialog, you first need to get access to the browser window you need before you can use gbrowser. you can find more information on getting access to the browser window i...
...advanceselectedtab(1, true); this moves one tab to the left. gbrowser.tabcontainer.advanceselectedtab(-1, true); detecting page load see also code snippets:on page load function examplepageload(event) { if (event.originaltarget instanceof components.interfaces.nsidomhtmldocument) { var win = event.originaltarget.defaultview; if (win.frameelement) { // frame within a tab was loaded. win should be the top window of // the frameset. if you don't want do anything when frames/iframes // are loaded in this web page, uncomment the following line: // return; // find the root document: win = win.top; } } } // do not try to add a callback until the browser window has // been initialised. we add a callback to the tabbed browser // when the browser...
...window.addeventlistener("load", function () { // add a callback to be run every time a document loads. // note that this includes frames/iframes within the document gbrowser.addeventlistener("load", examplepageload, true); }, false); ... ...
.../this is a problem i dont know why it would get here } } /*end do not edit here*/ /*start - do all your edits below here*/ var url = ohttp.uri.spec; //can get url without needing loadcontext if (loadcontext) { var contentwindow = loadcontext.associatedwindow; //this is the html window of the page that just loaded //adomwindow this is the firefox window holding the tab var adomwindow = contentwindow.top.queryinterface(ci.nsiinterfacerequestor).getinterface(ci.nsiwebnavigation).queryinterface(ci.nsidocshelltreeitem).roottreeitem.queryinterface(ci.nsiinterfacerequestor).getinterface(ci.nsidomwindow); var gbrowser = adomwindow.gbrowser; //this is the gbrowser ob...
browser.type - Archive of obsolete content
subdocuments of chrome documents are of chrome type, unless the container element (one of iframe, browser or editor) has one of the special type attribute values (the common ones are content, content-targetable and content-primary) indicating that the subdocument is of content type. ...
...subdocuments of chrome documents are of chrome type, unless the container element (one of iframe, browser or editor) has one of the special type attribute values (the common ones are content, content-targetable and content-primary) indicating that the subdocument is of content type. ...
...wser is added to a chrome document), and preventing documents from inheriting the principal of the parent document. the type attribute on all frames in content documents is ignored; subdocuments of content documents are always content documents. warning: the type attribute must be set before the element is inserted into the document. content a browser for content. the content that is loaded inside the browser is not allowed to access the chrome above it. content-primary the primary browser for content. the content that is loaded inside the browser is not allowed to access the chrome above it. for instance, in a web browser, this would be the element that displays the web page. the window for the primary content can be retrieved more conveniently using window.content. content-t...
...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. ...
Template Builder Interface - Archive of obsolete content
, while the tree builder also implements the nsixultreebuilder interface. the builder associated with an element is accessible via the element's 'builder' property both for content builders and for tree builders. an element that does not have a builder will have this property set to null. the processes of creating a builder for an element applies both when an element is created when the window is loaded and when an element is inserted dynamically. templates can only be used in xul documents, however, there is no requirement that the templates generate xul elements. they could also be used, for example, to generate html elements. this isn't a very common technique, however, here is an example of how this can be used: <html:div id="photoslist" datasources="template-guide-photos5.rdf" ref...
...n element is to call its 'rebuild' method. this method removes any existing generated content and deletes all data in the rule network. then, the method recompiles the query and the rules and regenerates the content. essentially, the rebuild method instructs the builder to remove any existing information and reconstruct it from the beginning. the only difference is that the datasource has already loaded so the data will be the same. however, this is often used if you modify the datasource or modify the rules. for rdf datasources, the builder's refresh method, however, will reload the datasources. it will not rebuild the template, but we'll see in a later section why this is not usually necessary. to summarize, the refresh method reloads the data, whereas the rebuild method reconstructs the conte...
...n this case, the template will be rebuilt automatically as you can set all of the datasources at once with this method of changing datasources. so you don't need to call the rebuild method. you can also do the same with 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...
...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 situtations where this will be necessary. if you do plan on determining the datasources dynamically, it is common to start with an empty datasource using the special uri 'rdf:null'. ...
prefpane - Archive of obsolete content
nd the user interface for adjusting those preferences. the former is specified using a preferences element while the latter may be specified using other xul elements. both may be specified directly as children of the prefpane element, or the src attribute may be used to put a pane in a separate file. in this latter case, the separate file should use an overlay tag as its root tag since it will be loaded as an overlay to the main preferences window. more information is available in the preferences system article. attributes helpuri, image, label, onpaneload, selected, src properties image, label, preferenceelements, preferences, selected, src examples methods preferenceforelement <prefpane id="panegeneral" label="general" src="chrome://path/to/paneove...
...termined by the dir and orient attributes. label type: string the label that will appear on the element. if this is left out, no text appears. for an editable menuitem element the value of this attribute is copied to the menulist.value property upon user selection of the menuitem. onpaneload type: script code code defined here is called when the pane has been loaded, much like the load event for a window. selected type: boolean this attribute will be set to true for the currently selected prefpane. to change the selected pane, use the prefwindow's showpane method. src type: uri the uri of the overlay contents of preference pane. if this is not specified, the contents of the prefpane element is used. prope...
... contents of preference pane. if this is not specified, the contents of the prefpane element is used. properties contentheight (readonly) the height (in pixels) of current pane's content. image type: image url gets and sets the value of the image attribute. label type: string gets and sets the value of the label attribute. loaded indicates whether the pane is fully loaded. preferenceelements type: dom nodelist holds a list of the ui elements in the pane that are attached to preferences. preferences type: dom nodelist holds a list of the preference elements in the pane. selected type: boolean this property's value is true if this element is selecte...
...after the overlay is merged.) you can put the handler for this event in the onpaneload attribute on the element. using multiple prefpanes note that when using multiple prefpanes in the same prefwindow, you must not put the <script> elements above the prefpane elements, but instead below them. otherwise the dialog will show erratic behavior and not display correctly. place the <script> tags...
2D maze game with device orientation - Game development
this.load.image('ball', 'img/ball.png'); // ... this.load.spritesheet('button-start', 'img/button-start.png', 146, 51); // ... this.load.audio('audio-bounce', ['audio/bounce.ogg', 'audio/bounce.mp3', 'audio/bounce.m4a']); }, create: function() { this.game.state.start('mainmenu'); } }; there are single images, spritesheets and audio files loaded by the framework. in this state the preloadbar is showing the progress on the screen. that progress of the loaded assets is visualized by the framework with the use of one image. with every asset loaded you can see more of the preloadbar image: from 0% to 100%, updated on every frame. after all the assets are loaded, the mainmenu state is launched. mainmenu.js the mainmenu state shows the main ...
...we’re also setting the anchor for any physics calculations to the middle of the ball, enabling the arcade physics engine (which handles all the physics for the ball movement), and setting the size of the body for the collision detection. the bounce property is used to set the bounciness of the ball when it hits the obstacles. controlling the ball it’s cool to have the ball r...
...allcollision, null, this); this.physics.arcade.collide(this.ball, this.levels[this.level-1], this.wallcollision, null, this); this will tell the framework to execute the wallcollision function when the ball hits any of the walls. we can use the wallcollision function to add any functionality we want like playing the bounce sound and implementing the vibration api. adding the sound among the preloaded assets there was an audio track (in various formats for browser compatibility), which we can use now. it has to be defined in the create() function first: this.bouncesound = this.game.add.audio('audio-bounce'); if the status of the audio is true (so the sounds in the game are enabled), we can play it in the wallcollision function: if(this.audiostatus) { this.bouncesound.play(); } that's a...
... this.showlevel(); } }, if the current level is equal to the maximum number of levels (in this case 5), then the game is finished — you'll get a congratulations message along with the number of seconds elapsed through the whole game, and a button to press that takes you to the main menu. if the current level is lower than 5, all the neccesary variables are reset and the next level is loaded. ideas for new features this is merely a working demo of a game that could have lots of additional features. we can for example add power-ups to collect along the way that will make our ball roll faster, stop the timer for a few seconds or give the ball special powers to go through obstacles. there’s also room for the traps which will slow the ball down or make it more difficult to reach the ...
What’s in the head? Metadata in HTML - Learn web development
it contains information such as the page <title>, links to css (if you choose to style your html content with css), links to custom favicons, and other metadata (data about the html, such as the author, and important keywords that describe the document.) in this article we'll cover all of the above and more, in order to give you a good basis for working with markup. prerequisites: basic html familiarity, as covered in getting started with html. ...
...instead, the head's job is to contain metadata about the document. in the above example, the head is quite small: <head> <meta charset="utf-8"> <title>my test page</title> </head> in larger pages however, the head can get quite full. try going to some of your favorite websites and use the developer tools to check out their head...
...familiarity. let's get started. adding a title we've already seen the <title> element in action — this can be used to add a title to the document. this however can get confused with the <h1> element, which is used to add a top level heading to your body content — this is also sometimes referred to as the page title. ...
...ntains the path to the stylesheet file: <link rel="stylesheet" href="my-css-file.css"> the <script> element should also go into the head, and should include a src attribute containing the path to 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: ...
Drawing graphics - Learn web development
tmlimageelement 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 you load your example in the browser now, you should see the image embeded in the canvas. but there's more! what if we wa...
...t if we want to display only a part of the image, or to resize it? we can do both with the more complex version of drawimage(). update your ctx.drawimage() line like so: ctx.drawimage(image, 20, 20, 185, 175, 50, 50, 185, 175); the first parameter is the image reference, as before. parameters 2 and 3 define the coordinates of the top left corner of the area you want to cut out of the loaded image, relative to the top-left corner of the image itself. nothing to the left of the first parameter or above the second will be drawn. parameters 4 and 5 define the width and height of the area we want to cut out from the original image we loaded. parameters 6 and 7 define the coordinates at which you want to draw the top-left corner of the cut-out portion of the image, relative to the t...
...alk-right.png in the same directory. at the bottom of the javascript, add the following line to once again make the coordinate origin sit in the middle of the canvas: ctx.translate(width/2, height/2); now let's create a new htmlimageelement object, set its src to the image we want to load, and add an onload event handler that will cause the draw() function to fire when the image is loaded: let image = new image(); image.src = 'walk-right.png'; image.onload = draw; now we'll add some variables to keep track of the position the sprite is to be drawn on the screen, and the sprite number we want to display. let sprite = 0; let posx = 0; let's explain the spritesheet image (which we have respectfully borrowed from mike thomas' create a sprite sheet walk cycle using css a...
... there's a bit more to take in here, so let's go through it in stages: we first create a cube global variable so we can access our cube from anywhere in the code. next, we create a new textureloader object, then call load() on it. load() takes two parameters in this case (although it can take more): the texture we want to load (our png), and a function that will run when the texture has loaded. inside this function we use properties of the texture object to specify that we want a 2 x 2 repeat of the image wrapped around all sides of the cube. next, we create a new boxgeometry object and a new meshlambertmaterial object, and bring them together in a mesh to create our cube. an object typically requires a geometry (what shape it is) and a material (what its surface looks like). las...
Manipulating documents - Learn web development
were you? despite the limitations, web apis still give us access to a lot of functionality that enable us to do a great many things with web pages. ...
... consider the following diagram, which represents the main parts of a browser directly involved in viewing web pages: the window is the browser tab that a web page is loaded into; this is represented in javascript by the window object. using methods available on this object you can do things like return the window's size (see window.innerwidth and window.innerheight), manipulate the document loaded into that window, store data specific to that document on the client-side (for example using a local database or other storage mechanism), attach an event handler to the current window, and more. the navigator represents the state and identity of the browser (i.e. the user-agent) as it exists on the web. in javascript, this is represented by the navigator object. you can use this object to retri...
...er to the current window, and more. the navigator represents the state and identity of the browser (i.e. the user-agent) as it exists on the web. in javascript, this is represented by the navigator object. you can use this object to retrieve things like the user's preferred language, a media stream from the user's webcam, etc. the document (represented by the dom in browsers) is the actual page loaded into the window, and is represented in javascript by the document object. you can use this object to return and manipulate information on the html and css that comprises the document, for example get a reference to an element in the dom, change its text content, apply new styles to it, create new elements and add them to the current element as children, or even delete it altogether. in this art...
...ss that comprises the document, for example get a reference to an element in the dom, change its text content, apply new styles to it, create new elements and add them to the current element as children, or even delete it altogether. in this article we'll focus mostly on manipulating the document, but we'll show a few other useful bits besides. the document object model the document currently loaded in each one of your browser tabs is represented by a document object model. this is a "tree structure" representation created by the browser that enables the html structure to be easily accessed by programming languages — for example the browser itself uses it to apply styling and other information to the correct elements as it renders a page, and developers like you can manipulate the dom with...
Website security - Learn web development
an any other type of security threat. the xss vulnerabilities are divided into reflected and persistent, based on how the site returns the injected scripts to a browser. a reflected xss vulnerability occurs when user content that is passed to the server is returned immediately and unmodified for display in the browser. any scripts in the original user content will be run when the new page is loaded. for example, consider a site search function where the search terms are encoded as url parameters, and these terms are displayed along with the results. an attacker can construct a search link that contains a malicious script as a parameter (e.g., http://mysite.com?q=beer<script%20src="http://evilsite.com/tricky.js"></script>) and email it to another user. if the target user clicks this "inter...
...mation required to access the user's account. this sort of attack is extremely popular and powerful, because the attacker might not even have any direct engagement with the victims. while the data from post or get requests is the most common source of xss vulnerabilities, any data from the browser is potentially vulnerable, such as cookie data rendered by the browser, or user files that are uploaded and displayed. the best defense against xss vulnerabilities is to remove or disable any markup that can potentially contain instructions to run the code. for html this includes elements, such as <script>, <object>, <embed>, and <link>. the process of modifying user data so that it can't be used to run scripts or otherwise affect the execution of server code is known as input sanitization. many...
...ts of the web server file system that they should not be able to access. this vulnerability occurs when the user is able to pass filenames that include file system navigation characters (for example, ../../). the solution is to sanitize input before using it. file inclusion. in this attack, a user is able to specify an "unintended" file for display or execution in data passed to the server. when loaded, this file might be executed on the web server or the client-side (leading to an xss attack). the solution is to sanitize input before using it. command injection. command injection attacks allow a malicious user to execute arbitrary system commands on the host operating system. the solution is to sanitize user input before it might be used in system calls. for a comprehensive listing of websi...
...nitize all user-originating data before it is displayed in the browser, used in sql queries, or passed to an operating system or file system call. important: the single most important lesson you can learn about website security is to never trust data from the browser. this includes, but is not limited to data in url parameters of get requests, post requests, http headers and cookies, and user-uploaded files. always check and sanitize all incoming data. always assume the worst. a number of other concrete steps you can take are: use more effective password management. encourage strong passwords that are changed regularly. consider two-factor authentication for your site, so that in addition to a password the user must enter another authentication code (usually one that is delivered via some...
Application cache implementation overview
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 resource fails fallback step...
...ntation of “cache selection algorithm” as described by the html5 spec. for purpose of this documentation it's enough to describe the simplest case ; for complete documentation of the selection algorithm refer to the spec or to the code. when the url in the manifest attribute of the html tag is identical to the manifest url the channel's nsiapplicationcache object belongs to and, the channel's loadedfromapplicationcache flag is set, the document is associated with that nsiapplicationcache object and an update attempt for the manifest is scheduled after the document completely loads. marking entries as foreign when nscontentsink::processofflinemanifest() discovers that the url in the manifest attribute of the html tag is different from the manifest url the channel's nsiapplicationcache object ...
...nt is associated with that nsiapplicationcache object and an update attempt for the manifest is scheduled after the document completely loads. marking entries as foreign when nscontentsink::processofflinemanifest() discovers that the url in the manifest attribute of the html tag is different from the manifest url the channel's nsiapplicationcache object belongs to, the entry the document has been loaded from is marked “foreign” and the page load is completely restarted. the load starts again from the top with a completely new channel. but this time the entry is not selected to load the top level document from. we search another, if available, potentially even in a different offline cache group. loading subresources of a document using offline cache each sub resource loading channel is set in...
...ut to actually start, the scheduling service calls nsofflinecacheupdate::begin() method, that switches the update to checking state (+invokes onchecking event) and starts fetch of the manifest file. note: whenever a load of an items (including the manifest) fails due to a network or server error or leads to a redirect, the update fails and completely rollbacks any changes made (i.e. all files downloaded are deleted and the new cache version is discarded.) an md5 hash is then calculated from the manifest content we download from the server to be compared to existing md5 (in case of an “update”). during the load, manifest is parsed according the “parsing the cache manifest” html5 spec, and lists of entries and namespaces are collected. after the manifest fetch is done, nsofflinecacheupdate...
Download
y downloaderror when the download fails, this is set to a downloaderror instance indicating the cause of the failure. if the download has been completed successfully or has been canceled, this property is null. this property is reset to null when a failed download is restarted. haspartialdata read only boolean indicates whether, at this time, there is any partially downloaded data that can be used when restarting a failed or canceled download. this property is relevant while the download is in progress, and also if it failed or has been canceled. if the download has been completed successfully, this property is not relevant anymore. whether partial data can actually be retained depends on the saver and the download source, and may not be known before the dow...
...load has been completed successfully. target read only downloadtarget target of this download. totalbytes read only number when hasprogress is true, this indicates the total number of bytes to be transferred before the download finishes; this value can be zero if the file is empty. ...
... when hasprogress is true, this indicates the total number of bytes to be transferred before the download finishes; this value can be zero if the file is empty. note: this property's value may not match the actual final size of the downloaded file if the download is encoded during the network transfer. you can use the downloadtarget.size property to get the actual size of the completely-downloaded file once the download has succeeded. when hasprogress is false, this property is always zero. trytokeeppartialdata boolean indicates whether any partially downloaded data should be retained, to use when restarting a failed or canceled download. the default is false. whether partial data can actually be retained depends on the saver and the download source, and m...
...the default is false. promise resolves to undefined when the operation has finished successfully. ...
Downloads.jsm
resolves to the newly created download object. fetch() downloads data from a remote network location to a local file. this download method does not provide user interface or the ability to cancel or restart the download programmatically. for that, you should obtain a reference to a download object using the createdownload() function. since the download cannot be restarted, any partially downloaded data will not be kept in case the download fails. promise fetch( asource, atarget, object aoptions ); parameters asource string containing the uri for the download source. alternatively, may be an nsiuri or a downloadsource object. atarget string containing the path of the target file. alternatively, may be an nsifile or a downloadtarget object. aoptions optional an optional obje...
...finished successfully and you can access the target file. promise can be rejected with downloaderror if the download failed. getlist() retrieves the specified type of downloadlist object. there is one download list for each type, and this method always retrieves a reference to the same download list when called with the same argument. calling this function may cause the download list to be reloaded from the previous session, if it wasn't loaded already. promise<downloadlist> getlist(atype); parameters atype this can be downloads.public, downloads.private, or downloads.all. downloads added to the downloads.public and downloads.private lists are reflected in the downloads.all list, and downloads added to the downloads.all list are also added to either the downloads.public or the downlo...
....private list based on their properties. promise resolves to the requested downloadlist object. getsummary() retrieves the specified type of downloadsummary object. there is one download summary for each type, and this method always retrieves a reference to the same download summary when called with the same argument. calling this 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...
... to demonstrate the logging, a new download is started while a message box is being shown. the download is stopped and removed from the list when the message box is closed, regardless of whether it has been completed or not. componen...
Using JavaScript code modules
javascript code modules are a concept introduced in gecko 1.9 and can be used for sharing code between different privileged scopes. modules can also be used to create global javascript singletons that previously required using javascript xpcom objects. a javascript code module is simply some javascript code located in a registered location. the module is loaded into a specific javascript scope, such as xul script or javascript xpcom script, using components.utils.import() or components.utils["import"](). creating a javascript code module a very simple javascript module looks like this: var exported_symbols = ["foo", "bar"]; function foo() { return "foo"; } var bar = { name : "bar", size : 3 }; var dummy = "dummy"; notice that the module uses normal javascript to create functions, ...
...ing changes to a code module, be sure to change the application's build id (e.g., the version) before your next test run; otherwise, you may find yourself running the previous version of your module's code. the url for a code module as you can see from the example above, you need a url to import a code module. (the url in the example is "resource://app/my_module.jsm".) code modules can only be loaded using a chrome: (), resource:, or file: url. if you're writing an extension for firefox 4 and already have a chrome.manifest with a content instruction in it, you can put the code module in your content folder and reference it like your other content files via chrome://<yourextension>/content/<yourmodule>.jsm. if your extension or application needs to support mozilla 1.9.x (firefox 3.x), you ...
...ther content files via chrome://<yourextension>/content/<yourmodule>.jsm. if your extension or application needs to support mozilla 1.9.x (firefox 3.x), you should register a new resource url. details on doing this are in the "extending resource: urls" section below. sharing objects using code modules an extremely important behavior of components.utils.import() is that modules are cached when loaded and subsequent imports do not reload a new version of the module, but instead use the previously cached version. this means that a given module will be shared when imported multiple times. any modifications to data, objects, or functions will be available in any scope that has imported the module. for example, if the simple module were imported into two different javascript scopes, changes in one...
...this means you can't use components.utils.import() with your own resource url at the top level in a component source. a possible solution is moving the call to components.utils.import() into the xpcom component constructor (discussion). packaging notes it's important to note that you should not typically put your javascript code modules in a jar file in your add-on. ...
JS::CompileOptions
. version jsversion javascript version used to compile the script. methods some methods of js::owningcompileoptions and js::compileoptions return the instance itself to allow method chain. methods of js::readonlycompileoptions method description bool mutederrors() const determines if errors are muted. the web platform allows scripts to be loaded from arbitrary cross-origin sources. this allows an attack by which a malicious website loads a sensitive file (say, a bank statement) cross-origin (using the user's cookies), and sniffs the generated syntax errors (via a window.onerror handler) for juicy morsels of its contents. to counter this attack, html5 specifies that script errors should be sanitized ("muted") when the script is not s...
...allows an attack by which a malicious website loads a sensitive file (say, a bank statement) cross-origin (using the user's cookies), and sniffs the generated syntax errors (via a window.onerror handler) for juicy morsels of its contents. to counter this attack, html5 specifies that script errors should be sanitized ("muted") when the script is not same-origin with the global for which it is loaded. callers should set this flag for cross-origin scripts, and it will be propagated appropriately to child scripts and passed back in jserrorreports. const char *filename() const returns filename of the source code. const char *introducerfilename() const returns filename of the file which introduces the file. const char16_t *sourcemapurl() const returns the u...
...n bool true if asm.js is allowed in the code. forceasync bool false means js::cancompileoffthread may returns false depends on the length of the code. installedfile bool true iff pre-compiling js file in packaged app. sourceislazy bool true indicates that, after compilation, script source should not be cached by the js engine and should be lazily loaded from the embedding as-needed. introductiontype const char a statically allocated c string: one of following in general: "eval" - code passed to eval "function" - code passed to the function constructor. "generatorfunction" - code passed to the generatorfunction constructor. in addition to above, the following are used in browser: "wor...
...bedding as-needed. introductiontype const char a statically allocated c string: one of following in general: "eval" - code passed to eval "function" - code passed to the function constructor. "generatorfunction" - code passed to the generatorfunction constructor. in addition to above, the following are used in browser: "worker" - code loaded by calling the web worker constructor—the worker's main script. "importscript" - code by calling importscripts in a web worker. "eventhandler" - code assigned to dom elements' event handler idl attributes as a string. "scriptelement" - code belonging to <script> elements. "javascripturl" - code presented in javascript: urls. "settimeout" - code passed to settimeout as a...
Shell global objects
name returns. sourcemapurl if present with value v, convert v to a string, and provide that as the code's source map url. if omitted, attach no source map url to the code (although the code may provide one itself, via a //#sourcemappingurl comment). sourceislazy if present and true, indicates that, after compilation, script source should not be cached by the js engine and should be lazily loaded from the embedding as-needed. loadbytecode if true, and if the source is a cacheentryobject, the bytecode would be loaded and decoded from the cache entry instead of being parsed, then it would be executed as usual. savebytecode if true, and if the source is a cacheentryobject, the bytecode would be encoded and saved into the cache entry after the script execution. asserteqbytecode if...
...and an assertion is raised if they differ. run('foo.js') run the file named by the first argument, returning the number of of milliseconds spent compiling and executing it. read('bar.js') reads the file named by the first argument, returning the content of the file as string. ...
...apped first, so this can be used on objects from different globals. sleep(dt) sleep for dt seconds. compile(code) compiles a string to bytecode, potentially throwing. parsemodule(code) parses source text as a module and returns a module object. setmoduleresolvehook(function(module, specifier) {}) set the hostresolveimportedmodule hook to function. this hook is used to look up a previously loaded module object. it should be implemented by the module loader. getmoduleloadpath() return any --module-load-path argument passed to the shell. used by the module loader. parse(code) parses a string, potentially throwing. syntaxparse(code) check the syntax of a string, returning success value offthreadcompilescript(code[, options]) compile code on a helper thread. to wait for the compilatio...
...ion is currently available or whether it is disabled (e.g., by the debugger). issimdavailable returns true if simd extensions are supported on this platform. getcompileroptions() return an object describing some of the jit compiler options. isasmjsmodule(fn) returns whether the given value is a function containing "use asm" that has been validated according to the asm.js spec. isasmjsmoduleloadedfromcache(fn) return whether the given asm.js module function has been loaded directly from the cache. this function throws an error if fn is not a validated asm.js module. isasmjsfunction(fn) returns whether the given value is a nested function in an asm.js module that has been both compile- and link-time validated. wasmissupported() returns a boolean indicating whether webassembly is suppor...
XPCOM changes in Gecko 2.0
rozen interfaces there are no longer any frozen interfaces; from now on, all interfaces are subject to change. documentation will be updated as time allows to remove references to interfaces being "frozen" or "unfrozen." component registration the way xpcom components are registered changed in gecko 2. prior to gecko 2, during component registration, all binary and javascript component files were loaded and called, asking them to register themselves. if you used xpcomutils.jsm, some of this was hidden from you, but it was still there. starting in gecko 2, however, components are registered using manifest files, similarly to how chrome is registered. in fact, the same chrome manifest file will be used to register components. all existing xpcom components will need to be updated to support this. h...
...nsions, this is the same chrome.manifest currently used to register chrome. xpt files the path of any xpt files must be listed explicitly in a manifest using an interfaces directive: interfaces components/mycomponent.xpt javascript components the registration information for javascript components is no longer located in the component itself; instead, it's located in the manifest. the component is loaded only when the xpcom component manager needs to create a component. chrome.manifest: # the {classid} here must match the classid in mycomponent.js component {e6b866e3-41b2-4f05-a4d2-3d4bde0f7ef8} components/mycomponent.js contract @foobar/mycomponent;1 {e6b866e3-41b2-4f05-a4d2-3d4bde0f7ef8} category profile-after-change mycomponent @foobar/mycomponent;1 the javascript code no longer exports a nsg...
... 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 with the chrome process. the changes to the component registration model let this so-called extension manager restart become a thing of the past. ins...
...a per-process basis, or somehow share a component cache with the chrome process. the changes to the component registration model let this so-called extension manager restart become a thing of the past. instead of relying on a potentially stale 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 compon...
Building the WebLock UI
access (e.g., native widgetry that instantiates and controls the weblock component). client code overview before we get started on the actual user interface, we should establish how the client code is to access the weblock component and use its interfaces to control the web locking of the browser. first of all, it's important to be able to represent the basic state of the lock as soon as it's loaded. like the secure page icon, the weblock icon that appears in the lower right corner of the browser should indicate whether the browser is currently locked or unlocked. since the weblock component is always initialized as unlocked, we can have the client code - the javascript code in the interface - represent this state and track it as the user manipulates the iweblock interface. a boolean wlocked...
...unctions and others: var weblock = components.classes["@dougt/weblock"] .getservice() .queryinterface(components.interfaces.iweblock); in addition to this basic setup, you must also write javascript that uses the addsite method to add new sites to the white list. this is a bit more complicated, because it requires that you work with the currently loaded page or provide other ui (e.g., a textfield where you can enter an arbitrary url) for specifying urls. in the xul section we'll go into how the user interface is defined. this section describes the functions that are called from the interface and how they interact with the weblock component. the url that the addsite method expects is a string, so we can pass a string directly in from the user in...
...g bundles in which strings that are used in the interface javascript can be similarly replaced. there are also technologies, not discussed here, which may be used in separate, installable files. these include bindings in xml files, metadata in rdf files, whole collections of css files called skins, and others. weblock.css the following style rules are defined in weblock.css, a css file that is loaded by the overlay and applied to the icon in the browser that reflects the current status of the web lock and provides access to the web lock manager dialog. statusbarpanel#weblock-status { list-style-image: url("chrome://weblock/wlock.gif"); } statusbarpanel#weblock-status[status="locked"] { list-style-image: url("chrome://weblock/wl-lock.gif"); } statusbarpanel#weblock-status[status="unlock...
...n the element in the xul with the id "weblock-status." as you can see above, when the status of the element is set to "locked", the image wl-lock.gif is used to show the state, and when the web locking is unlocked, it uses wl-un.gif. (note: we include three images to represent the state of the weblock, but wlock.gif and wl-lock.gif are identical, since weblock is presumed to be unlocked when it's loaded. this tutorial makes use of only two different states, but you can further customize the look of the weblock using the three images if you wish.) since the presentation of the weblock manager dialog itself doesn't require any special styles, these are all the rules you need in the weblock.css. note that the weblock.xul file in which the manager is defined imports only the global skin: <?xml-sty...
Creating the Component Code
to handle the relationship between your component and xpcom. having the component found and registered properly is the goal of this first chapter of the tutorial. in the subsequent chapters, we can begin to work on the example weblock component functionality itself. use the calculator (after learning long division) you have to write a fair amount of code to create a component library that gets loaded into xpcom. an xpcom component needs to implement at least three interfaces that xpcom requires, and often others as well. there is more code in this chapter than you'll eventually need, however. using xpcom utilities to make things easier shows some simpler and more elegant ways to create an xpcom component using generic macros, and this chapter is more about learning the basics. as in grade sch...
...ccessed relative to the component. this method is only called once, so you have to persist the location if you are going to use it later. the next two parameters are usually passed into the nsicomponentregistrar methods and used by xpcom to determine how to handle the component's registration. the aloaderstr parameter, which is opaque and should not be modified, distinguishes components that are loaded from the same location specified by the nsifile parameter. a single zip archive may store several xpcom components, where every component in the archive has the same nsifile parameter but the aloaderstr parameter can be used to refer to the location within the zip archive. the last parameter specifies what kind of loader to use on the component. this is reserved as an optimization, for the most ...
...where every component in the archive has the same nsifile parameter but the aloaderstr parameter can be used to refer to the location within the zip archive. the last parameter specifies what kind of loader to use on the component. this is reserved as an optimization, for the most part, but it can be a useful way to extend xpcom. since xpcom already knows internally what kind of file it has just loaded and called registerself on, passing this value to the registration methods is a shortcut for determining what kind of component is being registered. nsicomponentregistrar methods to tell xpcom what implementation is in the component library, call this method from registerself: ns_imethod registerfactorylocation(const nscid & aclass, const char *aclassname, ...
...cceeds[non-null-out]. the implementation of createinstance will ensure that the result will support the passed iid, kisupportsiid. the type of the variable sample should match the iid passed in as kisupportsiid. when createinstance is called, xpcom looks through all registered components to find a match for the given cid. xpcom then loads the component library associated with the cid if it isn't loaded already. xpcom then calls the function nsgetmodule on the library. finally, it calls the method getclassobject on the module. this method, which you must implement in your component code, is expected to return an nsifactory object for a given cid/iid pair. to prepare your component code, you need to create a factory object for each object that you have registered with xpcom. the main function th...
Observer Notifications
x 3.5, this was available to observers observing the app-startup/xpcom-startup notification. final-ui-startup triggered just before the first window for the application is displayed. sessionstore-windows-restored sent by the session restore process to indicate that all initial browser windows have opened. note that while the window are open and the chrome loaded the tabs in the windows may still be being restored after this notification. note: this notification is specific to firefox and seamonkey 2.0 applications application shutdown these are the topics that you can observe on shutdown, in order of appearance. topic description quit-application-requested something has requested that the application be shutdown.
...to true to abort the close. browser-lastwindow-close-granted sent when all interested parties have responded to the browser-lastwindow-close-requested notification and none of them requested that the close be aborted. after this is sent and handled, the browser window will close. browser-delayed-startup-finished sent when the browser window and all its components have been loaded and initialized. documents these topics indicate notifications you can monitor related to dom documents. topic subject data description chrome-document-global-created nsidomwindow null sent immediately after a chrome document window has been set up, but before any script code has been executed. this lets extensions inject api into chrome windows as nee...
...hierarchy works. extensions that cache information about windows may wish to observe this so they can release information when the window is destroyed. the window id can be obtained from subject.queryinterface(components.interfaces.nsisupportspruint64).data toplevel-window-ready nsiwindowwatcher called just after a new top level window has been opened and is ready, but has not yet loaded a document. xul-window-destroyed called just before a xul window is destroyed. xul-window-registered nsiappwindow called just after a top level xul window is registered with the window mediator service. xul-window-visible nsiappwindow called just after a xul window is made visible. browsing-context-discarded browsingcontext called while...
... the subject of the notification is the message manager that disconnected. if you're using a message manager to communicate with a script that may be running in a different process, you might need to know when the message manager has disconnected from the other end of the conversation, so you can stop sending it messages or expecting to receive messages. for example, suppose you've loaded a frame script into a tab using a browser message manager, and the user closes the tab. the frame script is unloaded and the browser message manager disconnects from it. by listening for message-manager-disconnect you will be informed when this happens. permission manager topic subject data description perm-changed nsipermission "deleted"/"added"/"changed"/"clea...
mozIJSSubScriptLoader
: see components.utils.import for another way to import javascript code. method overview jsval loadsubscript(in string url, in object targetobj optional, in string charset optional); jsval loadsubscriptwithoptions(in string url, in object options); methods loadsubscript() synchronously loads and executes the script from the specified url. as of gecko 8.0, scripts are loaded from the startup cache where possible. the loaded script is executed with the principal associated with the target object. any top-level functions or variables created by the loaded script via var are created as properties of the targetobj target object (but things declared via let and const are not). additionally, properties of the targetobj target object can be referred to as variables in the...
... if the script returns a value, it will be returned by this method. ...
...argetobj the object to use as the scope object for the script being executed. this is where var declarations in the script will be placed. it defaults to the global object of the caller. note that let and const declarations in the script will be placed on a syntactic scope that is not an object at all, and will not be available to the caller of loadsubscript. note: undeclared variables in the loaded script will be created as global variables in the caller (ie.: in the caller's global object). this object will be searched for variables that cannot be resolved in the subscript scope. charset an optional string to specify the character encoding of the file. if absent, the file is interpreted as ascii. loadsubscriptwithoptions() same as loadsubscript(), except that parameters after url ...
...ers url the url pointing to the script to load. it must be a local chrome:, resource: or file: url. options an object that may include any of these parameters: property type description target object the object to use as the scope object for the script being executed. it defaults to the global object of the caller. note: undeclared variables in the loaded script will be created as global variables in the caller (ie.: in the caller's global object). this object will be searched for variables that cannot be resolved in the subscript scope. charset string an optional string to specify the character encoding of the file. if absent, the file is interpreted as ascii. ignorecache boolean if present and set to true,...
nsIDOMWindowUtils
is no widget associated with this window. read only. outerwindowid unsigned long long the id of the window's outer window. read only. paintingsuppressed boolean true if painting is currently suppressed for this window; otherwise false. read only. this is used on mobile, for example, to prevent attempts to render content until enough of the page has been loaded to avoid content bouncing around excessively as more content is loaded. screenpixelspercsspixel float returns the number of screen pixels per css pixel. read only. audiomuted boolean with this it's possible to mute all the mediaelements in this window. we have audiomuted and audiovolume to preserve the volume across mute/umute. audiovolume float r...
... this is set, the selection is set from aoffset + alength to aoffset. select_character 0 select_cluster 1 select_word 2 select_line 3 select_beginline 4 select_endline 5 select_paragraph 6 select_wordnospace 7 agent_sheet 0 a possible type of a style sheet loaded/removed with loadsheet()/removesheet(). see css2 specification for details. user_sheet 1 a possible type of a style sheet loaded/removed with loadsheet()/removesheet(). see css2 specification for details. author_sheet 2 a possible type of a style sheet loaded/removed with loadsheet()/removesheet(). see css2 specification for details. methods activatenative...
...string with all profile information accumulated for the script. this includes the text of the script and details about its internal representation in spidermonkey, and counts for how often and in what ways each operation in the script executed. the structure of the json is unspecified and may vary between versions of firefox. getscrollxy() returns the scroll position of the window's currently loaded document. void getscrollxy( in boolean aflushlayout, out long ascrollx, out long ascrolly ); parameters aflushlayout flushes layout if true. otherwise, no flush occurs. ascrollx ascrolly getvisiteddependentcomputedstyle() perform the equivalent of: window.getcomputedstyle(aelement, apseudoelement). getpropertyvalue(apropertyname) except that, when the link whose presence i...
...an isinmodalstate(); parameters none. return value leavemodalstate() resume normal window state, where scripts can run and events are delivered. void leavemodalstate(); parameters none. loadsheet() synchronously loads a style sheet from |sheeturi| and adds it to the list of additional style sheets of the document. these additional style sheets are very much like user/agent sheets loaded with loadandregistersheet. the only difference is that they are applied only on the document owned by this window. sheets added via this api take effect immediately on the document. unsigned long loadsheet( in nsiuri sheeturi, in unsigned long type ); parameters sheeturi the nsiuri of the css file to be removed. type the type of the sheet (agent_sheet, user_sheet or author_sheet). n...
nsIDownloadManager
this interface is deprecated as of firefox 26. please use downloads.jsm instead. toolkit/components/downloads/public/nsidownloadmanager.idlscriptable this interface lets applications and extensions communicate with the download manager, adding and removing files to be downloaded, fetching information about downloads, and being notified when downloads are completed. inherits from: nsisupports last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) implemented by: @mozilla.org/download-manager;1. to get the service, use: var downloadmanager = components.classes["@mozilla.org/download-manager;1"] .getservice(components.interfaces.nsidownloadmanager); method overview nsidownload adddownload(in short adownloadtype, in nsiuri asource, i...
... nsidownloadprogresslistener alistener); void resumedownload(in unsigned long aid); void retrydownload(in unsigned long aid); void savestate(); obsolete since gecko 1.8 void startbatchupdate(); obsolete since gecko 1.9.1 attributes attribute type description activedownloadcount long the number of files currently being downloaded. read only. activedownloads nsisimpleenumerator an enumeration of active nsidownloads. read only. cancleanup boolean whether or not there are downloads that can be cleaned up (removed) that is downloads that have completed, have failed or have been canceled. read only. datasource nsirdfdatasource read only. obsolete since gecko 1.8 dbconnectio...
... listener nsidownloadprogresslistener the download manager's progress listener. obsolete since gecko 1.8 userdownloadsdirectory nsilocalfile returns the user configured downloads directory. the path is dependent on two user configurable prefs set in preferences: browser.download.folderlist defines the default download location for files: 0: files are downloaded to the desktop by default. 1: files are downloaded to 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 t...
... 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. ...
nsIModule
it is very important to ensure that no outstanding re...
...icomponentmanager acompmgr, in nsifile alocation, in string aloaderstr); methods canunload() this method may be queried to determine whether or not the component module can be unloaded by xpcom. boolean canunload( in nsicomponentmanager acompmgr ); parameters acompmgr the global component manager. return value indicates to the caller whether or not the component module can be unloaded. returning true is not a guarantee that the module will be unloaded. it constitues only willingness of the module to be unloaded. it is very important to ensure that no outstanding references to the module's code/data exist before returning true. returning false guaratees that the module will not be unloaded. if the component module is native (that is, as part of a dll), then this method may be c...
...getclassobject() obtains a class object from a nsimodule for a given cid and iid pair. this class object can either be query to a nsifactory or a may be query to a nsiclassinfo. ...
...getclassobject() obtains a class object from a nsimodule for a given cid and iid pair. this class object can either be query to a nsifactory or a may be query to a nsiclassinfo. ...
nsIProcessScriptLoader
e per process. the global object for process scripts is a contentprocessmessagemanager. methods void loadprocessscript(in astring aurl, in boolean aallowdelayedload) void removedelayedprocessscript(in astring aurl); jsval getdelayedprocessscripts(); loadprocessscript() load a script in the child process. process scripts are loaded as soon as loadprocessscript() is called. if this function is called on a chromemessagebroadcaster, : it will load the process script into all child processes. if aallowdelayedload is true, then the script will also be loaded into any new child processes created after the loadprocessscript() call. otherwise it will only be loaded into child processes that exist at the time of the call. if ...
...e of the call. if this function is called on a chromemessagesender: it will load the process script only into this chromemessagesender's child process aallowdelayedload should always be true. it's possible that the child process for this chromemessagesender is not yet available at the time of the loadprocessscript() call, and if you pass false in this situation, your process script won't be loaded. for example: let ppmm = services.ppmm.getchildat(1); ppmm.loadprocessscript('data:,dump("foo\n");', true); parameters name type description aurl string url for the script to load. aurl must be the absolute url. data: urls are also supported. for example data:,dump("foo\n"); aallowdelayedload boolean if this flag is false, the process scr...
... let ppmm = services.ppmm.getchildat(1); ppmm.loadprocessscript('data:,dump("foo\n");', true); parameters name type description aurl string url for the script to load. aurl must be the absolute url. data: urls are also supported. for example data:,dump("foo\n"); aallowdelayedload boolean if this flag is false, the process script will only be loaded into child processes that are already running at the time of the call. if this flag is true, the process script will be loaded into any new child processes created after the loadprocessscript() call, until removedelayedprocessscript() is called for that script. if you are calling loadprocessscript() on a chromemessagesender, you should always pass true here. removedelayedproc...
...meaning that the loader will no longer load the script into new child processes. if you used aallowdelayedload, you should call this as part of your cleanup (for example, when your add-on is disabled or uninstalled). parameters name type description aurl string url for the script to remove. getdelayedprocessscripts() returns all delayed scripts that will be loaded once a child process becomes available. the return value is a list of pairs [<url>, false]. returns list of the delayed scripts. each script is returned as a pair: [<url>, false]. ...
XUL Overlays
Mozilla › Tech › XUL › Overlays
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. 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 instructio...
...<?xul-overlay href="chrome://component/content/componentoverlay.xul"?> where component is the name of the package being overlayed (e.g., chrome://navigator/content/navigatoroverlay.xul). the layout engine loads any overlay files and then flows the resulting xul document, so problems associated with 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 o...
...mically -- 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 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 s...
...ys should never load the master skin file for a package. the navigatoroverlay.xul file, for example, does not and should never load the navigator.css file that defines the master skin for the navigator package. since the purpose of an overlay is to define new ui elements for a package within the context of that package's skin, the overlay should add structure but not new style. any skins that are loaded by an overlay destructively replace the master skin for the base file, and can change the basic appearance of the package's skin in unfortunate ways. note: the master skin is not the same as the global skin. for any package, the master skin file is that css file named after the package itself. the master skin file for the bookmarks package, for example, is called bookmarks.css, and is located i...
Initialization and Destruction - Plugins
« previousnext » this chapter describes the methods that provide the basic processes of initialization, instance creation and destruction, and shutdown. initialization: the browser calls the plug-in api function np_initialize when the plug-in code is first loaded. instance creation: the browser calls the plug-in api function npp_new when the instance is created. instance destruction: the plug-in instance is deleted when the user leaves the instance page or closes the instance window; the browser calls the function npp_destroy to tell the plug-in that the instance is being deleted. shutdown: when the last instance of a plug-in is deleted, the plug-in code is unloaded from memory and the browser calls the function np_shutdown. plug-ins consume no resources, other than disk ...
...use this function to allocate the memory and resources shared by all instances of your plug-in. nperror np_initialize(void) { }; after the last plug-in instance is deleted, the browser calls np_shutdown, which releases the memory or resources allocated by np_initialize. ...
...which releases the memory or resources allocated by np_initialize. for an example that shows the use of both the np_initialize and np_shutdown methods, see initialize and shutdown example. during initialization, when the browser encounters data of a mime type registered for a plug-in (either embedded in an html page or in a separate file), it loads the plug-in code into memory (if it hasn't been loaded already) and creates a new instance of the plug-in. for more information, see registering plug-ins. plug-ins are native code libraries: .dll files on windows, .so or .dso files on unix, and powerpc shared library files or 68k code resources on mac os. to reduce memory overhead, plug-ins are usually loaded only when needed and released as soon as possible. in the initialization process, the brow...
... delete the saved data with the equivalent of npn_memalloc at any time. shutdown when the application no longer needs the plug-in, it is shut down and released. np_shutdown gives you an opportunity to delete data allocated in np_initialize to be shared by all instances of a plug-in. the browser calls the plug-in's np_shutdown function, which informs the plug-in that its library is about to be unloaded, and gives it a chance to cancel any outstanding i/o requests, delete threads it created, free any memory it allocated, and perform any other closing tasks. the np_shutdown function releases memory or resources shared across all instances of a plug-in. it is called once after the last instance of the plug-in is destroyed, before releasing the plug-in library itself. void np_shutdown(void); for...
Debugger.Source - Firefox Developer Tools
is disabled if the debugger has the allowwasmbinarysource property set, the "[wasm]" value will be returned in this case. binary if the instance refers to webassembly code and the debugger has the allowwasmbinarysource property set, a uint8array that contains the webassembly bytecode. url if the instance refers to javascript source, the filename or url from which this script’s code was loaded. ...
... the url may be passed to the worker web worker constructor, or the web worker importscripts function. the url may be the name of a xpcom javascript module or subscript. ...
...following ways: the url may appear as the src attribute of a <script> element in markup text. the url may be passed to the worker web worker constructor, or the web worker importscripts function. the url may be the name of a xpcom javascript module or subscript. (note that code passed to eval, the function constructor, or a similar function isnot considered to be loaded from a url; the url accessor on debugger.source instances for such sources should return undefined.) if the instance refers to webassembly code, the url of the script that called new webassembly.module with the string "> wasm" appended. sourcemapurl if the instance refers to javascript source, if this source was produced by a minimizer or translated from some other language, and we know t...
...uctiontype if the instance refers to javascript source, a string indicating how this source code was introduced into the system. this accessor returns one of the following values: "eval", for code passed to eval. "function", for code passed to the function constructor. "function.prototype", for function.prototype internally generated code. "worker", for code loaded by calling the web worker constructor—the worker’s main script. "importscripts", for code by calling importscripts in a web worker. "eventhandler", for code assigned to dom elements’ event handler idl attributes as a string. "scriptelement", for code belonging to <script> elements. "javascripturl", for code presented in javascript: urls. "settime...
Document.readyState - Web APIs
ment is still loading. break; case "interactive": // the document has finished loading. we can now access the dom elements. // but sub-resources such as images, stylesheets and frames are still loading. var span = document.createelement("span"); span.textcontent = "a <span> element."; document.body.appendchild(span); break; case "complete": // the page is fully loaded. ...
...ch as images, stylesheets and frames are still loading. var span = document.createelement("span"); span.textcontent = "a <span> element."; document.body.appendchild(span); break; case "complete": // the page is fully loaded. ...
...till loading. var span = document.createelement("span"); span.textcontent = "a <span> element."; document.body.appendchild(span); break; case "complete": // the page is fully loaded. ...
... living standard h...
Document - Web APIs
Web › API › Document
the dom tree includes elements such as <body> and <table>, among many others. it provides functionality globally to the document, like how to obtain the page's url and create new elements in the document. ...
...only returns a list of the style sheet sets available on the document. document.timelineread only returns timeline as a special instance of documenttimeline that is automatically created on page load. document.undomanager read only … document.visibilitystateread only returns a string denoting the visibility state of the document. possible values are visible, hidden, prerender, and unloaded. the document interface is extended with the parentnode interface: parentnode.childelementcount read only returns the number of children of this parentnode which are elements. parentnode.children read only returns a live htmlcollection containing all of the element objects that are children of this parentnode, omitting all of its non-element nodes. parentnode.firstelementchild read onl...
...keydown event is raised. globaleventhandlers.onkeypress is an eventhandler representing the code to be called when the keypress event is raised. globaleventhandlers.onkeyup is an eventhandler representing the code to be called when the keyup event is raised. globaleventhandlers.onload is an eventhandler representing the code to be called when the load event is raised. globaleventhandlers.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 res...
...e. also available via the onfullscreenerror property. keyboard events keydown fired when a key is pressed. also available via the onkeydown property. keypress fired when a key that produces a character value is pressed down. also available via the onkeypress property. keyup fired when a key is released. also available via the onkeyup property. load & unload events domcontentloaded fired when the document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. readystatechange fired when the readystate attribute of a document has changed. also available via the onreadystatechange property. pointer events gotpointercapture fired when when an element captures a pointer using setpointercapture(). also availabl...
HTMLImageElement.loading - Web APIs
timize page performance. the possible values are: eager the default behavior, eager tells the browser to load the image as soon as the <img> element is processed. lazy tells the user agent to hold off on loading the image until the browser estimates that it will be needed imminently. for instance, if the user is scrolling through the document, a value of lazy will cause the image to only be loaded shortly before it will appear in the window's visual viewport. usage notes timing of the load event the load event is fired when the document has been fully processed. when images are loaded eagerly (which is the default), every image in the document must be fetched before the load event can fire. by specifying the value lazy for loading, you prevent the image from delaying the load attribut...
...(which is the default), every image in the document must be fetched before the load event can fire. by specifying the value lazy for loading, you prevent the image from delaying the load attribute by the amount of time it takes to request, fetch, and process the image. ...
...loading, you prevent the image from delaying the load attribute by the amount of time it takes to request, fetch, and process the image. images whose loading attribute is set to lazy but are located within the visual viewport immediately upon initial page load are loaded as soon as the layout is known, but their loads do not delay the firing of the load event. in other words, these images aren't loaded immediately when processing the <img> element, but are still loaded as part of the initial page load. they justt don't affect the timing of the load event. that means that when load fires, it's possible that any lazy-loaded images located in the visual viewport may not yet be visible. preventing element shift during image lazy loads when an image whose loading has been delayed by the loading a...
... element, but are still loaded as part of the initial page load. they justt don't affect the timing of the load event. that means that when load fires, it's possible that any lazy-loaded images located in the visual viewport may not yet be visible. preventing element shift during image lazy loads when an image whose loading has been delayed by the loading attribute being set to lazy is finally loaded, the browser will determine the final size of the <img> element based on the style and intrinsic size of the image, then reflow the document as needed to update the positions of elements based on any size change made to the element to fit the image. to prevent this reflow from occurring, you should explicitly specify the size of the image's presentation using the image element's width and height...
Request.cache - Web APIs
Web › API › Request › cache
ues are: default — the browser looks for a matching request in its http cache. if there is a match and it is fresh, it will be returned from the cache. if there is a match but it is stale, the browser will make a conditional request to the remote server. if the server indicates that the resource has not changed, it will be returned from the cache. otherwise the resource will be downloaded from the server and the cache will be updated. if there is no match, the browser will make a normal request, and will update the cache with the downloaded resource. no-store — the browser fetches the resource from the remote server without first looking in the cache, and will not update the cache with the downloaded resource. reload — the browser fetches the resource from the remote...
...l make a normal request, and will update the cache with the downloaded resource. no-store — the browser fetches the resource from the remote server without first looking in the cache, and will not update the cache with the downloaded resource. reload — the browser fetches the resource from the remote server without first looking in the cache, but then will update the cache with the downloaded resource. no-cache — the browser looks for a matching request in its http cache. if there is a match, fresh or stale, the browser will make a conditional request to the remote server. if the server indicates that the resource has not changed, it will be returned from the cache. otherwise the resource will be downloaded from the server and the cache will be updated. if there is no matc...
...e. if there is a match, fresh or stale, the browser will make a conditional request to the remote server. if the server indicates that the resource has not changed, it will be returned from the cache. otherwise the resource will be downloaded from the server and the cache will be updated. if there is no match, the browser will make a normal request, and will update the cache with the downloaded resource. force-cache — the browser looks for a matching request in its http cache. if there is a match, fresh or stale, it will be returned from the cache. if there is no match, the browser will make a normal request, and will update the cache with the downloaded resource. only-if-cached — the browser looks for a matching request in its http cache. if there is a ma...
...cts will be followed if the request's redirect property is "follow" and the redirects do not violate the "same-origin" mode. example // download a resource with cache busting, to bypass the cache // completely. fetch("some.json", {cache: "no-store"}) .then(function(response) { /* consume the response */ }); // download a resource with cache busting, but update the http // cache with the downloaded resource. fetch("some.json", {cache: "reload"}) .then(function(response) { /* consume the response */ }); // download a resource with cache busting when dealing with a // properly configured server that will send the correct etag // and date headers and properly handle if-modified-since and // if-none-match request headers, therefore we can rely on the // validation to guarantee a fresh respon...
Service Worker API - Web APIs
r control over everything. note: service workers make heavy use of promises, as generally they will wait for responses to come through, after which they will respond with a success or failure action. the promises architecture is ideal for this. registration a service worker is first registered using the serviceworkercontainer.register() method. ...
...ster() method. if successful, your service worker will be downloaded to the client and attempt installation/activation (see below) for urls accessed by the user inside the whole origin, or inside a subset specified by you. download, install and activate at this point, your service worker will observe the following lifecycle: download install activate the service worker is immediately downloaded when a user first accesses a service worker–controlled site/page. after that, it is updated when: a navigation to an in-scope page occurs. an event is fired on the service worker and it hasn't been downloaded in the last 24 hours. ...
...rker will observe the following lifecycle: download install activate the service worker is immediately downloaded when a user first accesses a service worker–controlled site/page. after that, it is updated when: a navigation to an in-scope page occurs. an event is fired on the service worker and it hasn't been downloaded in the last 24 hours. installation is attempted when the downloaded file is found to be new — either different to an existing service worker (byte-wise compared), or the first service worker encountered for this page/site. if this is the first time a service worker has been made available, installation is attempted, then after a successful installation, it is activated. if there is an existing service worker available, the new version is installed in the back...
...r this page/site. if this is the first time a service worker has been made available, installation is attempted, then after a successful installation, it is activated. if there is an existing service worker available, the new version is installed in the background, but not yet activated — at this point it is called the worker in waiting. it is only activated when there are no longer any pages loaded that are still using the old service worker. as soon as there are no more pages to be loaded, the new service worker activates (becoming the active worker). activation can happen sooner using serviceworkerglobalscope.skipwaiting() and existing pages can be claimed by the active worker using clients.claim(). you can listen for the installevent; a standard action is to prepare your service worker ...
Media events - Developer guides
gh_data, indicating that the entire media can be played without interruption, assuming the download rate remains at least at the current level. it will also be fired when playback is toggled between paused and playing. note: manually setting the currenttime will eventually fire a canplaythrough event in firefox. other browsers might not fire this event. durationchange the metadata has loaded or changed, indicating a change in duration of the media. this is sent, for example, when the media has loaded enough that the duration is known. 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. encrypted the user agent has encountered initializat...
... loadstart sent when loading of the media begins. ...
... 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 time you receive...
...ibute. 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 is unexpectedly not forthcoming. suspend sent when loading of the media i...
<audio>: The Embed Audio element - HTML: Hypertext Markup Language
Web › HTML › Element › audio
position, in seconds, of the audio. if the audio's metadata isn't available yet—thereby preventing you from knowing the media's start time or duration—currenttime instead indicates, and can be used to change, the time at which playback will begin. otherwise, setting currenttime sets the current playback position to the given time and seeks the media to that position if the media is currently loaded. if the audio is being streamed, it's possible that the user agent may not be able to obtain some parts of the resource if that data has expired from the media buffer. other audio may have a media timeline that doesn't start at 0 seconds, so setting currenttime to a time before that would fail. for example, if the audio's media timeline starts at 12 hours, setting currenttime to 3600 would be a...
...tart upon reaching the end of the audio. muted a boolean attribute that indicates whether the audio will be initially silenced. its default value is false. 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. it may have one of the following values: none: indicates that the audio should not be preloaded. metadata: indicates that only audio metadata (e.g. length) is fetched. 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 au...
...o 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 the input buffer of a scriptprocessornode is ready to be processed. canplay the browser can play the media, but estimates that not enough data has been loaded to play the media up to its end without having to stop for further buffering of content. canplaythrough the browser estimates it can play the media up to its end without stopping for content buffering. complete the rendering of an offlineaudiocontext is terminated. durationchange the duration attribute has been updated. emptied the media has become ...
...uffering of content. canplaythrough the browser estimates it can play the media up to its end without stopping for content buffering. complete the rendering of an offlineaudiocontext is terminated. 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 read...
<video>: The Video Embed element - HTML: Hypertext Markup Language
Web › HTML › Element › video
ormation. currenttime reading currenttime returns a double-precision floating-point value indicating the current playback position of the media specified in seconds. if the media has not started playing yet, the time offset at which it will begin is returned. setting currenttime sets the current playback position to the given time and seeks the media to that position if the media is currently loaded. if the media is being streamed, it's possible that the user agent may not be able to obtain some parts of the resource if that data has expired from the media buffer. other media may have a media timeline that doesn't start at 0 seconds, so setting currenttime to a time before that would fail. the getstartdate() method can be used to determine the beginning point of the media timeline's refere...
...een. 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: none: indicates that the video should not be preloaded. metadata: indicates that only video metadata (e.g. length) 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 bro...
...lement 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 event name fired when audioprocess the input buffer of a scriptprocessornode is ready to be processed. canplay the browser can play the media, but estimates that not enough data has been loaded to play the media up to its end without having to stop for further buffering of content. canplaythrough the browser estimates it can play the media up to its end without stopping for content buffering. complete the rendering of an offlineaudiocontext is terminated. durationchange the duration attribute has been updated. emptied the media has become ...
...uffering of content. canplaythrough the browser estimates it can play the media up to its end without stopping for content buffering. complete the rendering of an offlineaudiocontext is terminated. 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 read...
HTML documentation index - HTML: Hypertext Markup Language
Web › HTML › Index
ly used to describe a web page's appearance/presentation (css) or functionality/behavior (javascript). 2 allowing cross-origin use of images and canvas advanced, cors, canvas, html, image, reference, security, storage, data html provides a crossorigin attribute for images that, in combination with an appropriate cors header, allows images defined by the <img> element that are loaded from foreign origins to be used in a <canvas> as if they had been loaded from the current origin. 3 applying color to html elements using css beginner, css, css colors, guide, html, html colors, html styles, styling html, color with css, there are lots of ways to add color to your html elements to create just the look you want. this article is a primer introducing each of the...
...ment, html, html root element, reference, web the html <html> element represents the root (top-level element) of an html document, so it is also referred to as the root element. all other elements must be descendants of this element. 113 manifest cache, application cache the manifest attribute of <html> element specifies a url of a application cache manifest that is downloaded in the early stages of page load. 114 <i>: the idiomatic text element element, html, html text-level semantics, reference, web, em the html idiomatic text element (<i>) represents a range of text that is set off from the normal text for some reason, such as idiomatic text, technical terms, taxonomical designations, among others. 115 <iframe>: the inline frame eleme...
...to let the user enter and edit an e-mail address, or, if the multiple attribute is specified, a list of e-mail addresses. 126 <input type="file"> directory picker, file, file picker, files, form input, html, html forms, input type, reference, type <input> elements with type="file" let the user choose one or more files from their device storage. once chosen, the files can be uploaded to a server using form submission, or manipulated using javascript code and the file api. 127 <input type="hidden"> element, forms, html, html forms, input, input types, reference, hidden <input> elements of type hidden let web developers include data that cannot be seen or modified by users when a form is submitted. for example, the id of the content that is currently being ...
...ipates in the table model. 205 <template>: the content template element element, html, html web components, html:flow content, html:metadata content, html:phrasing content, html:script-supporting element, reference, template, web, web components 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. 206 <textarea> element, forms, html, html forms, reference, web, textarea the html <textarea> element represents a multi-line plain-text editing control, useful when you want to allow users to enter a sizeable amount of free-form text, for example a comment on a review or feedback form. 207 <tfoo...
Preloading content with rel="preload" - HTML: Hypertext Markup Language
oads, but the benefits can be seen much more clearly 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: audi...
...we use window.matchmedia / mediaquerylist to do this (see testing media queries for more). this makes it much more likely that the font will be available for the page render, cutting down on fout (flash of unstyled text). this doesn't have to be limited to images, or even files of the same type — thin...
...); var header = document.queryselector('header'); if (mediaquerylist.matches) { header.style.backgroundimage = 'url(bg-image-narrow.png)'; } else { header.style.backgroundimage = 'url(bg-image-wide.png)'; } </script> </body> we include media attributes on our <link> elements so that a narrow image is preloaded if the user has a narrow viewport, and a wider image is loaded if they have a wide viewport. we use window.matchmedia / mediaquerylist to do this (see testing media queries for more). this makes it much more likely that the font will be available for the page render, cutting down on fout (flash of unstyled text). this doesn't have to be limited to images, or even files of the same type — think big! you could perhaps preload and display a simple svg diagr...
...pt. for example, here we create a htmllinkelement instance, then attach it to the dom: var preloadlink = document.createelement("link"); preloadlink.href = "myscript.js"; preloadlink.rel = "preload"; preloadlink.as = "script"; document.head.appendchild(preloadlink); this means that the browser will preload the myscript.js file, but not actually use it yet. to use it, you could do this: var preloadedscript = document.createelement("script"); preloadedscript.src = "myscript.js"; document.body.appendchild(preloadedscript); this is useful when you want to preload a script, but then defer execution until exactly when you need it. other resource preloading mechanisms other preloading features exist, but none are quite as fit for purpose as <link rel="preload">: <link rel="prefetch"> has bee...
Cross-Origin Resource Sharing (CORS) - HTTP
Web › HTTP › CORS
code served from https://domain-a.com uses xmlhttprequest to make a request for https://domain-b.com/data.json. for security reasons, browsers restrict cross-origin http requests initiated from scripts. for example, xmlhttprequest and the fetch api follow the same-origin policy. this means that a web application using those apis can only request resources from the same origin the application was loaded from unless the response from other origins includes the right cors headers. the cors mechanism supports secure cross-origin requests and data transfers between browsers and servers. modern browsers use cors in apis such as xmlhttprequest or fetch to mitigate the risks of cross-origin http requests. who should read this article? everyone, really. more specifically, this article is for web a...
...gin sharing from a server perspective (with php code snippets) is supplementary reading. what requests use cors? this cross-origin sharing standard can enable cross-site http requests for: invocations of the xmlhttprequest or fetch apis, as discussed above. web fonts (for cross-domain font usage in @font-face within css), so that servers can deploy truetype fonts that can only be cross-site loaded and used by web sites that are permitted to do so. webgl textures. images/video frames drawn to a canvas using drawimage(). css shapes from images. this article is a general discussion of cross-origin resource sharing and includes a discussion of the necessary http headers. functional overview the cross-origin resource sharing standard works by adding new http headers that let servers desc...
...d by both xmlhttprequest or fetch and cors is the ability to make "credentialed" requests that are aware of http cookies and http authentication information. by default, in cross-site xmlhttprequest or fetch invocations, browsers will not send credentials. a specific flag has to be set on the xmlhttprequest object or the request constructor when it is invoked. in this example, content originally loaded from http://foo.example makes a simple get request to a resource on http://bar.other which sets cookies. content on foo.example might contain javascript like this: const invocation = new xmlhttprequest(); const url = 'http://bar.other/resources/credentialed-content/'; function callotherdomain() { if (invocation) { invocation.open('get', url, true); invocation.withcredentials = true; ...
..."*" wildcard, the credential-cognizant content is returned to the invoking web content. note that the set-cookie response header in the example above also sets a further cookie. in case of failure, an exception—depending on the api used—is raised. third-party cookies note that cookies set in cors responses are subject to normal third-party cookie policies. in the example above, the page is loaded from foo.example, but the cookie on line 20 is sent by bar.other, and would thus not be saved if the user has configured their browser to reject all third-party cookies. the http response headers this section lists the http response headers that servers send back for access control requests as defined by the cross-origin resource sharing specification. the previous section gives an overview of ...
Advanced Example - XSLT: Extensible Stylesheet Language Transformations
using the xsltprocessor.getparameter() method, the code can figure whether to sort in ascending or descending order. ...
...xpression. once the transformation is complete, the result is appended to the document, as shown in this example. ...
... // importnode is ...
...<div>10</div> </div> // javascript var xslref; var xslloaded = false; var xsltprocessor = new xsltprocessor(); var mydom; var xmlref = document.implementation.createdocument("", "", null); function sort() { if (!xslloaded){ p = new xmlhttprequest(); p.open("get", "example2.xsl", false); p.send(null); xslref = p.responsexml; xsltprocessor.importstylesheet(xslref); xslloaded = true; } // create a new xml document in memory xmlref = document.implementation.createdocument("", "", null); // we want to move a part of the dom from an html document to an xml document. // importnode is used to clone the nodes we want to process via xslt - true makes it do a deep clone var mynode = document.getelementbyid("example"); var clonednode = xmlref.importnode(mynode,...
windows - Archive of obsolete content
determine whether the new window should be private or not. if your add-on does not support private browsing this will have no effect. see the private-browsing documentation for more information. optional options: name type onopen function a callback function that is called when the window has opened. this does not mean that the url content has loaded, only that the window itself is fully functional and its properties can be accessed. this is an optional property. onclose function a callback function that is called when the window will be called. this is an optional property. onactivate function a callback function that is called when the window is made active. this is an optional property. ...
... console.log("a window was closed."); }); // add a listener to the 'activate' event windows.on('activate', function(window) { console.log("a window was activated."); }); // add a listener to the 'deactivate' event windows.on('deactivate', function(window) { console.log("a window was deactivated."); }); open event emitted when a new window is open. ...
... arguments window : listeners are passed the window object that triggered the event. activate event emitted when an inactive window is made active. arguments window : listeners are passed the window object that has become active. deactivate event emitted when the active window is made inactive. ...
content/loader - Archive of obsolete content
let frame = self._frame = this.element; self._emit('propertychange', { contenturl: self.contenturl }); } })); }, _onchange: function _onchange(e) { if ('contenturl' in e) this._frame.setattribute('src', this._contenturl); } }); loader properties contentscriptfile the local file urls of content scripts to load. content scripts specified by this property are loaded before those specified by the contentscript property. contentscript the texts of content scripts to load. content scripts specified by this property are loaded after those specified by the contentscriptfile property. contentscriptwhen when to load the content scripts. this may take one of the following values: "start": load content scripts immediately after the document element for the pag...
...the texts of content scripts to load. content scripts specified by this property are loaded after those specified by the contentscriptfile property. contentscriptwhen when to load the content scripts. this may take one of the following values: "start": load content scripts immediately after the document element for the page is inserted into the dom, but before the dom content itself has been loaded "ready": load content scripts once dom content has been loaded, corresponding to the domcontentloaded event "end": load content scripts once all the content (dom, js, css, images) for the page has been loaded, at the time the window.onload event fires contentscriptoptions read-only value exposed to content scripts under self.options property. any kind of jsonable value (object, array, strin...
...onding to the domcontentloaded event "end": load content scripts once all the content (dom, js, css, images) for the page has been loaded, at the time the window.onload event fires contentscriptoptions read-only value exposed to content scripts under self.options property. any kind of jsonable value (object, array, string, etc.) can be used here. optional. contenturl the url of the content loaded. allow permissions for the content, with the following keys: ...
dev/panel - Archive of obsolete content
u can use it to do any cleanup. optional onready function an event handler that will be called when the document in the panel becomes interactive. it's equivalent to document.readystate === "interactive". at this point you can send the panel document messages. optional onload function an event handler that will be called after the document in the panel is fully loaded. it's equivalent to document.readystate === "complete". optional once you've defined the panel's constructor you have to export it so it can be called by the framework. creating a tool next, you need to create a new tool using the dev/toolbox module, initializing it with the newly defined constructor. example here's a complete main.js: // main.js // require the sdk modules const {...
...uggee; }, dispose: function() { this.debuggee = null; }, onready: function() { // in this function you can communicate // with the panel document } }); // export the constructor exports.mypanel = mypanel; // create a new tool, initialized // with the new constructor const mytool = new tool({ panels: { mypanel: mypanel } }); panel document environment the panel document loaded from the url property can of course include css and javascript just like a normal web page: <html> <head> <meta charset="utf-8"> <link href="./my-panel.css"rel="stylesheet"></link> <script src="resource://sdk/dev/volcan.js"></script> </head> <body> <div id="content"></div> </body> <script src="./my-panel.js"></script> </html> it doesn't have access to any privileged...
...cript> </html> it doesn't have access to any privileged apis, including the add-on sdk apis. however, it can receive messages from the add-on that created it, and the add-on can pass it the debuggee so it can communicate with the debugger server the developer tools are targeting. communicating with the panel document the main add-on code can't directly access the panel document or any scripts loaded by the panel document. however it can send messages to the panel document using the postmessage method of panel. this is closely modeled on window.postmessage. you can only send the panel document message after you've received the ready event. in the main add-on code: // main.js // require the sdk modules const { panel } = require("dev/panel"); const { tool } = require("dev/toolbox"); const { ...
frame/hidden-frame - Archive of obsolete content
ers, 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. ...
... globals constructors hiddenframe(options) creates a hidden frame. ...
... 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 frame. ...
remote/child - Archive of obsolete content
enables an sdk module loaded into a child process to access web content in the child process and communicate with modules in the main process. usage the sdk/remote/parent module enables sdk code to load modules into child processes. the sdk/remote/child module is for these "child process modules". it provides two main things: access to web content loaded into this child process port mechanisms to communicate with the main process interacting with web content to interact with web content, the sdk/remote/child module provides a frames property that's a list of all content frames loaded into this child process. each frame then has a content property that's the top-level dom window for the frame, and addeventlistener/removeeventlistener functions that enable you to listen to dom events ...
.... events attach triggered when a new content frame is opened (for example, the user opened a new tab). the event listener gets a frame object as an argument. at this point you can't access frame's content yet, but you can add event listeners: const { frames } = require("sdk/remote/child"); frames.on("attach", function(frame) { console.log("new frame"); frame.addeventlistener("domcontentloaded", function(e) { console.log(e.target.location.href); }); }); detach triggered when a frame is removed (for example, the user closed a tab). frame a frame represents a content frame in this process and provides a way to communicate frame specific events to the main process. methods addeventlistener(event, listener, iscapturing) adds an event listener for dom events dispatched by this ...
...ggered when a frame is removed (for example, the user closed a tab). frame a frame represents a content frame in this process and provides a way to communicate frame specific events to the main process. methods addeventlistener(event, listener, iscapturing) adds an event listener for dom events dispatched by this content frame. this can include load and unload events from any content that is loaded in the frame. listeners are automatically removed when this frame is destroyed. removeeventlistener(event, listener, iscapturing) removes an event listener that was previously registered. properties port an event emitter that can be used to send and receive frame specific events to and from code in the main process. content the top level dom window currently displaying in this frame. ista...
system/unload - Archive of obsolete content
therefore, when you register an object with ensure(), you can call its destructor method yourself, you can let it happen for you, or you can do both. the destructor will be called with a single argument describing the reason for the unload; see when(). if object does not have the expected destructor method, then an exception is thrown when ensure() is called. ...
...h a single argument describing the reason for the unload; see when(). if object does not have the expected destructor method, then an exception is thrown when ensure() is called. parameters object : object an object that defines a destructor method. name : string optional name of the destructor method. default is unload. when(callback) registers a function to be called when the module is unloaded. ...
...the expected destructor method, then an exception is thrown when ensure() is called. parameters object : object an object that defines a destructor method. name : string optional name of the destructor method. default is unload. when(callback) registers a function to be called when the module is unloaded. parameters callback : function a function that will be called when the module is unloaded. it is called with a single argument, one of the following strings describing the reason for unload: "uninstall", "disable", "shutdown", "upgrade", or "downgrade". if a reason could not be determined, undefined will be passed instead. note that if an add-on is unloaded with reason "disable", it will not be notified about "uninstall" while it is disabled. see bug 571049. ...
Canvas code snippets - Archive of obsolete content
yield new promise(accept => { reader.onloadend = accept }); return yield os.file.writeatomic(path, new uint8array(reader.result), { tmppath: path + '.tmp' }); }); } loading a remote page onto a canvas element the following class first creates a hidden iframe element and attaches a listener to the frame's load event. 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 code as a plain webpage, you will get a 'security error" code: "1000' error. remotecanvas = function() { this.url = 'http://developer.mozilla.org'; }; remotecanvas.canvas_w...
...th = window.innerwidth - 25; var iframe; iframe = document.createelement('iframe'); iframe.id = 'test-iframe'; iframe.height = '10px'; iframe.width = windowwidth + 'px'; iframe.style.visibility = 'hidden'; iframe.src = this.url; // here is where the magic happens... ...
...px'; iframe.width = windowwidth + 'px'; iframe.style.visibility = 'hidden'; iframe.src = this.url; // here is where the magic happens... ...
Extension Versioning, Update and Compatibility - Archive of obsolete content
<!-- one targetapplication for each application the add-on is compatible with --> <em:targetapplication> <rdf:description> <em:id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</em:id> <em:minversion>1.5</em:minversion> <em:maxversion>2.0.0.*</em:maxversion> <!-- this is where this version of the add-on will be downloaded from --> <em:updatelink>https://www.mysite.com/foobar2.2.xpi</em:updatelink> <!-- a page describing what is new in this updated version --> <em:updateinfourl>http://www.mysite.com/updateinfo2.2.xhtml</em:updateinfourl> </rdf:description> </em:targetapplication> </rdf:description> </rdf:li> <rdf:l...
...irements will be ignored when checking for new versions. note that https links to sites with invalid certificates or that redirect to http sites will fail for both the update.rdf and updatelink cases. updatelink using an https site with a non-builtin token ca signed certificate will fail regardless of whether or not updatehash is used. update hashes in order to verify the integrity of the downloaded xpi you may provide an updatehash entry alongside the updatelink. this should be a hash generated against the file data using one of the supported hashing algorithms (sha1, sha256, sha384 and sha512). in firefox 3 if the updatelink is not https then the hash must be made using one of the sha family of algorithms. the hashing algorithm used is put at the start of the string and separated from the ...
...om the hash by a :. <em:updatehash>sha256:78fc1d2887eda35b4ad2e3a0b60120ca271ce6e64ad2e3a0b60120ca271ce6e6</em:updatehash> note: the value of updatehash, must start with the string of hashing algorithm, it is a common error to delete this prefix, when setting new value to updatehash:sha256:78fc1d2887eda35b4ad2e3a0b60120ca271ce6e64ad2e3a0b60120ca271ce6e6 when a hash is specified the downloaded file is compared with the hash and an error shown if it does not match. there are quite a few tools you may use to generate hashes: various unix flavors include sha1sum, sha256sum and so on. windows users should consider hashtab for interactive (non-build-script) use. there are also gnu ports for win (besides usual suspects like cygwin), which are good for non-interactive use: sha256sum file ...
JavaScript Object Management - Archive of obsolete content
ired is normally not that much. if you have complex behavior that requires too much code, look for ways to divide it into multiple objects and files. you can include as many scripts in a xul window as you need. to initialize your chrome objects, it's usually better to run the initialization code from the "load" event handler for the window. the load event is fired after the dom on the window has loaded completely, but before it's displayed to the user. this allows you to manipulate and possibly change elements in the window without the user noticing the changes. /** * controls the browser overlay for the hello world extension. */ 〈namespace〉.browseroverlay = { /** * initializes this object. */ init : function(aevent) { this._stringbundle = document.getelementbyid("xulscho...
... */ init : function(aevent) { this._stringbundle = document.getelementbyid("xulschoolhello-string-bundle"); // you can make changes to the window dom here. } // more stuff }; window.addeventlistener( "load", function() { 〈namespace〉.browseroverlay.init(); }, false); there are some things you can't (or shouldn't) do inside load handlers, such as closing the window being loaded, or opening new windows, alerts or dialogs. the window has to finish loading before it can do any of these things. they are bad ui practices anyway and you should avoid them. if you really need to do something like this anyway, one way to do it is to have a timeout execute the code after a delay: init : function(aevent) { let that = this; this._stringbundle = document.getelementbyid("xs-h...
...o export, usually we just need the namespace object. all of the objects inside of it are exported as well, since they are members of the 〈modulenamespace〉 object. module files can be imported to a chrome script or to other code modules with the following line: components.utils.import("resource://xulschoolhello/messagecount.js"); when using components.utils.import, code modules must be loaded using a file: or resource: url pointing to a file on the disk. in particular, chrome: urls (even those that point to a file outside a jar archive) are not valid. to get a better idea, let's look at the code of the modified hello world example. we have defined two files, one to declare namespaces and another one for the message count functionality mentioned in the previous exercise. here again w...
Security best practices in extensions - Archive of obsolete content
a more detailed explanation of this process is in displaying web content in an extension without security issues. the privileges that a document gets also depend on where it comes from. for example, if you load a chrome url, this means the content has been registered with firefox and has full access. content from a domain (such as http://www.example.com) can only access that same domain. files loaded using the file protocol can access files on the user's disk and other local devices. there are ways to get around the content/chrome security barrier, if for example, you want a web page to send a notification to the add-on (or vice versa). one way to do this is to use custom dom events; see interaction between privileged and non-privileged pages. regardless of where the document comes from, you...
... better protection for data passed over the network. json has become a popular data format for return formats for web services. be sure to read using native json to find out the correct way to handle it. apis can't be used with self-signed certificates. remote javascript and content there are a number of ways of remote scripts being used in extensions. they can be included in content, or downloaded at intervals. non-chrome urls in chrome xul or html such as the following example are not allowed: <script type="text/javascript" src="http://mysite.greatsite.com/js/wow-content.js" /> in general, scripts that are from remote sources that run in the chrome context are not acceptable, as many times the source of the script can never be 100% guaranteed, and they are vulnerable to man-in-the-midd...
...e only legitimate environment for remote scripts is to run in a sandbox. for more information, refer to the evalinsandbox() section. evalinsandbox the evalinsandbox document explains very well how it works, so there will be no repetition here. the usefulness of it and power of how it works is best illustrated by the popular greasemonkey extension, which works on the premise of scripts being downloaded and stored locally, to be injected into the web content context via the sandbox. many extensions use the greasemonkey compiler to bundle it in their extension for convenience. if you choose to do so, beware when making edits to the bundled files so as not to break the well thought out security architecture. third-party javascript in the context of web sites, using javascript written by others i...
Visualizing an audio spectrum - Archive of obsolete content
note: you can use the audionode called analysernode to perform real-time fft analysis on an audio stream, rather than the code shown below. ...
... <audio id="audio-element" src="song.ogg" controls="true" style="width: 512px;"> </audio> <div><canvas id="fft" width="512" height="200"></canvas></div> <script> var canvas = document.getelementbyid('fft'), ctx = canvas.getcontext('2d'), channels, rate, framebufferlength, fft; function loadedmetadata() { channels = audio.mozchannels; rate = audio.mozsamplerate; framebufferlength = audio.mozframebufferlength; fft = new fft(framebufferlength / channels, rate); } function audioavailable(event) { var fb = event.framebuffer, t = event.time, /* unused, but it's there */ signal = new float32a...
...+ ) { // multiply spectrum by a zoom value magnitude = fft.spectrum[i] * 4000; // draw rectangle bars for each frequency bin ctx.fillrect(i * 4, canvas.height, 3, -magnitude); } } var audio = document.getelementbyid('audio-element'); audio.addeventlistener('mozaudioavailable', audioavailable, false); audio.addeventlistener('loadedmetadata', loadedmetadata, false); // fft from dsp.js, see below var fft = function(buffersize, samplerate) { this.buffersize = buffersize; this.samplerate = samplerate; this.spectrum = new float32array(buffersize/2); this.real = new float32array(buffersize); this.imag = new float32array(buffersize); this.reverset...
Structure of an installable bundle - Archive of obsolete content
ed for security reasons, and can normally only provide a chrome.manifest which registers the theme and a jar file. platform-specific files gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) removed support for platform-specific subdirectories, described below. instead, you need to use manifest flags, such as the os and abi flags, in your chrome manifest to specify components that should be loaded for specific platforms. for example: binary-component components/windows/mycomponent.dll abi=winnt_x86-msvc binary-component components/mac/mycomponent.dylib abi=darwin_x86-gcc3 binary-component components/mac/mycomponent64.dylib abi=darwin_x86_64-gcc3 binary-component components/linux/mycomponent.so abi=linux_x86-gcc3 this also means you can no longer have platform-specific preference files ...
.../app loader has special sub-directories specifically for platform-specific files (starting with toolkit/gecko 1.8, firefox/thunderbird 1.5). the platform string is defined during the toolkit build process to a value unique for the combination of operating system, processor architecture and compiler. the format of the platform string is: {os_target}_{target_xpcom_abi} all of the files which are loaded from the main extension directory are loaded from the subdirectory /platform/{platform string} if it exists. for example, if a plugin vendor wanted to make a plugin available for consumer computers running linux(of the form: /platform/linux*/), macintosh(of the form: /platform/darwin*/), and windows(of the form: /platform/win*/), it would provide the following files: /platform/linux_x86-gcc3/...
...mytheme-base.jar platform/darwin/chrome.manifest platform/darwin/chrome/mytheme-mac.jar platform/winnt/chrome.manifest platform/winnt/chrome/mytheme-win.jar the app/extension loader processes the base directory first, followed by the applicable platform directories (first /{os_target}/, then /{os_target}_{target_xpcom_abi}/). when default preferences are defined in several directories, the ones loaded later overwrite the earlier ones. official references for toolkit api structure of an installable bundle: describes the common structure of installable bundles, including extensions, themes, and xulrunner applications extension packaging: specific information about how to package extensions theme packaging: specific information about how to package themes multiple-item exten...
Download Manager preferences - Archive of obsolete content
default value is false. ...
...e removed automatically. in firefox and seamonkey the default value is 2. in thunderbird the default value is 1; if the preference is missing, the value 0 is used. browser.download.manager.scanwhendone a boolean value that indicates whether or not to perform virus scans after downloads are complete. on windows xp sp2 and windows vista, this value also indicates whether downloaded files trigger a security warning upon launch. default value is true. browser.download.manager.showalertinterval the minimum number of milliseconds that must elapse between download complete alerts; if two downloads complete within this amount of time, only one alert is displayed. default value is 2000 (2 seconds). browser.download.manager.showalertoncomplete a bool...
...rence is not set when the download manager looks it up, the download manager assumes the default value but doesn't necessarily add the missing preference. the following table however, includes preferences which must be included in any product for the download manager to function. preference description browser.download.dir a local folder the user may have selected for downloaded files to be saved. migration of other browser settings may also set this path. this folder is enabled when browser.download.folderlist equals 2. browser.download.folderlist indicates the default folder to download a file to. 0 indicates the desktop; 1 indicates the systems default downloads location; 2 indicates a custom (see: browser.download.dir) folder. in firefox 3 and e...
JavaScript Client API - Archive of obsolete content
you acknowledge that you will need to install and use a local version of the firefox sync server for multiple account testing and that any use of mozilla’s hosted firefox sync services is subject to mozilla’s firefox sync terms of service at https://services.mozilla.com/tos/. ...
...files in the services/sync/ directory of mozilla-central or similar repository. terminology syncengine the main sync client object. it's what starts all the magic. engine governs the synchronizing of a specific set of information. e.g. there is an engine for bookmarks, tabs, history, preferences, etc. record piece of information that gets synchronized. records are transformed to wbo's, uploaded to a collection in a sync server and eventually downloaded by other sync clients. tracker entity that tracks changes to data. each engine has a corresponding tracker which listens for changes to data or events it is interested in. when something of interest occurs, it interacts with the engine to let it know something has happened and it might want to take action store entity that serves as a...
... getallids() must return an iterable list containing the guids of every item being stored on the local system. this can be a dictionary-type object where the keys are the guids and the values are whatever; or it can simply be a list of guids. this is the method that the engine will call the first time it syncs, in order to get a complete inventory of what data there is that will need to be uploaded to the server. unless the items you're syncing have their own inherent guids already defined, you'll need to invent guids for all your items at this time. when one of these guids is later passed as an argument to createrecord(), you need to return a record based on the matching data. therefore, it's the responsibility of this method to define the guid -> item mapping, and to store it for later re...
jspage - Archive of obsolete content
s(d,b); }}else{if(c[a]){c[a].keys.each(function(e){this.addevent(a,e);},this);}}return this;}});element.nativeevents={click:2,dblclick:2,mouseup:2,mousedown:2,contextmenu:2,mousewheel:2,dommousescroll:2,mouseover:2,mouseout:2,mousemove:2,selectstart:2,selectend:2,keydown:2,keypress:2,keyup:2,focus:2,blur:2,change:2,reset:2,select:2,submit:2,load:1,unload:1,beforeunload:2,resize:1,move:1,domcontentloaded:1,readystatechange:1,error:1,abort:1,scroll:1}; (function(){var a=function(b){var c=b.relatedtarget;if(c==undefined){return true;}if(c===false){return false;}return($type(this)!="document"&&c!=this&&c.prefix!="xul"&&!this.haschild(c)); };element.events=new hash({mouseenter:{base:"mouseover",condition:a},mouseleave:{base:"mouseout",condition:a},mousewheel:{base:(browser.engine.gecko)?"dommousescro...
...b=this,c=0;while((b=b.previoussibling)){if(b.nodetype==1&&++c>a){return false;}}return(c==a);},even:function(b,a){return selectors.pseudo["nth-child"].call(this,"2n+1",a); },odd:function(b,a){return selectors.pseudo["nth-child"].call(this,"2n",a);},selected:function(){return this.selected;},enabled:function(){return(this.disabled===false); }});element.events.domready={onadd:function(a){if(browser.loaded){a.call(this);}}};(function(){var b=function(){if(browser.loaded){return;}browser.loaded=true; window.fireevent("domready");document.fireevent("domready");};window.addevent("load",b);if(browser.engine.trident){var a=document.createelement("div"); (function(){($try(function(){a.doscroll();return document.id(a).inject(document.body).set("html","temp").dispose();}))?b():arguments.callee.delay(50);})...
...ser.loaded=true; window.fireevent("domready");document.fireevent("domready");};window.addevent("load",b);if(browser.engine.trident){var a=document.createelement("div"); (function(){($try(function(){a.doscroll();return document.id(a).inject(document.body).set("html","temp").dispose();}))?b():arguments.callee.delay(50);})(); }else{if(browser.engine.webkit&&browser.engine.version<525){(function(){(["loaded","complete"].contains(document.readystate))?b():arguments.callee.delay(50); })();}else{document.addevent("domcontentloaded",b);}}})();var json=new hash(this.json&&{stringify:json.stringify,parse:json.parse}).extend({$specialchars:{"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},$replacechars:function(a){return json.$specialchars[a]||"\\u00"+math.floor(a.charcodeat()/...
Scripting - Archive of obsolete content
preload just before the user interface is displayed. ...
...preload just before the user interface is displayed. ...
...preload just before the user interface is displayed. returning false causes the application to terminate. load after the main application windows has finished loading. ...
Safely loading URIs - Archive of obsolete content
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. ...
...hods are exposed on the nsiscriptsecuritymanager interface and are called checkloaduri, checkloaduriwithprincipal, and checkloaduristr. all three methods take three arguments: the first argument identifies the source of the uri, the second argument is the uri that one plans to load, and the third argument is a set of flags that can be used to impose additional restrictions on the uris that may be loaded. it's important to make sure that the first argument to these methods identifies the source of the uri. so if you're implementing a context menu and you add a "view image" option, the source of the image uri would be the page the image is in, not the chrome document the context menu code is in. differences between the methods the three methods differ from each other in how the source of the uri...
... these methods identifies the source of the uri. so if you're implementing a context menu and you add a "view image" option, the source of the image uri would be the page the image is in, not the chrome document the context menu code is in. differences between the methods the three methods differ from each other in how the source of the uri is identified and in what is known about the uri to be loaded. in general, the following guidelines apply for gecko 1.8: if you plan pass a uri string to nsiwebnavigation.loaduri (which can happen indirectly, e.g. by passing the string to something that loads it in a <browser> or <iframe>), you must call checkloaduristr to be secure. there's no way to do this completely securely in gecko versions prior to 1.8.0.4. if you're doing anything else (passing...
Venkman Internals - Archive of obsolete content
be set on some source lines some of the time? sometimes the source has small ticks in the margin for every executable line in my javascript. sometimes these ticks are missing on some or all lines of a file. only lines with tick marks seem to break point properly. venkman asks the js engine which lines are executable. it will mark these with a "tick" as you call it. if the file is not currently loaded, the js engine doesn't know anything about the file. you can still set breakpoints, but they will be future breakpoints, which will be "real" breakpoints when/if the file is loaded (note that this may never happen!). note also that this is just my knowledge of venkman, which is quite limited. you would be better off asking silver (james ross). gijskruitbosch 05:41, 7 march 2007 (pst) venkman-de...
...there is one scriptmanager per url (web page). this method is set into jsdiscripthook.onscriptcreated venkman-views.js views are the panels shown within the venkman window. for example, the "open windows" view shows the browser's windows. ...
...you can set and clear breakpoints by line number (instead of by program counter), locate a scriptwrapper for a given line number, and do a few other useful things. scriptinstance.functions is a hash of all of the functions in the script instance, keyed by the tag property of the jsdscript. scriptinstance.toplevel is the top-level script for the instance. scriptmanager sometimes the same url is loaded more than once in the browser. to deal with this, all scriptinstances are parented by a single scriptmanager. a scriptmanager keeps all of the loaded instances of a particular url in the scriptmanager.instances array, in the order that they were loaded. from here, you can set and clear breakpoints in all instances. scriptmanager.transients is a hash of all of the "transient" scripts from this url...
Using Breakpoints in Venkman - Archive of obsolete content
uture" breakpoint, represents a promise from venkman to set a hard breakpoint as soon as it is possible. future breakpoints are used when you want to stop in a script that has not yet been compiled. the most common use of future breakpoints is to stop in a "top level" script (script that executes outside of any function), or script that executes during the onload event of a page. when a script is loaded that matches the url of a future breakpoint, and has executable code at the specified line, venkman will automatically set a future breakpoint. except for this distinction, breakpoints in venkman work like breakpoints in most other debuggers. the dots you see in the left margin of the source code view indicate which lines contain executable code, places where a hard breakpoint can be set. settin...
...et, the margin will change to the letter "b", as in figure 2. if you execute this code again after having set this breakpoint, venkman will stop at line 81. (note: by default, venkman hides files file that appear to be part of the browser core; this includes extensions. to debug an extension, uncheck "exclude browser files" on the debug menu and your installed extension files should appear in the loaded scripts list.) venkman also indicates that one or more breakpoints have been set in the loaded scripts view, where red dots appear next to the files in which breakpoints have been set, along with the line number where the function begins whose code is being stopped. using breakpoints to debug when you set a breakpoint, you give venkman (or whatever debugger you're using) the opportunity to disp...
...stop if the result is true. the //@jsd_eval command will insert a breakpoint which is set to execute the script that follows without stopping and without logging the result. these meta comments can be used to insert debug-only code in your scripts with zero impact on production code. to enable meta comments in a script, select "scan for meta comments" from the context menu of the file in the loaded scripts view. when you add a meta comment, a normal breakpoint is created. you can change or delete this breakpoint just as you would a breakpoint created by hand. resources venkman introduction—previous article on venkman. venkman's home page on devmo. original document information authors: robert ginda, ian oeschger published 02 may 2003 ...
International characters in XUL JavaScript - Archive of obsolete content
gecko 1.8, as used in firefox 1.5 and other applications, added support for non-ascii characters in javascript files loaded from xul files. this means that such script files can use any character from virtually any language of the world. for example, they can contain a line: var text = "ein schönes beispiel eines mehrsprachigen textes: 日本語"; this mixes german and japanese characters. earlier versions always interpreted js files loaded from xul as iso-8859-1 (latin-1), in both local and remote cases. unicode escapes, as discussed below, have always worked. how the character encoding is determined in gecko 1.8 and later when the javascript file is loaded from a chrome:// url, a byte order mark (fixme: )(bom) is used to determine the character encoding of the script. otherwise...
... cross-version compatibility if you want the same code to work in both gecko 1.8 and earlier versions, you must limit yourself to ascii. ...
..., you must limit yourself to ascii. however, you can use unicode escapes – the earlier example rewritten using them would be: var text = "ein sch\u00f6nes beispiel eines mehrsprachigen textes: \u65e5\u672c\u8a9e"; an alternative might be to use property files via nsistringbundle or the xul <stringbundle> element; this would allow for localization of the xul. this can not be done in xul files loaded from the web, only in privileged code, e.g. in extensions. ...
Sorting and filtering a custom tree view - Archive of obsolete content
because of bug 340478, this code will only work from privileged script. ...
...because of bug 340478, this code will only work from privileged script. ...
...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...
Filtering - Archive of obsolete content
e to generate the items on a menu or in a listbox or tree. the syntax is the same regardless of what type of content is being created. in the previous example, we hard-coded a menulist with the list of countries, but we could also generate this list from the datasource. the same datasource may used for both the photos list and the menulist. even though the same datasource is used, it will only be loaded once and both templates will be notified when the data has loaded. we will need to add some information to the datasource in order to specify the list of countries that are available. there are two possibilities. first, a separate seq could be added listing the countries. then, a simple <member> element can be used to iterate over it. or, we could use an rdf type to specify the countries. then, w...
...untrytitle" value="?country"/> </menupopup> </action> the result will be two generated menuitems, one for each country, inside a menupopup. the value attribute is assigned the ?country variable so that the applyfilter function can use this value easily for filtering. the complete example shows this working. note that due to a bug with template generation in menulists when the datasource hasn't loaded yet, you may have to load the example twice to get it work. this issue only affects the menulist element. several workarounds can be used in this simple example. first, you could move the <menupopup> element outside of the template and put the datasources attribute on it instead of the <menulist> element. this will work in this simple example, but has the disadvantage that the builder won't be ab...
...in this simple example. first, you could move the <menupopup> element outside of the template and put the datasources attribute on it instead of the <menulist> element. this will work in this simple example, but has the disadvantage that the builder won't be able to generate the content lazily only when the popup is opened. another workaround is to just rebuild the template once the data has been loaded. next, we will look at how to add the all choice to the menu, which won't be generated from the datasource. « previousnext » ...
Introduction - Archive of obsolete content
lanet.com/ds/sample.rdf" querytype="rdf"> this example specifies the datasource 'http://www.xulplanet.com/ds/sample.rdf', using the datasource type rdf as indicated by the querytype attribute'. we'll look at rdf datasources first. the template builder loads an rdf datasource using the rdf service in the same way as you would create a datasource through the rdf service directly. the 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 dataso...
...if some results can be created. if so, some content can be generated. if not, nothing gets generated again. an interesting thing to note is that due to the nature of the rdf parsing process, the builder generates results and builds content incrementally while the data arrives. of course, since the data arrives so quickly from the network, you really don't notice this. ...
...for example: <listbox datasources="http://www.xulplanet.com/ds/sample.xml" querytype="xml"> <template> <listitem label="?name"/> </template> </listbox> this template uses an xml datasource to generate a listbox. ...
Complete - Archive of obsolete content
outlines how to add them. if you want to see these techniques in action, then you can download and install the complete allcustom extension: allcustom.xpi (the link is external only because this wiki does not support xpi files.) the extension does not contain any useful functions. it is just an extended code sample. to see the code, use a jar tool or zip tool to unpack the xpi file that you downloaded. for more information about developing extensions, see the main extensions page here. features of this extension this extension is a more complex version of the original custom toolbar button extension. it provides a user interface in two languages (english and french). it supports firefox, thunderbird, sunbird and flock—these are referred to as "firefox etc." in the rest of this page. it also ...
...xample, if your locale is fr-fr, it loads: locale/fr-fr/allcustom/allcustom.dtd from inside the jar file. when you restart after installing the extension, the locales en-us and fr-fr are both registered for the component allcustom. you can see the registration details in chrome.manifest (firefox, etc.) or in installed-chrome.txt and chrome.rdf (seamonkey). when the xul file, allcustom.xul is loaded, the doctype declaration near the top loads a dtd from chrome://allcustom/locale/. the application's chrome registry converts this url to the correct dtd file for the locale you are using. the xul toolbarbutton tag contains an entity &allcustom.alert.1;. the dtd resolves this into a text string in the appropriate language. when you press the button, the code in the xul element sends the text ...
...details for classic in chrome.manifest. for example, if you are using modern, it loads: skin/modern/allcustom/seamonkey/allcustom.css from inside the jar. when you restart after installing the extension, the skins classic and modern are both registered for the component allcustom. you can see the registration details in installed-chrome.txt and chrome.rdf. when the xul file, allcustom.xul is loaded, the stylesheet declaration near the top loads a stylesheet from chrome://allcustom/skin/. the application's chrome registry converts this to the correct css file for the theme you are using. the xul toolbarbutton tag has an id all-custom-1. the css stylesheet uses the corresponding selector #all-custom-1 to provide the appropriate image: button-1.png file structure in the new file structure, ...
Content Panels - Archive of obsolete content
sometimes, you will want to change part of the window. a good example is a step-by-step wizard that guides you through a number of screens, asking a set of questions. each time the user clicks the next button, the next screen of the wizard is displayed. you could create a wizard interface by opening a different window for each screen. ...
...pts when running in different windows. note that xul does have a wizard element which may be used to create wizard interfaces. this will be described in a later section. another approach is to use the iframe element, which works much like the html element of the same name. it creates a separate document within the window. it has the advantage that it can be placed anywhere and the contents can be loaded from a different file. set the url to appear in the frame with the src attribute. this url may point to any kind of file, although it will usually point to an html file or another xul file. you can use a script to change the contents of the iframe without affecting the main window. in the mozilla browser window, the area where the web page is displayed is created by using an iframe. when the user...
...rowser, you cannot set the url directly like this, as it doesn't display just one url. instead, you must use a script and call the loaduri function. there are three classes of browser, depending on the kind of content that you want to display inside. the type may be specified using the type attribute. the first type is the default and is used if you don't specify a type. in this case, the content loaded inside the browser is treated as if it was part of the same application and has access to the outer window. that means that when a script loaded inside the browser tries to get the topmost window, it will get the outer xul window. this would be suitable for a child xul panel that is part of your application, but this isn't what you want for a browser that loads a web page. instead, you would want...
Using the Editor from XUL - Archive of obsolete content
warning: the content of this article may be out of date. overview the editor in xul lives on top of a xul <iframe> element; it observes document loading in this <iframe>, and, when document loading is complete, it instantiates an editor on the loaded document. 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. you can 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 edit...
...s 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 from css. editoronload() is called. it does some getting of window.arguments (which is a way callers can pass parameters to new windows -- we use this to get the url to be loaded), then it calls editorstartup(), where the real work happens. it passes two parameters; the first indicates whether we want a plain text or html editor (pass text or html here), and the second is the <iframe> element on which we wish to create the editor. we could either pass document.getelementbyid("content-frame") or window._content here. the important stuff in editorstartup() begins w...
...ple with frameset documents, or html documents with their own embedded <iframe>s. in this case, we need to be careful to instantiate the editor on the correct document. we are currently only able to have one editor per composer window; in future, relaxing this restriction would allow us to edit all the subdocuments in a frameset at the same time. we detect that the document we want to edit has loaded successfully in nseditorshell::onenddocumentload(). after checking that we can actually edit this document, we go ahead and instantiate an editor on it (in nseditorshell::preparedocumentforediting()). as well as making the editor (which happens via nseditorshell::doeditormode()) we also hook up various listeners and observers for ui updating and user interaction, and store a file specifier for...
editor - Archive of obsolete content
ust enable editing using the makeeditable method. to specify the document to load in the editor use the src attribute. however, an issue is that if you specify the src attribute initially on the editor tag in the xul file, the document does not become editable by default. to enable editing on an editor, do either of the following: set the src attribute on the editor after the outer window has loaded, for example, in the onload handler. you might also set the src attribute based on what the user selects from a file dialog. in this case, set the editortype attribute on the editor. call the makeeditable method to make the document loaded in the editor editable. enable the design mode of the document loaded in the editor. to edit a new document, set the src attribute to about:blank. to acce...
... see the rich text editing and midas pages for more information about gecko's built-in rich text editor. ...
...more information about gecko's built-in rich text editor. ...
iframe - Archive of obsolete content
mentbyid('myframe').setattribute('src', url); } </script> attributes showcaret type: boolean whether or not to cause a typing caret to be visible in the content area. default is false. src type: uri the uri of the content to appear in the element. type type: one of the values below. the type of browser, which can be used to set access of the document loaded inside the browser. if this is not set, the loaded document has the same access as the window containing the browser. more precisely: the document loaded into a chrome window is always of chrome type. subdocuments of chrome documents are of chrome type, unless the container element (one of iframe, browser or editor) has one of the special type attribute values (the common ones are content, conten...
...wser is added to a chrome document), and preventing documents from inheriting the principal of the parent document. the type attribute on all frames in content documents is ignored; subdocuments of content documents are always content documents. warning: the type attribute must be set before the element is inserted into the document. content a browser for content. the content that is loaded inside the browser is not allowed to access the chrome above it. content-primary the primary browser for content. the content that is loaded inside the browser is not allowed to access the chrome above it. for instance, in a web browser, this would be the element that displays the web page. the window for the primary content can be retrieved more conveniently using window.content. content-t...
...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. ...
2006-11-17 - Archive of obsolete content
seamonkey 1.0.6 in french seamonkey 1.0.6 in french (fr-fr) is released. discussions how to translate mozilla to a language called quiché how to translate mozilla to a language called quiché. ...
... seamonkey 1.0.6 in french seamonkey 1.0.6 in french (fr-fr) is released. discussions how to translate mozilla to a language called quiché how to translate mozilla to a language called quiché. ...
... seamonkey 1.0.6 in french seamonkey 1.0.6 in french (fr-fr) is released. discussions how to translate mozilla to a language called quiché how to translate mozilla to a language called quiché. ...
NPN_GetURL - Archive of obsolete content
_blank or _new: load the link in a new blank unnamed window. safest target, even though, when used with a mailto or news url, this creates an extra blank the browser instance. _self or _current: load the link into the same window the plug-in instance occupies. not recommended; if target refers to the window or frame containing the instance, the instance is destroyed and the plug-in may be unloaded. use with npn_geturl() only if you want to terminate the plug-in. _parent: load the link into the immediate <frameset> parent of the plug-in instance's document. if the plug-in instance's document has no parent, the default is _self. _top: load the link into the plug-in instance window. the default is _self, if the plug-in instance's document is already at the top. use for breaking out of a...
...use for breaking out of a deep frame nesting. if the target is null, the browser creates a new stream and delivers the data to the current instance regardless of the mime type of the url. in general, if a url works in the location box of the browser, it works here, except for the _self target. returns if successful, the function returns nperr_no_error. if unsuccessful, the plug-in is not loaded and the function returns an error code. for possible values, see error codes. description npn_geturl() is used to load a url into the current window or another target or stream. plug-ins can use this capability to provide hyperlinks to other documents or to retrieve data from anywhere on the network. this is especially useful for enabling an existing application to operate on the web. for http u...
...ank line). make sure that the target matches the url type sent to it. for example, a null target does not make sense for some url types (such as mailto). the following recommendations about target choice apply to other methods that handle urls as well. if the target parameter refers to the window or frame containing the current plug-in instance, the instance is destroyed and the plug-in may be unloaded. if target is null, the application creates a new stream and delivers the data to the plug-in instance, through calls to npp_newstream(), npp_writeready() and npp_write(), and npp_destroystream(). this means that if you want the plug-in to handle a new stream, no matter what the mime type is, use null. if the application cannot locate the url and retrieve the data, it does not create a stream for...
Audio for Web games - Game development
we can do this with javascript's async/await functionality. once they are available to play, we need to make sure they start at the correct point that other tracks might be playing at, so they sync up. let's create our audio context: // for cross browser compatibility const audiocontext = window.audiocontext || window.webkitaudiocontext...
... audio context: // for cross browser compatibility const audiocontext = window.audiocontext || window.webkitaudiocontext; const audioctx = new audiocontext(); now let's select all the <li> elements; later we can harness these elements to give us access to the track file path and each individual play button. ...
...t audiobuffer = await audioctx.decodeaudiodata(arraybuffer); return audiobuffer; } we can then use the await operator when calling this function, which ensures that we can run subsequent code when it has finished executing. let's create another async function to set up the sample — we can combine the two async functions in a nice promise pattern to perform further actions when each file is loaded and buffered: async function loadfile(filepath) { const track = await getfile(filepath); return track; } let's also create a playtrack() function, which we can call once a file has been fetched. we need an offset here, so if we have started one file playing, we have a record of how far through to start another file. start() takes two optional parameters. the first is when to commence play...
How to build custom form controls - Learn web development
e user uses. the script is in conflict with, or is affected by, a browser extension (such as firefox's noscript extension or chrome's notscripts extension). the user is using a legacy browser, and one of the features you require is not supported: this will happen frequently when you make use of cutting-edge apis. the user is interacting with the content before the javascript has been fully downloaded, parsed, and executed. because of these risks, it's really important to seriously consider what will happen if your javascript doesn't work. we'll discuss options to consider and cover the basics in our example (a full discussion of solving this issue for all scenarios would require a book). just remember, it is vital make your script generic and reusable. in our example, if our javascript cod...
...; // we remove the highlight from all options optionlist.foreach(function (other) { other.classlist.remove('highlight'); }); // we highlight the right option option.classlist.add('highlight'); }; you need these in order to handle the various states of the custom control. next, we bind these functions to the appropriate events: // we handle the event binding when the document is loaded. window.addeventlistener('load', function () { var selectlist = document.queryselectorall('.select'); // each custom control needs to be initialized selectlist.foreach(function (select) { // as well as all its `option` elements var optionlist = select.queryselectorall('.option'); // each time a user hovers their mouse over an option, we highlight the given option optionli...
...rol function getindex(select) { // we need to access the native control for the given custom control // in our example, that native control is a sibling of the custom control var nativewidget = select.previouselementsibling; return nativewidget.selectedindex; }; with these two functions, we can bind the native controls to the custom ones: // we handle event binding when the document is loaded. window.addeventlistener('load', function () { var selectlist = document.queryselectorall('.select'); // each custom control needs to be initialized selectlist.foreach(function (select) { var optionlist = select.queryselectorall('.option'), selectedindex = getindex(select); // we make our custom control focusable select.tabindex = 0; // we make the native control ...
Sending forms through JavaScript - Learn web development
( data[name] ) ); } // combine the pairs into a single string and replace all %-encoded spaces to // the '+' character; matches the behaviour of browser form submissions. ...
...const btn = document.queryselector('button'); function senddata( data ) { const xhr = new xmlhttprequest(), fd = new formdata(); // push our data into our formdata object for( name in data ) { fd.append( name, data[ name ] ); } // define what happens on successful data submission xhr.addeventlistener( 'load', function( event ) { alert( 'yeah! data sent and response loaded.' ); } ); // define what happens in case of error xhr.addeventlistener(' error', function( event ) { alert( 'oops! something went wrong.' ); } ); // set up our request xhr.open( 'post', 'https://example.com/cors.php' ); // send our formdata object; http headers are set automatically xhr.send( fd ); } btn.addeventlistener( 'click', function() { senddata( {test:'ok'} ); } ...
...re's a blank line between the metadata and the data data += '\r\n'; // append the text data to our body's request data += text.value + "\r\n"; // once we are done, "close" the body's request data += "--" + boundary + "--"; // define what happens on successful data submission xhr.addeventlistener( 'load', function( event ) { alert( 'yeah! data sent and response loaded.' ); } ); // define what happens in case of error xhr.addeventlistener( 'error', function( event ) { alert( 'oops! something went wrong.' ); } ); // set up our request xhr.open( 'post', 'https://example.com/cors.php' ); // add the required http header to handle a multipart form data post request xhr.setrequestheader( 'content-type','multipart/form-data; bo...
Creating hyperlinks - Learn web development
part of the same document: <p>the <a href="#mailing_address">company mailing address</a> can be found at the bottom of this page.</p> absolute versus relative urls two terms you'll come across on the web are absolute url and relative url: absolute url: points to a location defined by its absolute location on the web, including protocol and domain name. ...
...and finds the file that's being requested. with a relative url, the browser just looks up the file that's being requested on the same server. if you use absolute urls where relative urls would do, you're constantly making your browser do extra work, meaning that it will perform less efficiently. linking to non-html resources — leave clear signposts when linking to a resource that will be downloaded (like a pdf or word document), streamed (like video or audio), or has another potentially unexpected effect (opens a popup window, or loads a flash movie), you should add clear wording to reduce any confusion. for example: if you're on a low bandwidth connection, click a link, and then a multiple megabyte download starts unexpectedly. if you don't have the flash player installed, click a lin...
...here's an example with a download link to the latest windows version of firefox: <a href="https://download.mozilla.org/?product=firefox-latest-ssl&os=win64&lang=en-us" download="firefox-latest-64bit-installer.exe"> download latest firefox for windows (64-bit) (english, us) </a> active ...
Graceful asynchronous programming with Promises - Learn web development
ilar to when you add an event listener to an object using addeventlistener(). it doesn't run until an event occurs (when the promise fulfills). the most notable difference is that a .then() will only run once for each time it is used, whereas an event listener could be invoked multiple times. we immediately run the blob() method on this response to ensure that the response body is fully downloaded, and when it is available transform it into a blob object that we can do something with. the result of this is returned like so: response => response.blob() which is shorthand for function(response) { return response.blob(); } unfortunately, we need to do slightly more than this. fetch promises do not fail on 404 or 500 errors — only on something catasrophic like a network failure...
...; let b = fetch(url2); let c = fetch(url3); promise.all([a, b, c]).then(values => { ... }); when the promise is fulfilled, the values passed into the fulfilment handler would contain three response objects, one for each of the fetch() operations that have completed. however, we don't want to do this. our code doesn't care when the fetch() operations are done. instead, what we want is the loaded data. that means we want to run the promise.all() block when we get back usable blobs representing the images, and a usable text string. we can write a function that does this; add the following inside your <script> element: function fetchanddecode(url, type) { return fetch(url).then(response => { if(!response.ok) { throw new error(`http error! status: ${response.status}`); } e...
... note: if you get stuck, you can compare your version of the code to ours, to see what it is meant to look like — see it live, and see the source code. note: if you were improving this code, you might want to loop through a list of ite...
Fetching data from the server - Learn web development
, 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 extremely wasteful and results in a poor user experience, especially as pages get larger and more complex. enter ajax this led to the creation of technologies t...
..., and load it. now search for something, like a new product. the main content will change, but most of the surrounding information, like the header, footer, navigation menu, etc., will stay the same. this is a really good thing because: page updates are a lot quicker and you don't have to wait for the page to refresh, meaning that the site feels faster and more responsive. less data is downloaded on each update, meaning less wasted bandwidth. 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...
...sktop 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 application, we'd be more likely to use a s...
Perceived performance - Learn web development
icks to follow. some of these quick tips have full articles if you want to dive deeper. displaying content, or at least some part of the page with an indication that content is loading, as quickly as possible, is essential to improving perceived performance. for example, because page render is blocked by loading and parsing css and javascript, minimizing the amount of css and js that needs to be loaded on initially will have a major impact on improving perceived performance. even though the bytes might be the same, not blocking the page from rendering makes the load feel faster. here are a few tips and tricks to help improve performance: minimize initial load to improve perceived performance, minimize the original page load. in other words, first download everything you're going to actually ...
...t, you may need to add some code -- but because the download of non-immediately necessary assets are delayed in a manner that is not perceptible the the user, the user will feel like the download was faster. to minimize the assets required for initial load, separate interactive functionality from content so that required content -- the text, styles, and images visible at initial load -- can be loaded first. delay, or lazy load, the rest of the assets. don't load images or scripts that aren’t used or visible on the initial page load. either delay their load, loading them when the page becomes usable, or, loading them when they become necessary. loading additional assets and resources after initial page load improves perceived performance. loading essential data in initial requests and progr...
...an reduce another 200ms of the perceived load. you're not saving 400ms of time, but the user doesn't feel like they're waiting for content until, well, until they're waiting for content. conclusion by turning as much of the download, render and wait time into active phases and reducing any passive waiting, even if the objective measurements stay the same, the user will feel like the content downloaded, rendered, and responded more quickly. now that we know what we should be speeding up, let's take a look at some metrics and learn how we can measure these events. previous overview: performance next in this module the "why" of web performance what is web performance? how do users perceive performance? measuring performance multimedia: images multimedia: video javascript perfor...
JavaScript performance - Learn web development
previous overview: performance next while images and video account for over 70% of the bytes downloaded for the average website, byte per byte, javascript has a greater negative impact on performance. this article looks to introduce performance issues caused by scripts and introduces tips and tricks for optimizing javascript for web performance. prerequisites: basic computer literacy, basic software installed, and basic knowledge of client-side web technologies. objective: to learn about the effects of javascript on performance optimization, and how a javascript file size is not the only impact on web performance. ...
...puter literacy, basic software installed, and basic knowledge of client-side web technologies. objective: to learn about the effects of javascript on performance optimization, and how a javascript file size is not the only impact on web performance. similar to images and video, the best way to improve performance is to omit what is not, in fact, necessary. but not all bytes downloaded have the same impact. javascript bytes have to be downloaded, parsed, and exectuted. javascript impacts download performance. we'll cover tips and tricks to minimize that impact on download. but javascript can also consume the main thread, the cpu, and the battery. it can make the ui feel unresponsive or janky. we'll introduce concepts for handling that as well. download impact web applications...
...ky. we'll introduce concepts for handling that as well. download impact web applications include a lot of javascript. many applications are built with a javascrpit framework, or multiple, with several additional dependencies. often times third party scripts and apis are added, including a/b testing, tracking pixels, and features like maps and support features. all of this javascript must be downloaded. eventually. performance optimizatins should include: reducing the amount of javascript that is needed. some features requiring complex javascript can be done with a few lines of javascript. requiring a library for other features may improve developer experience, but is all that javascript required? is there a lighter weight or home spun solutions? some features may not be necessary, and tho...
Setting up your own test automation environment - Learn web development
ntation seems fairly up-to-date and it is well-maintained. if you want different options, webdriver.io and nightwatch.js are also good choices. to install selenium-webdriver, run the following command, making sure you are inside your project folder: npm install selenium-webdriver note: it is still a good idea to follow these steps even if you previously installed selenium-webdriver and downloaded the browser drivers. you should make sure that everything is up-to-date. next, you need to download the relevant drivers to allow webdriver to control the browsers you want to test. you can find details of where to get them from on the selenium-webdriver page (see the table in the first section.) obviously, some of the browsers are os-specific, but we're going to stick with firefox and chrome, ...
...webdriver will then wait for 2 seconds; the document title is then accessed, and if it is "webdriver - google search", we will return a message to claim the test is passed. webdriver will then close down the firefox instance and stop. testing in multiple browsers at once there is also nothing to st...
...ou should see your new job now has the updated data attached to it: your own remote server if you don't want to use a service like sauce labs or browserstack, you can always set up your own remote testing server. let's look at how to do this. the selenium remote server requires java to run. download the latest jdk for your platform from the java se downloads page. install it when it is downloaded. next, download the latest selenium standalone server — this acts as a proxy between your script and the browser drivers. choose the latest stable version number (i.e. not a beta), and from the list choose a file starting with "selenium-server-standalone". when this has downloaded, put it in a sensible place, like in your home directory. if you've not already added the location to your path, d...
A bird's-eye view of the Mozilla framework
e examples of packages. content (dom) the mozilla document object model (dom) specifies a logical tree structure for storing ui and document content, and provides an api (application programming interface) for accessing and manipulating the content. an application such as the browser may have one or more open documents accessible via dom apis. when an html, xml, svg or other type of document is loaded, the nglayout engine (also known as gecko) parses the contents into a dom tree, and handles the layout and rendering of the document pages. the nglayout engine also parses xul ui controls into a dom tree and handles rendering of the ui. core services modules such as the nglayout engine comprise the core application services available to other core modules, and xul packages core applicatio...
...le, it's helpful to have a basic understanding of the xpcom object model. mozilla architectural modules are comprised of groups of related xpcom objects that provide services to and access services from each other through dynamically queryable interfaces. object model at a glance mozilla dynamically loads and integrates core modules and xul packages into the runtime environment on startup. once loaded, a module or package has full access to the xpcom objects of all the other modules in the runtime environment. the ability to dynamically integrate modules and packages at startup is a powerful benefit of the object model, which defines a module as a set of one or more xpcom objects calledcomponents. these objects provide services to client packages and modules and access services provided by oth...
...entifies and loads all of the different xpcom components comprising the core application services and builds a central registry it uses to generate instances of xpcom components and instances of interface implementation classes on demand. ...
Chrome registration
ge to translate an application without altering the rest of the source code. the two main types of localizable files are dtd files and java-style properties files. skin a skin provider is responsible for providing a complete set of files that describe the visual appearance of the chrome. typically a skin provider will provide css files and images. note: scripts (including those found in xbl) loaded from skin packages will not execute. the chrome registry the gecko runtime maintains a service known as the chrome registry that provides mappings from chrome package names to the physical location of chrome packages on disk. this chrome registry is configurable and persistent, and thus a user can install different chrome providers, and select a preferred skin and locale. this is accomplished...
...ruction should only be applied if the extension is installed into an application using the gecko version identified. multiple platformversion flags may be included on a single line, in which case the line is applied if any of the flags match. contentaccessible chrome resources can no longer be referenced from within <img>, <script>, or other elements contained in, or added to, content that was loaded from an untrusted source. this restriction applies to both elements defined by the untrusted source and to elements added by trusted extensions. if such references need to be explicitly allowed, set the contentaccessible flag to yes to obtain the behavior found in older versions of firefox. see bug 436989. the contentaccessible flag applies only to content packages: it is not recognized for loca...
... (windows/os2), mac (os9/osx), or unix (everything else). anything residing outside of these subdirectories will be ignored. process in electrolysis registrations can be set to only apply in either the main process or any content processes. the "process" flag selects between these two. this can allow you to register different components for the same contract id or ensure a component can only be loaded in the main process. note: extensions can't currently (bug 1131065) register components to load in the content process using the manifest file so this flag is largely useless to extension developers. component {09543782-22b1-4a0b-ba07-9134365776ee} maincomponent.js process=main component {98309951-ac89-4642-afea-7b2b6216bcef} contentcomponent.js process=content xpcnativewrappers chrome pac...
Obsolete Build Caveats and Tips
ing visual studio, go to project properties > c/c++ > language > treat wchar_t as built-in type and set it to "yes". from source_code/mercurial mozilla-2.0 (firefox 4.0) code for the firefox 4.0 (gecko 2.0) release lives in releases/mozilla-2.0. ...
...ake a while # as hundreds of megabytes of history is downloaded to .hg hg clone https://hg.mozilla.org/releases/mozilla-2.0/ 20src cd 20src mozilla-1.9.2 (firefox 3.6) code for the firefox 3.6 (gecko 1.9.2) release lives in releases/mozilla-1.9.2. to get this code, do the following: # pull the mozilla source to the folder 192src/ - may take a while # as hundreds of megabytes of history is downloaded to .hg hg clone https://hg.mozilla.org/releases/mozilla-1.9.2/ 192src cd 192src mozilla-1.9.1 (firefox 3.5) code for the firefox 3.5 (gecko 1.9.1) release lives in releases/mozilla-1.9.1. ...
...by default, a similar-to-release build is done. from windows_sdk_versions visual c++ 9 (vs2008) professional/express download and install the windows 7 sdk. ...
Limitations of chrome scripts
this is one of a pair of articles: the other one lists limitations of frame scripts. compatibility shims for many of the patterns described here we've implemented compatibility shims so the patterns still work. ...
...b content, and if that's your goal, create the sandbox in the content process. there is a shim for sandboxes: if you make a sandbox in the chrome process and give it content principals (by passing a cpow as the first argument to components.utils.sandbox) then we'll actually make it in the content process. ...
...le are loaded in the chrome process. this means that you can't access their content from the content process (via xhr, for example). you can change this default in the code you use to register the about: uri. see about: and chrome: uris. javascript code modules (jsms) in single-process firefox, you can use javascript code modules (jsms) to maintain global state. in multiprocess firefox, a jsm loaded into one process does not share any state with the same jsm loaded into a different process: so you can't use a jsm to share state between the chrome and content processes. if an add-on wants to use a jsm to share state in this way, it's best to load the jsm in the chrome process, and have frame scripts store and access the jsm's state by sending messages to the chrome process using the messa...
Process scripts
process scripts are new in firefox 38. if you're using the addon sdk you can use the remote/parent module's remoterequire instead. when you need to run code in the content process in order to access web content, then you should use frame scripts. however, a problem with frame scripts is that they can be loaded multiple times in the content process, in multiple scopes that are insulated from each other. for example, if you call the global frame message manager's loadframescript() function, then the script will be loaded separately into all open tabs. this can then cause a problem the frame scripts are interacting with a global service in the content process. for example, in multiprocess firefox, if you need to use nsicontentpolicy to register a content policy, you must do this in t...
...ipt() function, then the script will be loaded separately into all open tabs. this can then cause a problem the frame scripts are interacting with a global service in the content process. for example, in multiprocess firefox, if you need to use nsicontentpolicy to register a content policy, you must do this in the content process. but if you register it in a frame script, and the frame script is loaded more than once, you'll register the content policy more than once, which probably isn't what you intend. similarly, some observer notifications must be registered in the content process, but if you do this in a frame script, and the frame script is loaded more than once, then you will get multiple notifications for that event. the solution in these cases is to use a process script instead of a ...
...ed or removed the message-passing apis are the same: sendasyncmessage() is available in both directions, while sendsyncmessage() is available from content to chrome only process scripts are system-privileged, and have access to the components object. however, process scripts are subject to the same kinds of limitations as frame scripts (for example, no file system access). process scripts stay loaded until their host process is closed. the environment for process scripts is similar to that for frame scripts. however, you don't get access to web content or dom events from a process script. retrieving the content frame message manager for a content window when an observer notification in a process script contains a content document or window it can be useful to not use talk through the chil...
Message manager overview
it's a chromemessagebroadcaster object, which implements the following interfaces: nsiframescriptloader nsimessagelistenermanager nsimessagebroadcaster the window message manager can be accessed as ...
...manager is specific to a single xul <browser> element (which essentially corresponds to a single tab): loadframescript() loads the given script only into its <browser> sendasyncmessage() sends the message only to that <browser>. you can mix and match: so for example, you could load a script into every <browser> using the global message manager, but then send a message to the script instance loaded into a specific <browser> using the browser message manager. it's a chromemessagesender object, which implements the following interfaces: nsiprocesschecker nsiframescriptloader nsimessagelistenermanager nsimessagesender the browser message manager can be accessed as a property of the xul <browser> element: // chrome script let browsermm = gbrowser.selectedbrowser.messagemanager; proce...
... the jsm can then use the child process message manager to exchange messages with the parent process message manager. this can be useful for addons to register categories, observers and components in child processes. ...
Using the Browser API
Mozilla › Gecko › Chrome › API › Browser API › Using
, 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 the sections below. the html an <iframe> is turned into a browser iframe by setting the mozbrowser attribute on it: <iframe src="http://mozilla.org" mozbrowser> in addition, the <iframe> can be loaded in its own child process — separate to the page embedding this frame — by including the remote attribute. <iframe src="http://hostname.tld" mozbrowser remote> warning: this last attribute is necessary for security reasons if you plan to load content from an untrusted/unknown origin. if you don't use it, you run the risk of your application being compromised by a malicious web site. it is ...
...t 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 for the mozbrowserlocationchange event. when this fires, we set the value inside the url bar input to be equal to the event object detail property — this is so that t...
...hange the icon back to the reload icon (in this case we are just using a capital "r"). notice that this is also where we call the canmovebwd() and canmovefwd() functions we discussed earlier — it makes sense to update the status of the back and forward buttons after each page reload. in addition, the background of the controls ui bar is changed to the background color of the site that has just loaded, to provide a more integrated experience — this can be read out of the event object's e.detail.backgroundcolor value. when the front page of https://developer.mozilla.org is loaded, for example, the e.detail.backgroundcolor value reported is rgb(0, 83, 159). back to the stop/reload button — updating the icon is nice, but we also need to update the functionality that is invoked when each icon...
Browser API
erface addeventlistener(), removeeventlistener(), and dispatchevent(). htmliframeelement.sendmouseevent() sends a mouseevent to the <iframe>'s content. utility methods last, there are some utility methods, useful for apps that host a browser <iframe>. htmliframeelement.getstructureddata() retrieves any structured microdata (and hcard and hcalendar microformat data) contained in the html loaded in the browser <iframe> and returns it as json. browser api methods removed in firefox 65 in firefox 65, several of the mozilla browser api methods were removed in an effort to cut down on domrequest usage in the browser, and remove the parts of the browser api that are no longer needed (it is used only by the firefox devtools at this point). see bug 1503070 for more details. the methods remo...
...ment.addnextpaintlistener() defines a handler to listen for the next mozafterpaint event in the browser <iframe>. htmliframeelement.clearmatch() clears any content highlighted by findall() or findnext(). htmliframeelement.download() downloads a specified url, storing it at the specified filename/path. htmliframeelement.executescript() allows a specified script to be executed against a page loaded in the browser <iframe>. htmliframeelement.findall() searches for a string in a browser <iframe>'s content; if found, the first instance of the string relative to the caret position will be highlighted. htmliframeelement.findnext() highlights the next or previous instance of a search result after a findall() search has been carried out. htmliframeelement.getcontentdimensions() retrieves the...
... if found, the first instance of the string relative to the caret position will be highlighted. htmliframeelement.findnext() highlights the next or previous instance of a search result after a findall() search has been carried out. htmliframeelement.getcontentdimensions() retrieves the x and y dimensions of the content window. htmliframeelement.getmanifest() retrieves the manifest of an app loaded in the browser <iframe> and returns it as json. htmliframeelement.getscreenshot() takes a screenshot of the browser <iframe>'s content. this is particularly useful to get thumbnails of tabs in a tabbed browser app. htmliframeelement.purgehistory() clears all the resources (cookies, localstorage, cache, etc.) associated with the browser <iframe>. htmliframeelement.sendtouchevent() sends a to...
How Mozilla determines MIME Types
the several ways how this happens are described in this document. content-type "hints" mozilla has a concept of "content-type hints". this means that, for example, if mozilla encounters a <link type="text/css" rel="stylesheet" href="..."> element, a type of text/css will be assumed. this is, however, overridden by the actual mime type the server sends (if any). (for this specific example, the server override only happens in standards-compliant mode. see mozilla's quirks mode or web author faq). ...
...lain text/plain; charset=iso-8859-1 text/plain; charset=iso-8859-1 and the server did not send a content-encoding header, mozilla will sniff the first block of data it gets and check for non-text bytes. text bytes are 9-13, 27, and 31-255. when encountering a non-text byte, the helper app dialog will be shown, showing the mime type corresponding to the extension of the file. also, for images loaded via <img src>, mozilla's image library will do content sniffing (never extension sniffing) to find out the real type of the image. if the server did not send a content-type header, mozilla uses the unknown decoder to find a mime type. file uris for file: uris, mozilla will ask the externalhelperappservice for a mime type. ftp like http uris without a mime type, ftp uris go through the unknow...
...g system is asked for a mime type. (on unix, this means checking mime.types.) if that fails, a user-supplied helper app is searched for by extension, and the specified mime type will be used. (i.e. the list in edit/preferences/helper applications) if that failed, a list of "extra" mime types is searched for an extension match. see line 507 for the complete list. if that also failed, the list of loaded plugins is checked for a plugin that can handle this extension, and is asked for the mime type if no plugin is registered, the ext-to-type-mapping xpcom category is searched for the extension. this allows extensions 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-m...
InstallListener
srestart) 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 maxprogress property for the total data expected. a listener may return false to cancel...
... 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 install the addoninstall representing the install ondownloadfailed() called if there is some...
... void ondownloadfailed( in addoninstall install ) parameters install the addoninstall representing the install oninstallstarted() called when installation of an add-on begins. a listener may return false to cancel the install. ...
NSS PKCS11 Functions
adusermodule(char *modulespec, secmodmodule *parent, prbool recurse); parameters this function has the following parameters: modulespec is a pkcs #11 modulespec. parent is the moduledb that presented this module spec. for applications this value should be null. recurse is a boolean indicates whether or not the module should also launch additional pkcs #11 modules. this is only applicable if the loaded module is actually a moduledb rather than a pkcs #11 module (see pkcs11_module_specs). returns the function returns one of these values: if successful, a pointer to a secmodmodule. caller owns the reference if unsuccessful, null. description secmod_loadusermodule loads a new pkcs #11 module into nss and connects it to the current nss trust infrastructure. once the the module has been successfu...
...ule is actually a moduledb rather than a pkcs #11 module (see pkcs11_module_specs). returns the function returns one of these values: if successful, a pointer to a secmodmodule. caller owns the reference if unsuccessful, null. description secmod_loadusermodule loads a new pkcs #11 module into nss and connects it to the current nss trust infrastructure. once the the module has been successfully loaded, other nss calls will use it in the normal course of searching. modulespec specifies how the module should be loaded. more information about module spec is available at pkcs11_module_specs. nss parameters may be specified in module specs used by secmod_loadusermodule. module will continue to function in the nss infrastructure until unloaded with secmod_unloadusermodule. secmod_unloadusermodule un...
...s may be specified in module specs used by secmod_loadusermodule. module will continue to function in the nss infrastructure until unloaded with secmod_unloadusermodule. secmod_unloadusermodule unload a pkcs #11 module. syntax #include "secmod.h" extern secstatus secmod_unloadusermodule(secmodmodule *module); parameters this function has the following parameters: module is the module to be unloaded. returns the function returns one of these values: if successful, secsuccess. if unsuccessful, secfailure. description secmod_unloadusermodule detaches a module from the nss trust domain and unloads it. the module should have previously been loaded by secmod_loadusermodule. secmod_closeuserdb close an already opened user database. note: the database must be in the internal token, and must be on...
NSS tools : modutil
modulename -libfile library-file [-ciphers cipher-enable-list] [-mechanisms mechanism-list] for example: modutil -dbdir sql:/home/my/sharednssdb -add "example pkcs #11 module" -libfile "/tmp/crypto.so" -mechanisms rsa:dsa:rc2:random using database directory ... module "example pkcs #11 module" added to database. installing a cryptographic module from a jar file pkcs #11 modules can also be loaded using a jar file, which contains all of the required libraries and an installation script that describes how to install the module. the jar install script is described in more detail in [1]the section called “jar installation file format”. the jar installation script defines the setup information for each platform that the module can be installed on. for example: platforms { linux:5.4.
...mand. modutil -list [modulename] -dbdir [sql:]directory listing the modules shows the module name, their status, and other associated security databases for certificates and keys. for example: modutil -list -dbdir sql:/home/my/sharednssdb listing of pkcs #11 modules ----------------------------------------------------------- 1. ...
...for example: modutil -list "nss internal pkcs #11 module" -dbdir sql:/home/my/sharednssdb ----------------------------------------------------------- name: nss internal pkcs #11 module library file: **internal only module** manufacturer: mozilla foundation description: nss internal crypto services pkcs #11 version 2.20 library version: 3.11 cipher enable flags: none default mechanis...
NSS tools : modutil
Mozilla › Projects › NSS › tools › modutil
-libfile library-file [-ciphers cipher-enable-list] [-mechanisms mechanism-list] for example: modutil -dbdir sql:/home/my/sharednssdb -add "example pkcs #11 module" -libfile "/tmp/crypto.so" -mechanisms rsa:dsa:rc2:random using database directory ... module "example pkcs #11 module" added to database. installing a cryptographic module from a jar file pkcs #11 modules can also be loaded using a jar file, which contains all of the required libraries and an installation script that describes how to install the module. the jar install script is described in more detail in [1]the section called “jar installation file format”. the jar installation script defines the setup information for each platform that the module can be installed on. for example: platforms {...
...lename] -dbdir [sql:]directory listing the modules shows the module name, their status, and other associated security databases for certificates and keys. for example: modutil -list -dbdir sql:/home/my/sharednssdb listing of pkcs #11 modules ----------------------------------------------------------- 1. ...
...for example: modutil -list "nss internal pkcs #11 module" -dbdir sql:/home/my/sharednssdb ----------------------------------------------------------- name: nss internal pkcs #11 module library file: **internal only module** manufacturer: mozilla foundation description: nss internal crypto services pkcs #11 version 2.20 library version: 3.11 cipher enable flags: none default mecha...
imgIDecoderObserver
criptable this interface is used both for observing imgidecoder objects and for observing imgirequest objects. it lets you monitor the progress of loading an image. 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. if an image is decoded on load and not visibly discarded, decode notifications are nested logically inside load notifications as one might expect. however, with decode-on-draw, the set of decode notifications can come completely after the load notifications, and can come multiple times if the image is discarda...
... if the image is discardable. moreover, they can be interleaved in various ways. in general, any presumed ordering between load and decode notifications should not be relied upon. decode notifications may or may not be synchronous, depending on the situation. if imgidecoder::flag_sync_decode is passed to a function that triggers a decode, all notifications that can be generated from the currently loaded data fire before the call returns. if flag_sync_decode is not passed, all, some, or none of the notifications may fire before the call returns. method overview void ondataavailable(in imgirequest arequest, in boolean acurrentframe, [const] in nsintrect arect); native code only! void ondiscard(in imgirequest arequest); void onimageisanimated(in imgirequest arequest); ...
...gidecoder object. onimageisanimated() notification for when an image is known to be animated. this should be fired at the earliest possible time. void onimageisanimated( in imgirequest arequest ); parameters arequest the request on which data is available, or null if being called for an imgidecoder object. onstartcontainer() this load notification is called once enough data has been loaded from the network that we were able to parse the width and height from the image. by the time this callback is been called, the size has been set on the container and status_size_available has been set on the associated imgrequest. void onstartcontainer( in imgirequest arequest, in imgicontainer acontainer ); parameters arequest the request on which data is available, or null if bein...
imgIRequest
read only. imagestatus unsigned long status flags of the status_* variety. read only. mimetype string read only. uri nsiuri the uri the image load was started with. note that t...
...read only. imagestatus unsigned long status flags of the status_* variety. read only. mimetype string read only. uri nsiuri the uri the image load was started with. ...
...artial 0x2 used internally by imgrequest to flag that a request is being cancelled as a result of a failure of a proxy holder and not an internal failure. at least i think that's what it does. regardless, there's no reason for this flag to be public, and it should either go away or become a private state flag within imgrequest. do not rely on it. status_load_complete 0x4 the data has been fully loaded to memory, but not necessarily fully decoded. status_error 0x8 an error occurred loading the image. status_frame_complete 0x10 the first frame has been completely decoded. status_decode_complete 0x20 the whole 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. i...
nsIApplicationUpdateService
nd 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 ); 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 downloa...
...arts 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" 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. pausedownload() pauses the currently active update download. void pausedownload(); parameters none. removedownloadlistener() removes a listener ...
...void removedownloadlistener( in nsirequestobserver listener ); parameters listener the listener object to remove. selectupdate() selects the best update to install from a provided list of available updates. ...
nsIDOMChromeWindow
ow.idlscriptable this interface is implemented on the window object in chrome. inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview void beginwindowmove(in nsidomevent mousedownevent); void getattention(); void getattentionwithcyclecount(in long acyclecount); void maximize(); void minimize(); void notifydefaultbuttonloaded(in nsidomelement defaultbutton); void restore(); void setcursor(in domstring cursor); attributes attribute type description browserdomwindow nsibrowserdomwindow the related nsibrowserdomwindow instance which provides access to yet another layer of utility functions by chrome script. it will be null for domwindows not corresponding to browsers. messagemanager nsichromeframemessagem...
...long acyclecount ); parameters acyclecount the maximum number of times to animate the window per system conventions. if set to -1, cycles indefinitely until window is brought into the foreground. this behavior is same as getattention method. maximize() maximizes the window. void maximize(); parameters none. minimize() minimizes the window. void minimize(); parameters none. notifydefaultbuttonloaded() when a document has been loaded, the document can notify the default button of the document to the window by using this method. when this method is called on windows, gecko moves the mouse cursor to center of the button if the auto cursor snap setting is enabled on the system. however, when the window isn't active at that time, the cursor isn't moved. on other systems, this method doesn't have ...
...stems, this method doesn't have any reaction currently. this method is called automatically on dialog element or wizard element of xul. if some xul applications create a dialog like window which has a default button but it's not created by the dialog/wizard element, the applications should call this method for the accessibility and the usability on windows at onload event. void notifydefaultbuttonloaded( in nsidomelement defaultbutton ); parameters defaultbutton the default button element of the window. restore() restores the size and position of the window. void restore(); parameters none. setcursor() sets the mouse cursor to the specified cursor. the mouse cursor is locked to the specified cursor if it's not "auto". at that time, the cursor has been never changed by cursor moving. after ...
nsIDOMOfflineResourceList
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 application caches aren't supported yet. oncached nsidomeventlistener an event list...
...ants 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 ); parameters uri the uri of the...
...he list of dynamically managed entries. if this was the last reference to the given uri in the application cache, the cache entry is removed. void mozremove( in domstring uri ); parameters uri the uri of the item to remove from the list. swapcache() swaps in the newest version of the application cache. the newest version of resources are updated on first refresh. this means already loaded resources should only update after a page refresh. note: versioned application caches are not yet supported; this method will throw an exception. void swapcache(); parameters none. update() begins the application cache update process. this will check for a new cache manifest but will not tell the browser to use the updated cache. void update(); parameters none. see also offline r...
nsIDOMProgressEvent
dia 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. method overview void initprogressevent(in domstring typearg, in boolean canbubblearg, in boolean cancelablearg, in boolean lengthcomputablearg, in unsigned long long loadedarg, in unsigned long long totalarg); deprecated since gecko 22.0 attributes attribute type description lengthcomputable boolean specifies whether or not the total size of the transfer is known. read only. loaded unsigned long long the number of bytes transferred since the beginning of the operation. this doesn't include headers and other overhe...
... since gecko 22.0 this method has been removed from use in javascript in gecko 22.0. use the regular constructor to construct a synthetic progressevent. it still is usable from native c++ code. initializes the progress event object. void initprogressevent( in domstring typearg, in boolean canbubblearg, in boolean cancelablearg, in boolean lengthcomputablearg, in unsigned long long loadedarg, in unsigned long long totalarg ); parameters typearg the type of event. must be one of "abort", "error", "load", "loadstart", or "progress". canbubblearg specifies whether or not the created event will bubble. cancelablearg specifies whether or not the created event can be canceled. lengthcomputablearg if the size of the data to be transferred is known, this should be true. othe...
... long totalarg ); parameters typearg the type of event. must be one of "abort", "error", "load", "loadstart", or "progress". canbubblearg specifies whether or not the created event will bubble. cancelablearg specifies whether or not the created event can be canceled. lengthcomputablearg if the size of the data to be transferred is known, this should be true. otherwise, specify false. loadedarg the number of bytes already transferred. must be a non-negative value. totalarg the total number of bytes to be transferred. if lengthcomputable is false, this must be zero. see also using xmlhttprequest xmlhttprequest nsixmlhttprequesteventtarget nsixmlhttprequest ...
nsIDownload
this interface is deprecated as of firefox 26. please use downloads.jsm instead. toolkit/components/downloads/public/nsidownload.idlscriptable this interface describes a download object. download objects are used by the download manager (see nsidownloadmanager to manage files that are queued to download, being downloaded, and finished being downloaded.) inherits from: nsitransfer last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) note: once the download is completed, the download manager stops updating the nsidownload object. completed states are nsidownloadmanager::download_finished, nsidownloadmanager::download_failed, and nsidownloadmanager::download_canceled. attributes attribute type description amounttransferred long long ...
....5 / thunderbird 3.0 / seamonkey 2.0) note: once the download is completed, the download manager stops updating the nsidownload object. completed states are nsidownloadmanager::download_finished, nsidownloadmanager::download_failed, and nsidownloadmanager::download_canceled. attributes attribute type description amounttransferred long long the number of bytes downloaded so far. read only. cancelable nsicancelable an object that can be used to cancel the download. once the download is complete, this value is set to null. read only. displayname astring a user-readable description of the transfer. read only. id unsigned long the id by which the download is identified uniquely in the database - not globally unique. for...
... downloads transfer speed in bytes per second. read only. starttime long long the time at which the transfer was started. read only. state short the downloads current state. see nsidownloadmanager.constants. read only. target nsiuri the target of the transfer. read only. targetfile nsilocalfile indicates the location at which the downloaded file will be (or is, if the download is complete) stored. read only. see also nsidownloadmanager nsidownloadprogresslistener nsixpinstallmanagerui ...
nsIMicrosummaryService
rator getgenerator( in nsiuri generatoruri ); parameters generatoruri the uri of the generator. return value returns an nsimicrosummarygenerator for the given uri. getmicrosummaries() get the set of microsummaries available for a given page. ...
...nsimicrosummaryset getmicrosummaries( in nsiuri pageuri, in long long bookmarkid optional ); parameters pageuri the uri of the page for which to retrieve available microsummaries. ...
... passes a bookmark id, and one of the microsummaries is the current one for the bookmark, this method will retrieve content from the datastore for that microsummary, which is useful when callers want to display a list of microsummaries for a page that isn't loaded, and they want to display the actual content of the selected microsummary immediately (rather than after the content is asynchronously loaded). nsimicrosummaryset getmicrosummaries( in nsiuri pageuri, in long long bookmarkid optional ); parameters pageuri the uri of the page for which to retrieve available microsummaries. bookmarkid optional the id of the bookmark for which this method is being called. return value returns an nsimicrosummaryset of nsimicrosummaries for the given page. getmicrosummary() get the cu...
nsIMsgDBView
esignating the sort type used for the folder. defined in the interface: nsmsgviewsorttype. sortorder an nsmsgviewsortordervalue designating the sort order used for the folder. defined in the interface: nsmsgviewsortorder. viewflags other flags to be used. defined in the interface: nsmsgviewflagstype. return values acount upon return, the count variable may contain the number of messages loaded. close() close the current list of messages. void close(); init() initializes the database view for use. void init(in nsimessenger amessengerinstance, in nsimsgwindow amsgwindow, in nsimsgdbviewcommandupdater acommandupdater); parameters amessengerinstance amsgwindow acommandupdater sort() sorts the currently loaded messages. void sort(in nsmsgviewsortt...
...rt(in nsmsgviewsorttypevalue sorttype, in nsmsgviewsortordervalue sortorder); parameters sorttype a nsmsgviewsorttypevalue designating the sort type used. defined in the interface: nsmsgviewsorttype. sortorder an nsmsgviewsortordervalue designating the sort order used for the folder. defined in the interface: nsmsgviewsortorder. docommand() perform a command on the currently loaded messages. void docommand(in nsmsgviewcommandtypevalue command); parameters command the nsmsgviewcommandtypevalue to perform. defined in the interface: nsmsgviewcommandtype. docommandwithfolder() perform a command that requires a folder. typical examples are move or copy commands. void docommandwithfolder(in nsmsgviewcommandtypevalue command, in nsimsgfolder ...
...gned long in mailnewstypes2.idl. loadmessagebyurl() loads a message into the message pane. void loadmessagebyurl(in string aurl); parameters aurl the url of the message reloadmessage() reload the currently shown message. void reloadmessage(); reloadmessagewithallparts() reload the currently shown message with fetchcompletemessage set to true. this forces everything to be re-downloaded. void reloadmessagewithallparts(); selectmsgbykey() selects a message based on its key. used by "go to folder" feature and "remember last selected message" feature. if key is not found, nothing is selected. void selectmsgbykey(in nsmsgkey key); parameters key the key of the message to load. nsmsgkey is defined as an unsigned long in mailnewstypes2.idl. selectfoldermsgbykey() selec...
nsINavHistoryService
his transition type means the user followed a link and got a new toplevel window. transition_typed 2 this transition type is set when the user typed the url to get to the page. transition_bookmark 3 this transition type is set when the user followed a bookmark to get to the page. transition_embed 4 this transition type is set when some inner content is loaded. this is true of all images on a page, and the contents of the iframe. it is also true of any content in a frame, regardless if whether or not the user clicked something to get there. transition_redirect_permanent 5 this transition type is set when the transition was a permanent redirect. transition_redirect_temporary 6 this transition type is set when the transition...
... this transition type is set when the transition was a permanent redirect. transition_redirect_temporary 6 this transition type is set when the transition was a temporary redirect. transition_download 7 this transition type is set when the transition is a download. transition_framed_link 8 this transition type is set when the user followed a link that loaded a page in a frame. methods getpagetitle() this method retrieves the original title of the page. astring getpagetitle( in nsiuri auri ); parameters auri the page whose title needs to be retrieved. return value returns the original title of the page. markpageasfollowedbookmark() this method is just like markpageastyped (in nsibrowserhistory, also implemented by the history se...
...e( in nsiuri auri ); parameters auri the page whose title needs to be retrieved. return value returns the original title of the page. markpageasfollowedbookmark() this method is just like markpageastyped (in nsibrowserhistory, also implemented by the history service), but for bookmarks. it declares that the given uri is being opened as a result of following a bookmark. if this uri is loaded soon after this message has been received, that transition will be marked as following a bookmark. void markpageasfollowedbookmark( in nsiuri auri ); parameters 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 ur...
nsIProtocolHandler
anding relative uris; this includes http and ftp, for example. uri_norelative 1<<0 the protocol doesn't support relative uris (for example, about and javascript). uri_noauth 1<<1 the protocol doesn't have an authority component (for example, file). uri_inherits_security_context 1<<4 uris for this protocol have no inherent security context, so documents loaded using this protocol should inherit the security context of the document that loads them. uri_forbids_automatic_document_replacement 1<<5 "automatic" loads that would replace the document (such as a meta refresh, certain types of xlinks, and other non-user-triggered loads) are not allowed if the originating uri has this protocol flag. keep in mind that the decision of what constitu...
...y untrusted content in a viewing area that the user expects to have a lot of control over, such as an email reader. uri_loadable_by_anyone 1<<6 anyone can load the uris for this protocol; for example, any web site can load a uri for this protocol. web-safe protocols such as http should use this flag. uri_dangerous_to_load 1<<7 uris using this protocol are unsafe if loaded by untrusted web content and may only be loaded by privileged code (for example, code that has the system principal). various internal protocols use this flag. uri_is_ui_resource 1<<8 the uris for this protocol refer to resources that are part of the application's user interface. there are cases in which such resources may be made accessible to untrusted content such as web pages,...
...y_anyone. uri_is_local_file 1<<9 uris for this protocol from other origins should only be allowed if those origins should have access to the local file system. it's up 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 li...
nsISHistoryListener
docshell/shistory/public/nsishistorylistener.idlscriptable an interface you can implement to receive notifications about activities that occur in session history, and optionally cancel them. inherits from: nsisupports last changed in gecko 1.7 a session history listener is notified when pages are added to, removed from, and loaded from session history. the listener can prevent any action (except adding a new session history entry) from happening by returning false from the corresponding callback method. a session history listener can be registered on a particular nsishistory instance via the nsishistory.addshistorylistener() method. method overview boolean onhistorygoback(in nsiuri abackuri); boolean onhistorygoforward(in nsiuri aforwarduri); boolean onhistorygotoindex(in ...
...n history entry being navigated to. return value true to allow the go forward operation to proceed or false to cancel it. onhistorygotoindex() called when navigating to a session history entry by index, for example, when nsiwebnavigation.gotoindex() is called. boolean onhistorygotoindex( in long aindex, in nsiuri agotouri ); parameters aindex the index in session history of the entry to be loaded. agotouri the uri of the session history entry to be loaded. return value true to allow the operation to proceed or false to cancel it. onhistorynewentry() called when a new document is added to session history. new documents are added to session history by the docshell when new pages are loaded in a frame or content area; for example by calling nsiwebnavigation.loaduri(). note: you can't cancel...
...rom 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 document is reloaded, for example due to an nsiwebnavigation.reload() call. boolean onhistoryreload( in nsiuri areloaduri, in unsigned long areloadflags ); parameters areloaduri the uri of the document to be reloaded. areloadflags flags that indicate how the document is to be refreshed. see the nsiwebnavigation interface's load constants. return value true to allow the reload operation to proceed or false to c...
nsIStyleSheetService
iuri sheeturi, in unsigned long type); constants constant value description agent_sheet 0 user_sheet 1 author_sheet 2 methods loadandregistersheet() synchronously loads a style sheet from sheeturi and adds it to the list of user or agent style sheets. a user sheet loaded via this api will come before usercontent.css and userchrome.css in the cascade (so the rules in it will have lower precedence than rules in those sheets). an agent sheet loaded via this api will come after ua.css in the cascade (so the rules in it will have higher precedence than rules in ua.css). the relative ordering of two user or two agent sheets loaded via this api is undefined. sheets adde...
...void loadandregistersheet( in nsiuri sheeturi, in unsigned long type ); parameters sheeturi uri of the stylesheet to load and register. type one of the type constants. ...
... parameters sheeturi uri of the stylesheet to check. type one of the type constants. return value returns true if a style sheet at sheeturi has previously been added to the list of style sheets specified by type. unregistersheet() remove the style sheet at sheeturi from the list of style sheets specified by type. the removal takes effect immediately, even for already-loaded documents. void unregistersheet( in nsiuri sheeturi, in unsigned long type ); parameters sheeturi uri of the stylesheet to unregister. type one of the type constants. see also see using the stylesheet service for examples. ...
nsIUpdatePatch
toolkit/mozapps/update/nsiupdateservice.idlscriptable an interface that describes an object representing a patch file that can be downloaded and applied to a version of this application so that it can be updated. 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 nsidomelement serialize(in nsidomdocument updates); attributes attribute type description finalurl astring the final url this patch was being downloaded from. hashfunction astring the hash function to use when determining the integrity of the patch file. hashvalue astring the value of the hash function named in hashfunction that should be computed if the file is not corrupt. selected boole...
...false if another update is selected. size unsigned long the size of the patch file in bytes. state astring the state of this patch. type astring the type of patch represented by the object: "partial" a binary difference between two application versions. ...
...another update is selected. size unsigned long the size of the patch file in bytes. state astring the state of this patch. type astring the type of patch represented by the object: "partial" a binary difference between two application versions. "complete" a complete patch containing all the replacement files to update to the new version. url astring the url from which the patch was downloaded. methods serialize() serializes the patch object into a dom element. nsidomelement serialize( in nsidomdocument updates ); parameters updates the dom document into which to serialize the patch. return value the patch object serialized into an nsidomelement. see also nsiupdate nsiupdatechecklistener nsiupdatechecker nsiapplicationupdateservice nsiupdatemanager nsiupdateprompt nsiupdatetim...
nsIWebBrowserPersist
deleting all created files and directories. this flag does nothing for failed upload operations to remote servers. persist_flags_autodetect_apply_conversion 16384 let the webbrowserpersist decide whether the incoming data is encoded and whether it needs to go through a content converter, for example to decompress it. persist_flags_append_to_file 32768 append the downloaded data to the target file. this can only be used when persisting to a local file. persist_flags_force_allow_cookies 65536 force relevant cookies to be sent with this load even if normally they wouldn't be. persist_state_ready 1 persister is ready to save data. persist_state_saving 2 persister is saving data. persist_state_finished 3 pers...
...all 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 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 typ...
...way. save the specified uri to file. void saveuri( in nsiuri auri, in nsisupports acachekey, in nsiuri areferrer, in long areferrerpolicy, in nsiinputstream apostdata, in string aextraheaders, in nsisupports afile, in nsiloadcontext aprivacycontext ); parameters auri uri to save to file. some implementations of this interface may also support nsnull to imply the currently loaded uri. acachekey an object representing the uri in the cache or nsnull. this can be a necko cache key, an nsiwebpagedescriptor, or the currentdescriptor of an nsiwebpagedescriptor. areferrer the referrer 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 nsnul...
Mail event system
ed notifyitempropertychanged onitempropertychanged notifyitemintpropertychanged onitemintpropertychanged notifyitemboolpropertychanged onitemboolpropertychanged notifyitemunicharpropertychanged onitemunicharpropertychanged notifyitempropertyflagchanged onitempropertyflagchanged notifyitemevent onitemevent notifyfolderloaded onfolderloaded notifydeleteormovemessages ondeleteormovemessages sample code in this example, a listener will be set up to be notified when the message count changes in a folder: // our variable to know if the listener fired var listenerhasfired = false; var totalmessageslistenerhasfired = false; // the listening function that will react to changes function myonintproper...
... getservice(components.interfaces.nsimsgmailsession); mailsession.addlistener(folderlistener); // now test to see if integer stuff is firing at all // let's say "...
...hange the message count, such // as copying a message into this folder or something. then we could // verify that our listener fired by checking if listenerhasfired and // totalmessageslistenerhasfired are true // this is left as an exercise for the reader. future plans the notification system has two duplicate methods which could be implemented with onitemevent/notifyitemevent: folderloaded , and deleteormovemessagescompleted . both of these could be done by making atoms for each of these events and just firing it with notifyitemevent. completed there are some of redundant methods between the nsimsgmailsession and the nsifolderlistener interfaces. nsimsgmailsession also contains a number of other methods that are completely unrealted to folder notification. it would make sense ...
Thunderbird Binaries
described below are three types of generally available thunderbird packages - releases, early preview releases, and nightly builds (including trunk development builds) - and their downloaded locations. additionally, ad-hoc packages called try builds are made available on an as-needed basis to allow for testing of certain patches, and are typically announced in related bug reports. releases thunderbird releases have been extensively tested and are made available for anyone to download and use it. ...
...these builds are made to get feedback from testers and extension developers. ...
...s called try builds are made available on an as-needed basis to allow for testing of certain patches, and are typically announced in related bug reports. releases thunderbird releases have been extensively tested and are made available for anyone to download and use it. thunderbird current release can be downloaded from https://www.mozilla.org/thunderbird/ past thunderbird releases can be downloaded from https://releases.mozilla.org/pub/thunderbird/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. p...
Creating a Custom Column
andler that takes a column id and a handler object. our implementation will need to call something similar to: gdbview.addcolumnhandler("colreplyto", columnhandler); setting the custom column handler we've added a special event that gets fired whenever a view is created. when that event fires, you should set up the custom column handler on the new view. ...
...d a handler object. our implementation will need to call something similar to: gdbview.addcolumnhandler("colreplyto", columnhandler); setting the custom column handler we've added a special event that gets fired whenever a view is created. when that event fires, you should set up the custom column handler on the new view. ...
...tified of the msgcreatedbview event when enigmail is installed [protz]. what happens is: usually, the event sequence is: jsm load -> onload -> msgcreatedbview with enigmail, the event sequence becomes jsm load -> msgcreatedbview -> onload to workaround this, you can either i) manually run addcustomhandler() at the end of your onload handler or ii) register createdbobserver when your .jsm is loaded. some extensions (e.g. rkent's junquilla) use i). ...
Using the Mozilla symbol server
machine. using the symbol server in microsoft visual c++ using the symbol server in windbg the windbg symbol path is configured with a string value delimited with asterisk characters. to use only the mozilla symbol server, add the following entry to your symbol path (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://symbols.mozilla.org/ set this string as _nt_symbol_path in the environment, using the windbg menus, 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 dow...
...symbols): srv*c:\symcache\*https://symbols.mozilla.org/ set this string as _nt_symbol_path in the environment, using the windbg menus, 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 di...
...he\*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\* /s srv*c:\symcache\*https://symbols.mozilla.org/ note the \* after the mozilla directory. the output of this command should be similar to: symchk: fullsoft.dll failed - image is split correctly, but fullsoft.dbg is missing symchk: qfaservices.dll failed - qfaservices.pdb mismatc...
Working with windows in chrome code
pe as the window variable. technically speaking, it implements a number of interfaces, including nsidomjswindow and nsidomwindow, but it also contains the user-defined properties for global variables and functions of the window. so, for example, to access the dom document corresponding to the window, you can use win.document. note however, that the open() call returns before the window is fully loaded, so some calls, like win.document.getelementbyid() will fail. to overcome this difficulty, you can move the initialization code to a load handler of the window being opened or pass a callback function, as described below. you can get a window object from a document using document.defaultview. content windows when a xul window contains a widget capable of displaying a page, such as <browser> or...
...e document opened in the tab are separate from your chrome document. the following two subsections describe how to cross chrome-content boundaries in either way, i.e. accessing elements which are ancestors of your chrome document, or accessing elements which are descendants of your chrome document (but nevertheless in a different context). accessing content documents assume you have a document loaded in a <tabbrowser>, <browser>, or <iframe> element inside your document. you can use browser.contentdocument to access that document and browser.contentwindow to access the window object of that document. you should be aware of xpcnativewrappers when working with untrusted content. with xpcnativewrappers turned on (which is the default in firefox 1.5+), your extension can safely access the dom of...
...bar". to access the elements and variables inside the sidebar, you need to use document.getelementbyid("sidebar").contentdocument or .contentwindow, like when accessing content documents. for more sidebar tips, see code snippets:sidebar. accessing the elements of the top-level document from a child window the opposite case is when you want to access the chrome document from a privileged script loaded in a <browser> or an <iframe>. a typical case when this can be useful is when your code runs in the sidebar in the main firefox window and you want to access the elements in the main browser window. the dom tree, as shown by the dom inspector, can look like this: #document window main-window ... browser #document window myextensionwindow ...
Using js-ctypes
note: js-ctypes only works with c libraries; you can't use c++ methods directly. instead, you'll need to create a shim library that uses c functions that then call into the c++ library for you. examples can be found here: bugzilla :: bug 505907 - support c++ calling from jsctypes library search paths if you specify a full path, that path is used to load the library. otherwise, the sys...
...e("messageboxw", ctypes.winapi_abi, ctypes.int32_t, ctypes.int32_t, ctypes.jschar.ptr, ctypes.jschar.ptr, ctypes.int32_t); var mb_ok = 0; var ret = msgbox(0, "hello world", "title", mb_ok); lib.close(); in line 3, the user32.dll system library is loaded. line 6 declares msgbox() to be a method that calls the windows function messageboxw. line 15 calls the msgbox() routine, which displays the alert. the last thing we do is call lib.close() to close the library when we're done using it. instead of defining the whole path, you may also just give the file name. about declaring the function how we knew how to declare the function was by going to ...
... 0, hit); carbon.close(); the makestr() function is a utility routine that takes as input a standard javascript string and returns a carbon-style "pascal" string, which is a length byte followed by the characters of the string itself. note that this only works correctly if the string is in fact under 256 characters; if it's longer, this will fail spectacularly. in line 9, the carbon library is loaded from the system's carbon framework. line 11 declares the stdalert() function, which will call the carbon standardalert routine. it uses the default abi, returns a 16-bit integer (which is a carbon oserr value), and accepts an integer (the alert type), two strings, a pointer to a parameter block, which we aren't using, and another integer, which is used to return the hit item. see apple's documen...
Scripting plugins - Plugins
come from the same thread. future revisions to this api might provide a mechanism for proxying calls from one thread to another to aid in using this api from other threads. security model the security model for making calls through this api is much like the general same-origin security model enforced by the browser. that means that a script from an origin other than the origin of the page that loaded the plugin is not able to access methods and properties on the plugin. the same thing applies the other way too; the plugin can reach only javascript objects in the same origin as the page that loaded the plugin. in addition to this, a further extension to this api is being discussed that would give a plugin greater flexibility by letting the plugin control the origin of the calling code, so tha...
...this way such code can be executed with only the privileges of the origin of the code, and not the privileges of the plugin page's origin. ...
...page's origin. what's in the plugin code? a plugin that wishes to be scriptable using this new mechanism needs to return the appropriate npobject (which is created by calling npn_createobject) when the browser requests it by calling: npp_getvalue(npp, nppvpluginscriptablenpobject, ...); accessing browser objects from a plugin a plugin that wishes to access objects in the browser window that loaded the plugin can do this by getting the npobject for the browser's window object, or the dom element that loaded the plugin. this is done by using an extension to npn_getvalue. the extensions are two additions to the npnvariables enumeration; the new enumerations are npnvwindownpobject and npnvpluginelementnpobject. calling npn_getvalue() with either of those new enumerations will return an npobjec...
URLs - Plugins
*target); the instance parameter represents the current plug-in instance. the url parameter is the url of the request, which can be of any type, including http, ftp, news, or mailto. the target parameter represents the destination where the url will be displayed, a window or frame. if target refers to the window or frame containing the plug-in instance, it is destroyed and the plug-in may be unloaded. if the target parameter is set to null, the application creates a new stream and delivers the data to the plug-in instance, through calls to npp_newstream, npp_writeready and npp_write, and npp_destroystream. in general, if a url works in the location box of the navigator, it works as a target for npn_geturl, except for the _self target. make sure that the target matches the url type sent to i...
...ecial target names: _blank or _new: load the url in a new blank unnamed window. safest target, even though, when used with a mailto or news url, this creates an extra blank browser instance. _self or _current: load the url into the same window the plug-in instance occupies. if this target refers to the window or frame containing the instance, the instance is destroyed and the plug-in may be unloaded. _parent: load the url into the immediate frameset parent of the plug-in instance document. if the plug-in instance document has no parent, the default is _self. _top: load the url into the plug-in instance window. the default is _self, if the plug-in instance document is already at the top. use for breaking out of a deep frame nesting. be careful when you assign a target. if the target refer...
... parent, the default is _self. _top: load the url into the plug-in instance window. the default is _self, if the plug-in instance document is already at the top. use for breaking out of a deep frame nesting. be careful when you assign a target. if the target refers to the window or frame containing the instance or one of 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 po...
DOM Inspector internals - Firefox Developer Tools
but a panelset is always referred to as a "panelset".) a panel's purpose is to manage available viewers. at the top of each panel is a toolbar which contains a menu button allowing you to choose which viewer to display from the viewer list, a label displaying the name of the currently active viewer, and another menu button allowing you to issue viewer-specific commands. viewers are dynamically loaded; when the panel is made to switch from one viewer to another, the old viewer is destroyed, and the new viewer is loaded in its place. in this way, the panelset and panels function like a frameset and frames. this comparison turns out to be quite apt, since each panel actually contains an anonymous browser, and individual viewers exist in separate documents loaded in the browser. this separation a...
...another convenient consequence of this is that if you use a properly set up development profile, then for the most part, the effects of development changes can be seen by simply switching away from the current viewer and back. ...
...additionally, it defines the content in the main body of the dom inspector window, namely, the panelset, document and ...
Introduction to DOM Inspector - Firefox Developer Tools
pens, it may or may not load an associated document, depending on the host application. if the dom inspector doesn't automatically load a document or loads a document other than the one you'd like to inspect, you can select the desired document a few different ways. inspecting content documents the inspect content document menupopup can be accessed from the file menu, and it will list currently loaded content documents. in firefox and seamonkey browser, these will be the webpages you have opened in tabs. for thunderbird and seamonkey mail and news, any messages you're viewing will be listed here. inspecting chrome documents the inspect chrome document menupopup can be accessed from the file menu , and it will contain the list of currently loaded chrome windows and subdocuments. a browser win...
...rsions of those nodes are highlighted in the user interface itself. (note that there are bugs which prevent the flasher from dom inspector apis from working correctly on certain platforms.) if you inspect the main browser window, for example, and select nodes in the dom nodes viewer (other than the elements which have no visible ui as is the case with the endless list of script elements that are loaded into browser.xul), you will see the various parts of the browser interface being highlighted with a blinking red border. you can traverse the structure and go from the topmost parts parts of the dom tree to lower level nodes, such as the "search-go-button" icon that lets users perform a query using the selected search engine. now, once you have selected a node like the "search-go-button" node,...
...ontext menu. basic actions of the dom nodes viewer selecting elements by click another powerful interactive feature of the dom inspector is that when you have the dom inspector open and have enabled this functionality by choosing edit > select element by click or by clicking the little magnifying glass icon in the upper left portion of the dom inspector application, you can click anywhere in a loaded web page or the the inspect chrome document, and the element you click will be shown in the document pane in the dom nodes viewer and information displayed in the object pane. searching for nodes in the dom another way to inspect the dom is to search for particular elements you're interested in by id, class, or attribute. when you select edit > find nodes... or press ctrl + f, the dom inspector...
UI Tour - Firefox Developer Tools
at the top level sources are organized by origin, and under that they're organized by the directory structure from which they are served. you can search for a file using ctrl + p (cmd + p on a mac). web extensions are listed in the source list pane using the extension's name. there are several context menu options available for individ...
...se within the selected directory to be skipped by the debugger. all such files acquire the eye icon, and the menu option for that folder changes to unignore files outside this directory. outline view the outline view shows a tree for navigating the currently open file. use it to jump directly to a function, class or method definition. source pane this shows the javascript file currently loaded. when the source pane is focused you can search for a string in the file using ctrl + f (cmd + f on a mac). breakpoints have a blue arrow overlaid on the line number. conditional breakpoints have an orange arrow. if you're stopped at a breakpoint, the entire line gets a green overlay. in the screenshot below there are three breakpoints: line 82 has a normal breakpoint and execution is paused...
...nfiguration setting. the setting is reset when the developer tools are closed (except in firefox 77, see bug 1640318). inline variable preview: enabled by default, this option displays variable values within the source pane when the debugger is paused. source maps: enabled by default, this option directs the debugger to load the original versions of files, and map them to the generated ones loaded in a page, to ease debugging of translformed sources. see use a source map for details. breakpoints list under the toolbar, you'll see all the breakpoints you've set. next to each breakpoint is a checkbox which you can use to enable/disable it: watch expressions you can add watch expressions in the right pane. they will be evaluated when code execution is paused: variable tooltip ...
Using images - Web APIs
structor: var img = new image(); // create new img element img.src = 'myimage.png'; // set source path when this script gets executed, the image starts loading. if you try to call drawimage() before the image has finished loading, it won't do anything (or, in older browsers, may even throw an exception). so you need to be sure to use the load event so you don't try this before the image has loaded: var img = new image(); // create new img element img.addeventlistener('load', function() { // execute drawimage statements here }, false); img.src = 'myimage.png'; // set source path if you're only using one 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 imag...
...tcontext('2d'); return document.getelementbyid('myvideo'); } } this returns the htmlvideoelement object for the video, which, as covered earlier, is one of the objects that can be used as a canvasimagesource. drawing images once we have a reference to our source image object we can use the drawimage() method to render it to the canvas. as we will see later the drawimage() method is overloaded and has several variants. in its most basic form it looks like this: drawimage(image, x, y) draws the canvasimagesource specified by the image parameter at the coordinates (x, y). svg images must specify a width and height in the root <svg> element. example: a simple line graph in the following example, we will use an external image as the backdrop for a small line graph. using backdrop...
... which makes them easy to select using document.getelementbyid(). we then simply use drawimage() to slice the rhino out of the first image and scale him onto the canvas, then draw the frame on top using a second drawimage() call. art gallery example in the final example of this chapter, we'll build a little art gallery. the gallery consists of a table containing several images. when the page is loaded, a <canvas> element is inserted for each image and a frame is drawn around it. in this case, every image has a fixed width and height, as does the frame that's drawn around them. you could enhance the script so that it uses the image's width and height to make the frame fit perfectly around it. the code below should be self-explanatory. we loop through the document.images container and add new...
Document.write() - Web APIs
Web › API › Document › write
syntax document.write(markup); parameters markup a string containing the text to be written to the document. ...
...en(); document.write("<h1>out with the old, in with the new!</h1>"); document.close(); } </script> </head> <body onload="newcontent();"> <p>some original document content.</p> </body> </html> notes the text you write is parsed into the document's structure model. in the example above, the h1 element becomes a node in the document. writing to a document that has already loaded without calling document.open() will automatically call document.open(). after writing, call document.close() to tell the browser to finish loading the page. if the document.write() call is embedded within an inline html <script> tag, then it will not call document.open(). for example: <script> document.write("<h1>main title</h1>") </script> note: document.write() and document.writeln do no...
...ot_supported_err] error in the error console). this happens when opening a local file with the .xhtml file extension or for any document served with an application/xhtml+xml mime type. more information is available in the w3c xhtml faq. note: using document.write() in deferred or asynchronous scripts will be ignored and you'll get a message like "a call to document.write() from an asynchronously-loaded external script was ignored" in the error console. note: in edge only, calling document.write() more than once in an <iframe> causes the error "script70: permission denied". note: starting with version 55, chrome will not execute <script> elements injected via document.write() when specific conditions are met. for more information, refer to intervening against document.write(). specifications ...
How to create a DOM tree - Web APIs
...
... ...
... ...
EventTarget.addEventListener() - Web APIs
nt handlers, provides similar functionality as onresize, firing when certain html elements are resized. polyfill you can work around addeventlistener(), removeeventlistener(), event.preventdefault(), and event.stoppropagation() not being supported by internet explorer 8 by using the following code at the beginning of your script. the code supports the use of handleevent() and also the domcontentloaded event. note: usecapture is not supported, as ie 8 does not have any alternative method. the following code only adds ie 8 support. this ie 8 polyfill only works in standards mode: a doctype declaration is required. (function() { if (!event.prototype.preventdefault) { event.prototype.preventdefault=function() { this.returnvalue=false; }; } if (!event.prototype.stoppropagati...
...ners=[]; var addeventlistener=function(type,listener /*, usecapture (will be ignored) */) { var self=this; var wrapper=function(e) { e.target=e.srcelement; e.currenttarget=self; if (typeof listener.handleevent != 'undefined') { listener.handleevent(e); } else { listener.call(self,e); } }; if (type=="domcontentloaded") { var wrapper2=function(e) { if (document.readystate=="complete") { wrapper(e); } }; document.attachevent("onreadystatechange",wrapper2); eventlisteners.push({object:this,type:type,listener:listener,wrapper:wrapper2}); if (document.readystate=="complete") { var e=new event(); e.srcelement=window; ...
...pe,listener:listener,wrapper:wrapper}); } }; var removeeventlistener=function(type,listener /*, usecapture (will be ignored) */) { var counter=0; while (counter<eventlisteners.length) { var eventlistener=eventlisteners[counter]; if (eventlistener.object==this && eventlistener.type==type && eventlistener.listener==listener) { if (type=="domcontentloaded") { this.detachevent("onreadystatechange",eventlistener.wrapper); } else { this.detachevent("on"+type,eventlistener.wrapper); } eventlisteners.splice(counter, 1); break; } ++counter; } }; element.prototype.addeventlistener=addeventlistener; element.prototype.removeeventlistener=removeeventlistener; ...
HTMLImageElement - Web APIs
ached to any dom tree. it accepts optional width and height parameters. when called without parameters, new image() is equivalent to calling document.createelement("img"). properties inherits properties from its parent, htmlelement. htmlimageelement.alt a domstring that reflects the alt html attribute, thus indicating the alternate fallback content to be displayed if the image has not been loaded. htmlimageelement.complete read only returns a boolean that is true if the browser has finished fetching the image, whether successful or not. that means this value is also true if the image has no src value indicating an image to load. htmlimageelement.crossorigin a domstring specifying the cors setting for this image element. see cors settings attributes for further details. this may be nu...
... means this value is also true if the image has no src value indicating an image to load. htmlimageelement.crossorigin a domstring specifying the cors setting for this image element. see cors settings attributes for further details. this may be null if cors is not used. htmlimageelement.currentsrc read only returns a usvstring representing the url from which the currently displayed image was loaded. this may change as the image is adjusted due to changing conditions, as directed by any media queries which are in place. htmlimageelement.decoding an optional domstring representing a hint given to the browser on how it should decode the image. if this value is provided, it must be one of the possible permitted values: sync to decode the image synchronously, async to decode it asynchronously,...
... trying to load or render the image, and an onerror event handler has been configured to handle 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 specified src url is the same as the url of the page the user is currently on. the specified image is corrupted in some way that prevents it from being loaded. the specified image's metadata is corrupted in such a way that it's impossible to retrieve its dimensions, and no dimensions were specified in the <img> element's attributes. the specified image is in a format not supported by the user agent. example var img1 = new image(); // image constructor img1.src = 'image1.png'; img1.alt = 'alt'; document.body.appendchild(img1); var img2 = document.
HTMLMediaElement.readyState - Web APIs
r the current playback position as well as for at least a little bit of time into the future is available (in other words, at least two frames of video, for example). have_enough_data 4 enough data is available—and the download rate is high enough—that the media can be played through to the end without interruption. ...
...e (in other words, at least two frames of video, for example). have_enough_data 4 enough data is available—and the download rate is high enough—that the media can be played through to the end without interruption. examples this example will listen for audio data to be loaded for the element `example`. it will then check if at least the current playback position has been loaded. if it has, the audio will play. ...
...the end without interruption. examples this example will listen for audio data to be loaded for the element `example`. it will then check if at least the current playback position has been loaded. if it has, the audio will play. <audio id="example" preload="auto"> <source src="sound.ogg" type="audio/ogg" /> </audio> var obj = document.getelementbyid('example'); obj.addeventlistener('loadeddata', function() { if(obj.readystate >= 2) { obj.play(); } }); specifications specification status comment html living standardthe definition of 'htmlmediaelement.readystate' in that specification. living standard html5the definition of 'htmlmediaelement.readystate' in that specification. recommendation ...
History - Web APIs
Web › API › History
scrollrestoration allows web applications to explicitly set default scroll restoration behavior on history navigation. this property can be either auto or manual. ...
... scrollrestoration allows web applications to explicitly set default scroll restoration behavior on history navigation. this property can be either auto or manual. ...
... scrollrestoration allows web applications to explicitly set default scroll restoration behavior on history navigation. this property can be either auto or manual. ...
NavigationPreloadManager - Web APIs
ther preload is enabled and the contents of the service-worker-navigation-preload. ...
...eature 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. ...
... return fetch(event.request); }()); }); specifications specification status comment service workersthe definition of 'navigationpreloadmanager' in that specification. ...
PerformanceNavigationTiming.domComplete - Web APIs
the following example illustrates this property's usage. ...
...lustrates this property's usage. ...
...ge. ...
PerformanceNavigationTiming.domInteractive - Web APIs
the following example illustrates this property's usage. ...
...lustrates this property's usage. ...
...ge. ...
PerformanceNavigationTiming.loadEventEnd - Web APIs
the following example illustrates this property's usage. ...
...lustrates this property's usage. ...
...ge. ...
PerformanceNavigationTiming.loadEventStart - Web APIs
the following example illustrates this property's usage. ...
...lustrates this property's usage. ...
...ge. ...
PerformanceNavigationTiming.redirectCount - Web APIs
the following example illustrates this property's usage. ...
...lustrates this property's usage. ...
...ge. ...
PerformanceNavigationTiming.type - Web APIs
the following example illustrates this property's usage. ...
...lustrates this property's usage. ...
...ge. ...
PerformanceNavigationTiming.unloadEventEnd - Web APIs
the following example illustrates this property's usage. ...
...lustrates this property's usage. ...
...ge. ...
PerformanceNavigationTiming.unloadEventStart - Web APIs
the following example illustrates this property's usage. ...
...lustrates this property's usage. ...
...ge. ...
VideoPlaybackQuality.corruptedVideoFrames - Web APIs
it is up to the user agent to determine whether or not to display a corrupted video frame. if a corrupted frame is dropped, then both corruptedvideoframes and droppedvideoframes are incremented. ...
... it is up to the user agent to determine whether or not to display a corrupted video frame. if a corrupted frame is dropped, then both corruptedvideoframes and droppedvideoframes are incremented. ...
... it is up to the user agent to determine whether or not to display a corrupted video frame. if a corrupted frame is dropped, then both corruptedvideoframes and droppedvideoframes are incremented. ...
VideoPlaybackQuality.droppedVideoFrames - Web APIs
this information can be used to determine whether or not to downgrade the video stream to avoid dropping frames. ...
...this information can be used to determine whether or not to downgrade the video stream to avoid dropping frames. ...
...this information can be used to determine whether or not to downgrade the video stream to avoid dropping frames. ...
Starting up and shutting down a WebXR session - Web APIs
ough the webxr ar module, which has is approaching a stable state. documentation for ar is forthcoming shortly here on mdn. other improvements include updating 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 ...
...l brings support for webxr to browsers that don't have native webxr support, and smooths out the inconsistencies among implementations in the browsers that do have it, so it can sometimes also be useful even if webxr is natively available. here we define a getxr() function, which returns the xrsystem object after optionally installing the polyfill, assuming that the polyfill has been included or loaded using a prior <script> tag. let webxrpolyfill = null; function getxr(usepolyfill) { let tempxr; let temppoly; switch(usepolyfill) { case "if-needed": if (!navigator.xr) { webxrpolyfill = new webxrpolyfill(); } tempxr = navigator.xr; break; case "yes": webxrpolyfill = new webxrpolyfill(); tempxr = navigator.xr; break; case "no"...
... the user turned off their headset, or some sort of irresolvable error occurred in the xr system—by watching for the end event to be sent to the xrsession. session.onend = (event) => { /* the session has shut down */ freeresources(); }; here, when the session has ended and the end event is received, a freeresources() function is called to release the resources previously allocated and/or loaded to handle the xr presentation. by calling freeresources() in the end event handler, we call it both when the user clicks a button that triggers a shutdown such as by calling the shutdownxr() function shown above and when the session ends automatically, whether due to an error or some other reason. ...
Advanced techniques: Creating and sequencing audio - Web APIs
nnect(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. ...
...uffer = await audiocontext.decodeaudiodata(arraybuffer); return audiobuffer; } we can then use the await operator when calling this function, which ensures that we can only run subsequent code when it has finished executing. let's create another async function to set up the sample — we can combine the two async functions in a nice promise pattern to perform further actions when this file is loaded and buffered: async function setupsample() { const filepath = 'dtmf.mp3'; const sample = await getfile(audioctx, filepath); return sample; } note: you can easily modify the above function to take an array of files and loop over them to load more than one sample. this would be very handy for more complex instruments, or gaming. we can now use setupsample() like so: setupsample() ...
... drawnote) { pads.foreach(function(el, i) { el.children[lastnotedrawn].style.bordercolor = 'hsla(0, 0%, 10%, 1)'; el.children[drawnote].style.bordercolor = 'hsla(49, 99%, 50%, 1)'; }); lastnotedrawn = drawnote; } // set up to draw again requestanimationframe(draw); } putting it all together now all that's left to do is make sure we've loaded the sample before we are able to play the instrument. we'll add a loading screen that disappears when the file has been fetched and decoded, then we can allow the scheduler to start using the play button click event. // when the sample has loaded allow play let loadingel = document.queryselector('.loading'); const playbutton = document.queryselector('[data-playing]'); let isplaying = false; setu...
Using Web Workers - Web APIs
/* imports nothing */ importscripts('foo.js'); /* imports just "foo.js" */ importscripts('foo.js', 'bar.js'); /* imports two scripts */ importscripts('//example.com/hello.js'); /* you can import scripts from other origins */ the browser loads each listed script and executes it. any global objects from each script may then be used by the worker. ...
...t may then be used by the worker. if the script can't be loaded, network_error is thrown, and subsequent code will not be executed. previously executed code (including code deferred using window.settimeout()) will still be functional though. function declarations after the importscripts() method are also kept, since these are always evaluated before the rest of the code. note: scripts may be downloaded in any order, but will be executed in the order in which you pass the filenames into importscripts() . this is done synchronously; importscripts() does not return until all the scripts have been loaded and executed. shared workers a shared worker is accessible by multiple scripts — even if they are being accessed by different windows, iframes or even workers. in this section we'll discuss the...
...rences between dedicated and shared workers. note that in this example we have two html pages, each with javascript applied that uses the same single worker file. note: if sharedworker can be accessed from several browsing contexts, all those browsing contexts must share the exact same origin (same protocol, host, and port). note: in firefox, shared workers cannot be shared between documents loaded in private and non-private windows (bug 1177621). spawning a shared worker spawning a new shared worker is pretty much the same as with a dedicated worker, but with a different constructor name (see index.html and index2.html) — each one has to spin up the worker using code like the following: var myworker = new sharedworker('worker.js'); one big difference is that with a shared worker you...
Window: popstate event - Web APIs
ut its inner callback function that does the processing at the end of the browser event loop: window.onpopstate = () => settimeout(dosomething, 0); when popstate is sent when the transition occurs, either due to the user triggering the browser's "back" button or otherwise, the popstate event is near the end of the process to transition to the new location. it happens after the new location has loaded (if needed), displayed, made visible, and so on, after the pageshow event is sent, but before the persisted user state information is restored and the hashchange event is sent. to better understand when the popstate event is fired, consider this simplified sequence of events that occurs when the current history entry changes due to either the user navigating the site or the history being travers...
...e history being traversed programmatically. here, the transition is changing the current history entry to one we'll refer to as new-entry. the current page's session history stack entry will be referred to as current-entry. if new-entry doesn't currently contain an existing document, fetch the content and create its document before continuing. this will eventually send events such as domcontentloaded and load to the window containing the document, but the steps below will continue to execute in the meantime. if current-entry's title wasn't set using one of the history api methods (pushstate() or replacestate(), set the entry's title to the string returned by its document.title attribute. if the browser has state information it wishes to store with the current-entry before navigating away fr...
...ment referred to by new-entry, and the context's name is updated to match the context name of the now-current document. each form control within new-entry's document that has autocomplete configured with its autofill field name set to off is reset. see the html autocomplete attribute for more about the autocomplete field names and how autocomplete works. if new-entry's document is already fully loaded and ready—that is, its readystate is complete—and the document is not already visible, it's made visible and the pageshow event is fired at the document with the pagetransitionevent's persisted attribute set to true. the document's url is set to that of new-entry. if the history traversal is being performed with replacement enabled, the entry immediately prior to the destination entry (taki...
Using XMLHttpRequest - Web APIs
equest(); oreq.addeventlistener("progress", updateprogress); oreq.addeventlistener("load", transfercomplete); oreq.addeventlistener("error", transferfailed); oreq.addeventlistener("abort", transfercanceled); oreq.open(); // ... // progress on transfers from the server to the client (downloads) function updateprogress (oevent) { if (oevent.lengthcomputable) { var percentcomplete = oevent.loaded / oevent.total * 100; // ... } else { // unable to compute progress information since the total size is unknown } } function transfercomplete(evt) { console.log("the transfer is complete."); } function transferfailed(evt) { console.log("an error occurred while transferring the file."); } function transfercanceled(evt) { console.log("the transfer has been canceled by the user.
...re sent while performing a data transfer using xmlhttprequest. note: you need to add the event listeners before calling open() on the request. otherwise the progress events will not fire. the progress event handler, specified by the updateprogress() function in this example, receives the total number of bytes to transfer as well as the number of bytes transferred so far in the event's total and loaded fields. however, if the lengthcomputable field is false, the total length is not known and will be zero. progress events exist for both download and upload transfers. the download events are fired on the xmlhttprequest object itself, as shown in the above sample. the upload events are fired on the xmlhttprequest.upload object, as shown below: var oreq = new xmlhttprequest(); oreq.upload.addeve...
...bmit" /> </p> </fieldset> </form> </body> </html> note: as we said, formdata objects are not stringifiable objects. if you want to stringify a submitted data, use the previous pure-ajax example. note also that, although in this example there are some file <input> fields, when you submit a form through the formdata api you do not need to use the filereader api also: files are automatically loaded and uploaded. get last modified date function getheadertime () { console.log(this.getresponseheader("last-modified")); /* a valid gmtstring date or null */ } var oreq = new xmlhttprequest(); oreq.open("head" /* use head if you only need the headers! */, "yourpage.html"); oreq.onload = getheadertime; oreq.send(); do something when last modified date changes let's create two functions: fun...
Implementing a Microsoft Active Accessibility (MSAA) Server - Accessibility
your application closes, different signals are typically broadcast. for example, the application window closes and the window is blurred. it is impossible to know if and when the 3rd party assistive technology will use one of these signals to release the objects of yours that is is refcounting. this can lead to crashes where it releases something and the wrong time, when some of your dll's are unloaded but not others, and a destructor is called in an unloaded dll. solution: create a "shutdown" method for each internal accessible object, to remove any references to other internal objects before any of your dll's are unloaded. in order to do this effectively, you will have to keep track of every accessible object that you create. the shutdown method for an accessibility object should be called w...
...o 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 scrollto method, also needed by screen magnifiers. implement a custom interface for text objects, and support it through queryinterface or queryservice if it's being im...
...start listening for dom, page load and scroll events. these events cause msaa-specific events, such as event_object_focus or event_object_statechange, to fire on ui and document objects within the applicable window. we'll explain more about events later in this section. until the wm_getobject message is processed, the gecko accessibility service is not used, and thus the accessibility.dll is not loaded, so there is almost zero overhead for accessibility api support in mozilla or gecko, in the general case. once the accessibility service is created, however, gecko loads code to create an object on demand for every ui or document object that should support iaccessible. the created objects are cached in a hash table, and shutdown when they're no longer needed. they may still exist in memory in a n...
font-display - CSS: Cascading Style Sheets
syntax /* keyword values */ font-display: auto; font-display: block; font-display: swap; font-display: fallback; font-display: optional; values auto the font display strategy is defined by the user agent. block gives the font face a short block period and an infinite swap period. swap gives the font face an extremely small block period and an infinite swap period. fallback gives the font face an extremely small block period and a short swap period. optional gives the font face an extremely small block period and no swap period. ...
...the font face an extremely small block period and an infinite swap period. fallback gives the font face an extremely small block period and a short swap period. optional gives the font face an extremely small block period and no swap period. ...
...ce an extremely small block period and no swap period. description the font display timeline the font display timeline is based on a timer that begins the moment the user agent attempts to use a given downloaded font face. the timeline is divided into the three periods below which dictate the rendering behavior of any elements using the font face. font block period if the font face is not loaded, any element attempting to use it must render an invisible fallback font face. if the font face successfully loads during this period, it is used normally. font swap period if the font face is not loaded, any element attempting to use it must render a fallback font face. if the font face successfully loads during this period, it is used normally. font failure period if the font face is not lo...
@font-face - CSS: Cascading Style Sheets
font-family specifies a name that will be used as the font face value for font properties. font-stretch a font-stretch value. ...
... font-family specifies a name that will be used as the font face value for font properties. font-stretch a font-stretch value. since firefox 61 (and in other modern browsers) this also accepts two values to specify a range that is supported by a font-face, for example font-stretch: 50% 200%; font-style a font-style value. ...
...pes are: "woff", "woff2", "truetype", "opentype", "embedded-opentype", and "svg". unicode-range the range of unicode code points to be used from the font. description if the local() function is provided, specifying a font name to look for on the user's computer, and the user agent finds a match, that local font is used. otherwise, the font resource specified using the url() function is downloaded and used. by allowing authors to provide their own fonts, @font-face makes it possible to design content without being limited to the so-called "web-safe" fonts (that is, the fonts which are so common that they'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...
Variable fonts guide - CSS: Cascading Style Sheets
that has different widths as well). in such a scenario, in order to use a typeface for typical use on a site for body copy you would need at least four files: regular, italic, bold, and bold italic. if you wanted to add more weights, like a lighter one for captions or a heavier one for extra emphasis, that would mean several more files. this results in more http requests, and more data being downloaded (usually around 20k or more per file). variable fonts with a variable font, all of those permutations can be contained in a single file. that file would be larger than a single font, but in most cases smaller or about the same size as the 4 you might load for body copy. the advantage in choosing the variable font is that you have access to the entire range of weights, widths, and styles availab...
...l of those permutations can be contained in a single file. that file would be larger than a single font, but in most cases smaller or about the same size as the 4 you might load for body copy. the advantage in choosing the variable font is that you have access to the entire range of weights, widths, and styles available, rather than being constrained to only the few that you previously would have loaded separately. this allows for common typographic techniques such as setting different size headings in different weights for better readability at each size, or using a slightly narrower width for data-dense displays. for comparison, it is typical in a typographic system for a magazine to use 10–15 or more different weight and width combinations throughout the publication — giving a much wider...
...ariable 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 being loaded. example for a standard upright (roman) font: @font-face { font-family: 'myvariablefontname'; src: 'path/to/font/file/myvariablefont.woff2' format('woff2-variations'); font-weight: 125 950; font-stretch: 75% 125%; font-style: normal; } example for a font that includes both upright and italics: @font-face { font-family: 'myvariablefontname'; src: 'path/to/font/file/myvariablefont.woff2...
Audio and Video Delivery - Developer guides
"3gp_src" src="video.3gp" type='video/3gpp; codecs="mp4v.20.8, samr"'> </source> <source id="ogg_src" src="video.ogv" type='video/ogv; codecs="theora, vorbis"'> </source> </video> since firefox doesn't support mp4 and 3gp on some platforms due to their patent-encumbered nature, the <source> elements with the ids "mp4_src" and "3gp_src" will receive error events before the ogg resource is loaded. the sources are tried in the order in which they appear, and once one loads successfully, the remaining sources aren't tried at all. checking whether the browser supports the supplied formats use the following verified sources within your audio and video elements to check support. audio mp3 (type="audio/mpeg"): http://jplayer.org/audio/mp3/miaow-01-tempered-song.mp3 (play the mp3 audio live...
...if this is htmlmediaelement.network_no_source, you know that all the sources failed to load. if at that point you add another source, by inserting a new <source> element as a child of the media element, gecko attempts to load the specified resource. showing fallback co...
...yling for the player. cross-browser audio basics this article provides a basic guide to creating an html5 audio player that works cross browser, with all the associated attributes, properties and events explained, and a quick guide to custom controls created using the media api. media buffering, seeking, and time ranges sometimes it's useful to know how much <audio> or <video> has downloaded or is playable without delay — a good example of this is the buffered progress bar of an audio or video player. this article discusses how to build a buffer/seek bar using timeranges, and other features of the media api. html5 playbackrate explained the playbackrate property allows us to change the speed or rate at which a piece of web audio or video is playing. this article explains it in de...
Overview of events and handlers - Developer guides
javascript integrated into web pages is wrapped into an event function call to ensure that the code is only executed when the html has been processed and is available for alteration or decoration. for example, code might be attached as: var funcinit = function(){ // user code goes here and can safely address all the html elements from the page // since the document has successfully been 'loaded' } document.addeventlistener('domcontentloaded', funcinit); so that this code will only be executed after the document object emits the 'domcontentloaded' event because the html has been parsed and javasript objects created representing each of the nodes of the html document. note that in this example, the code does not even name the event argument to the function because the code never needs t...
...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. ...
...vent 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 browser window is changed by a user, the dom object document representing the html document emits an event called 'domcontentloaded' when the document has finished loading, the dom node objects such as div or button emit an event called 'click' when the user presses the mouse button while the mouse pointer is on top of the dom node in the html page. 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 ...
<iframe>: The Inline Frame element - HTML: Hypertext Markup Language
Web › HTML › Element › iframe
ity policy enforced for the embedded resource. see htmliframeelement.csp for details. height the height of the frame in css pixels. default 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 v...
...also served from a separate origin to limit potential damage. the sandbox attribute is unsupported in internet explorer 9 and earlier. src the url of the page to embed. use a value of about:blank to embed an empty page that conforms to the same-origin policy. also note that programatically removing an <iframe>'s src attribute (e.g. via element.removeattribute()) causes about:blank to be loaded in the frame in firefox (from version 65), chromium-based browsers, and safari/ios. srcdoc inline html to embed, overriding the src attribute. if a browser does not support the srcdoc attribute, it will fall back to the url in the src attribute. width the width of the frame in css pixels. default is 300. deprecated attributes these attributes are deprecated and may no longer be supported b...
... resource via the contentwindow property. the contentdocument property refers to the document inside the <iframe>, same as contentwindow.document. from the inside of a frame, a script can get a reference to its parent window with window.parent. script access to a frame's content is subject to the same-origin policy. scripts cannot access most properties in other window objects if the script was loaded from a different origin, including scripts inside a frame accessing the frame's parent. cross-origin communication can be achieved using window.postmessage(). positioning and scaling as a replaced element, the position, alignment, and scaling of the embedded document within the <iframe> element's box, can be adjusted with the object-position and object-fit properties. examples a simple <ifram...
<img>: The Image Embed element - HTML: Hypertext Markup Language
Web › HTML › Element › img
hows usage of the <img> element: the src attribute is required, and contains the path to the image you want to embed. the alt attribute holds a text description of the image, which isn't mandatory but is incredibly useful for accessibility — screen readers read this description out to their users so they know what the image means. alt text is also displayed on the page if the image can't be loaded for some reason: for example, network errors, content blocking, or linkrot. there are many other attributes to achieve various purposes: referrer/cors control for security and privacy: see crossorigin and referrerpolicy. use both width and height to set the intrinsic size of the image, allowing it to take up space before it loads, to mitigate content layout shifts. responsive image hints w...
...g 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 loaded. the image's metadata is corrupted in such a way that it's impossible to retrieve its dimensions, and no dimensions were specified in the <img> element's attributes. the image is in a format not supported by the user agent. attributes this element includes the global attributes. alt defines an alternative text description of the image. note: browsers do not always display images. ther...
...rnative text describe the resource the link is pointing to, as if you were using a text link instead. <a href="https://developer.mozilla.org"> <img src="https://udn.realityripple.com/samples/6c/98485e5d8a.png" alt="visit the mdn site"> </a> using the srcset attribute in this example we include a srcset attribute with a reference to a high-resolution version of the logo; this will be loaded instead of the src image on high-resolution devices. the image referenced in the src attribute is counted as a 1x candidate in user agents that support srcset. <img src="https://udn.realityripple.com/samples/61/869e27c81e.png" alt="mdn logo" srcset="/static/external/6c/6c98485e5d8acac9fecd7824ce30c9587f0d8548b946ee9fb1293d2eccdb6cf1.png 2x"> using the srcset and sizes attributes ...
HTTP caching - HTTP
Web › HTTP › Caching
owser and proxy caches, but there are also gateway caches, cdn, reverse proxy caches and load balancers that are deployed on web servers for better reliability, performance and scaling of web sites and web applications. private browser caches a private cache is dedicated to a single user. you might have seen "caching" in your browser's settings already. a browser cache holds all documents downloaded via http by the user. this cache is used to make visited documents available for back/forward navigation, saving, viewing-as-source, etc. without requiring an additional trip to the server. it likewise improves offline browsing of cached content. shared proxy caches a shared cache is a cache that stores responses to be reused by more than one user. for example, an isp or your company might have...
...cache-control header the cache-control http/1.1 general-header field is used to specify directives for caching mechanisms in both requests and responses. use this header to define your caching policies with the variety of directives it provides. no caching the cache should not store anything about the client request or server response. a request is sent to the server and a full response is downloaded each and every time. cache-control: no-store cache but revalidate a cache will send the request to the origin server for validation before releasing a cached copy. cache-control: no-cache private and public caches the "public" directive indicates that the response may be cached by any cache. this can be useful if pages with http authentication, or response status codes that aren't normally...
...ovided either a strong validator or a weak validator. revalidation is triggered when the user presses the reload button. it is also triggered under normal browsing if the cached response includes the "cache-control: must-revalidate" header. another factor is the cache validation preferences in the advanced->cache preferences panel. there is an option to force a validation each time a document is loaded. etags the etag response header is an opaque-to-the-useragent value that can be used as a strong validator. that means that a http user-agent, such as the browser, does not know what this string represents and can't predict what its value would be. if the etag header was part of the response for a resource, the client can issue an if-none-match in the header of future requests – in order to v...
Web audio codec guide - Web media technologies
ch compression do you need to achieve? let's consider a few common scenarios to get a feel for the decision-making process. example: music for streaming for streaming music, you want to select a codec that minimizes bandwidth usage as much as possible while introducing as few artifacts as possible into the audio through compression. this is necessary because the rate at which the music is downloaded needs to be no greater than the amount of bandwidth available on the network, and ideally there should be room left for network speed fluctuations and use of the network by other applications. unless there's a specific need for lossless compression, or the network bandwidth is guaranteed to be high enough to support it, a lossy compression scheme is a good choice. which one you choose depends on...
...re to refer to the compatibility tables before committing to a given media format. based on this, aac is likely your best choice if you can only support one audio format. of course, if you can provide multiple formats (for example, by using the <source> element within your <audio> and <video> elements), you can avoid many or all of those exceptions. example: music for download music being downloaded by the user can be compressed to a larger overall file size than streamed music, since (unlike when streaming) it doesn't matter if the download speed is slower than the playback speed of the media. that means you can consider using lossy compression at higher bit rates, which results in larger files but with less loss of fidelity. or you can choose a lossless format. the choice depends largely o...
...f your application's requirements and the preferences of your users. for an actual music download service, you might offer songs for download as 128 kbps mp3 files, 256 kbps aac files (in mp4 containers), or flac files, depending on a preference selected by the user. if you need to choose just one format, select one that makes sense given your requirements and the type of audio content being downloaded. generally, of course, mp3 is the most common format used for music; choose a bit rate of at least 192 kbps if possible. the itunes store, on the other hand, distributes music in 256 kbps aac format. example: voice recording and playback the specific characteristics of human speech allow speech-specific codecs to compress the audio far more than most general-purpose codecs can. that's because ...
Privacy, permissions, and information security
gardless of how it's obtained. privacy exceptions may be granted to specific sites or applications, but it may also be granted conditionally, such as by permitting only a select group of people to access it, or only allowing the information to be accessed and used for a limited period of time. security security is about the active protection of data or a system against being accessed, downloaded, or operated by people or organizations that don't have permission to do so. good security practices aim to prevent unauthorized access to systems or data, regardless of what the target is. personal and private information <what kind of information is private or personal?> privacy risks <what are ways personal information can be gotten by third parties?> fingerprinting fingerprinting is ...
...tificates content security policy provides the ability to define the extent to which a document's content can be accessed by other devices over the web; used in particular to prevent or mitigate attacks on the server feature policy lets web developers selectively enable, disable, and modify the behavior of certain features and apis both for a document and for subdocuments loaded in <iframe>s <iframe>'s allow attribute technically part of feature policy, the allow attribute on an <iframe> specifies which web features the document in the frame should be allowed to access http public key pinning (hpkp) hpkp is used by servers to instruct a client to associate a specific public key with the server going forward in order to decrease the likelihood of m...
...for these technologies either state or recommend tactics for handling situations like this, browsers may offer different solutions to improve security even further or to try new features, or try to reduce complexity for users, among other possible reasons. <--- allow attribute, feature policy, and permissions api stuff ---> a specific user experience issue that often arises is a document that's loaded with permission to access a resource and the document contains an <iframe> with the allow attribute to delegate that permission to the contents of the frame. in this case, it's possible for the user to wind up being prompted repeatedly for that same resource, first by the main page, then by the document in the frame. browsers may choose to provide ways around this. for example, in firefox 73, th...
Progressive web app structure - Progressive web apps (PWAs)
approach to server- or client-side rendering can be achieved with the streams api. with a little help from service workers, streams can greatly improve the way we parse content. the app shell model requires all the resources to be available before the website can start rendering. ...
...p from service workers, streams can greatly improve the way we parse content. the app shell model requires all the resources to be available before the website can start rendering. it's different with html, as the browser is actually streaming the data already and you can see when the elements are loaded and rendered on the website. to have the javascript "operational", however, it has to be downloaded in its entirety. the streams api allows developers to have direct access to data streaming from the server — if you want to perform an operation on the data (for example, adding a filter to a video), you no longer need to wait for all of it to be downloaded and converted to a blob (or whatever) — you can start right away. it provides fine-grained control — the stream can be started, chaine...
..., twitter: 'platane_', website: 'github.com/platane', github: 'github.com/platane/js13k-2017' }, // ... { slug: 'emma-3d', name: 'emma-3d', author: 'prateek roushan', twitter: '', website: '', github: 'github.com/coderprateek/emma-3d' } ]; every entry has its own image in the data/img folder. this is our content, loaded into the content section with javascript. next up in the next article we will look in more detail at how the app shell and the content are cached for offline use with the help from the service worker. previous overview: progressive web apps next ...
Index - XSLT: Extensible Stylesheet Language Transformations
Web › XSLT › Index
rs xslt no summary! 5 the xslt/javascript interface in gecko xslt no summary! 6 advanced example xslt this advanced example sorts several divs based on their content. the example allows sorting the content multiple times, alternating between ascending and descending order. the javascript loads the .xsl file only on the first sort and sets the xslloaded variable to true once it has finished loading the file. using the xsltprocessor.getparameter() method, the code can figure whether to sort in ascending or descending order. it defaults to ascending if the parameter is empty (the first time the sorting happens, as there is no value for it in the xslt file). the sorting value is set using xsltprocessor.setparameter(). 7 basic example ...
... see xsltprocessor in the web api documentation section. 9 introduction gecko, intro, javascript, xslt with modern browsers supporting xslt, developers can now use javascript to access the power that xslt provides. javascript can enable a web application to load xml data, process it via xslt into a presentable form and then add it into an existing document. since the xml data loaded only contains the raw information without any presentation data, it can load quickly even on dialup. 10 javascript/xslt bindings dom, javascript, xml, xslt javascript can run xslt transformations through the xsltprocessor object. once instantiated, an xsltprocessor has an xsltprocessor.importstylesheet() method that takes as an argument the xslt stylesheet to be used in the t...
... javascript/xslt bindings dom, javascript, xml, xslt javascript can run xslt transformations through the xsltprocessor object. once instantiated, an xsltprocessor has an xsltprocessor.importstylesheet() method that takes as an argument the xslt stylesheet to be used in the transformation. the stylesheet has to be passed in as an xml document, which means that the .xsl file has to be loaded by the page before calling xsltprocessor.importstylesheet(). this can be done via xmlhttprequest or xmldocument.load(). 11 resources xslt no summary! 12 setting parameters xslt while running transformations using precoded .xsl and .xml files is quite useful, configuring the .xsl file from javascript may be even more useful. for example, javascript and xsl...
port - Archive of obsolete content
won't be encoded. you also can't include circular references. ...
...var pagemods = require("sdk/page-mod"); var self = require("sdk/self"); var pagemod = pagemods.pagemod({ include: ['*'], contentscriptfile: self.data.url("content-script.js"), onattach: setuplistener }); function setuplistener(worker) { worker.port.on('loaded', function(pageinfo) { console.log(pageinfo[0]); console.log(pageinfo[1]); }); } //content-script.js self.port.emit('loaded', [ document.location.tostring(), document.title ]); ...
Communicating using "port" - Archive of obsolete content
he payload can be serialized to json. this means that it needs to be a string, number, boolean, null, array of json-serializable values, or an object whose property values are themselves json-serializable. this means you can't send functions, and if the object contains methods they won't be encoded. ...
...f strings in the payload: var pagemodscript = "self.port.emit('loaded'," + " [" + " document.location.tostring()," + " document.title" + " ]" + ");" var pagemod = require('page-mod').pagemod({ include: ['*'], contentscript: pagemodscript, onattach: function(worker) { worker.port.on('loaded', function(pageinfo) { console.log(pageinfo[0]); console.log(pageinfo[1]); }); } }); ...
Working with Events - Archive of obsolete content
whenever the event occurs. the arguments that will be passed to the listener are specific to an event type and are documented with the event emitter. for example, the following add-on registers a listener with the tabs module to listen for the ready event, and logs a string to the console reporting the event: var tabs = require("sdk/tabs"); tabs.on("ready", function () { console.log("tab loaded"); }); it is not possible to enumerate the set of listeners for a given event. the value of this in the listener function is the object that emitted the event. listening to all events you can pass the wildcard "*" as the type argument. if you do this, the listener will be called for any event emitted by that object, and its argument will be the name of the event: var ui = require("sdk/ui");...
... ...
private-browsing - Archive of obsolete content
r a worker that's associated with a document hosted in a private window any window, tab, or worker if the browser has been configured to never remember history (options->privacy->history) add-ons can use this api to decide whether or not to store user data. ...
...in the handler for the page-mod's attach event, it passes the worker into isprivate(): var pagemod = require("sdk/page-mod"); var privatebrowsing = require("sdk/private-browsing"); var loggingscript = "self.port.on('log-content', function() {" + " console.log(document.body.innerhtml);" + "});"; function logpublic...
ui/toolbar - Archive of obsolete content
de the toolbar using the firefox "view/toolbars" menu, alongside built-in toolbars like the bookmarks toolbar. hidden state persists even over create/destroy cycles: if a toolbar is created, then hidden, then destroyed, and another toolbar with the same title is then created, the new toolbar will be in the hidden state. toolbar events toolbars get attach and detach events when their content is loaded and unloaded, and show and hide events when the uses shows or hides them. working with multiple browser windows there's only a single toolbar for all browser windows, so operations like show and hide work across all browser windows. if you need to customize content for a particular browser window, you can do that by messaging the window-specific frame hosted by that toolbar. globals construct...
...able until after the attach event is emitted. items the array of frames hosted by this toolbar. this property is read-only and is not available until after the attach event is emitted. hidden boolean indicating whether the toolbar is hidden. this property is read-only and is not available until after the attach event is emitted. events attach this event is emitted when the toolbar is first loaded. note that since there is only one toolbar for the whole browser, opening another browser window does not cause this event to be emitted again. after this event the toolbar's properties are available: var { toolbar } = require("sdk/ui/toolbar"); var { frame } = require("sdk/ui/frame"); var frame = new frame({ url: "./frame.html" }); var toolbar = toolbar({ title: "my toolbar", items: [fr...
Low-Level APIs - Archive of obsolete content
y, and retrieve bookmarks. places/favicon helper functions for working with favicons. places/history access the user's browsing history. platform/xpcom implement xpcom objects, factories, and services. preferences/event-target listen to changes to the preferences system in firefox. preferences/service access the preferences system in firefox. remote/child enables an sdk module loaded into a child process to access web content in the child process and communicate with modules in the main process. remote/parent enables you to load modules, and privileged parts of your add-on in general, into child processes. stylesheet/style modify styles using stylesheet files or css rules. stylesheet/utils helper functions for working with stylesheets. system/child_process an implemen...
...r functions for working with stylesheets. system/child_process an implementation of the node.js child_process api. system/environment access, set and clear environment variables. system/events api for working with the application observer service. system/runtime access to information about firefox's runtime environment. system/unload register callbacks that are called when a module is unloaded. system/xul-app information about the application on which your add-on is running. tabs/utils functions for working with xul tabs and the xul tabbrowser object. test/assert implements the assert interface defined in the commonjs unit testing specification version 1.1. test/harness test harness setup and execution. test/httpd an http server for the mozilla platform, which can be used in ...
Displaying annotations - Archive of obsolete content
, and for a more complex widget try the toolbar or sidebar apis. in this chapter we'll use a page-mod to locate elements of web pages that have annotations associated with them, and a panel to display the annotations. matcher page-mod matcher content script the content script for the matcher page-mod is initialized with a list of all the annotations that the user has created. when a page is loaded the matcher searches the dom for elements that match annotations. if it finds any it binds functions to that element's mouseenter and mouseleave events to send messages to the main module, asking it to show or hide the annotation. like the selector, the matcher also listens for the window's unload event and on unload sends a detach message to the main module, so the add-on can clean it up. the ...
...this function: initializes the content script instance with the current set of annotations provides a handler for messages from that content script, handling the three messages - show, hide and detach - that the content script might send adds the worker to an array, so we it can send messages back later. then in the module's scope implement a fu...
Getting Started (jpm) - Archive of obsolete content
firefox with your add-on installed. if firefox can not be located, or you have installed firefox developer as an alternate browser, you may need to provide the path to it. for example, in ubuntu: jpm run -b /usr/bin/firefox when firefox launches, in the top-right corner of the browser you'll see an icon with the firefox logo. click the icon, and a new tab will open with http://www.mozilla.org/ loaded into it. that's all this add-on does. it uses two sdk modules: the action button module, which enables you to add buttons to the browser, and the tabs module, which enables you to perform basic operations with tabs. in this case, we've created a button whose icon is the firefox icon, and added a click handler that loads the mozilla home page in a new tab. try editing this file. for example, we ...
...n does. it uses two sdk modules: the action button module, which enables you to add buttons to the browser, and the tabs module, which enables you to perform basic operations with tabs. in this case, we've created a button whose icon is the firefox icon, and added a click handler that loads the mozilla home page in a new tab. try editing this file. ...
Getting started (cfx) - Archive of obsolete content
" directory: icon-16.png icon-32.png icon-64.png back at the command prompt, type: cfx run this is the sdk command to run a new instance of firefox with your add-on installed. when firefox launches, in the top-right corner of the browser you'll see an icon with the firefox logo. click the icon, and a new tab will open with https://www.mozilla.org/ loaded into it. that's all this add-on does. it uses two sdk modules: the action button module, which enables you to add buttons to the browser, and the tabs module, which enables you to perform basic operations with tabs. in this case, we've created a button whose icon is the firefox icon, and added a click handler that loads the mozilla home page in a new tab. try editing this file. for example, we ...
...n does. it uses two sdk modules: the action button module, which enables you to add buttons to the browser, and the tabs module, which enables you to perform basic operations with tabs. in this case, we've created a button whose icon is the firefox icon, and added a click handler that loads the mozilla home page in a new tab. try editing this file. ...
Tutorials - Archive of obsolete content
refox's main menus. display a popup display a popup dialog implemented with html and javascript. add a context menu item add items to firefox's context menu. interact with the browser open a web page open a web page in a new browser tab or window using the tabs module, and access its content. listen for page load use the tabs module to get notified when new web pages are loaded, and access their content. get the list of open tabs use the tabs module to iterate through the currently open tabs, and access their content. modify web pages modify web pages based on url create filters for web pages based on their url: whenever a web page whose url matches the filter is loaded, execute a specified script in it. modify the active web page dynamically...
...modules, so other add-on developers can use them too. unit testing writing and running unit tests using the sdk's test framework. chrome authority get access to the components object, enabling your add-on to load and use any xpcom object. creating event targets enable the objects you define to emit their own events. listen for load and unload get notifications when your add-on is loaded or unloaded by firefox, and pass arguments into your add-on from the command line. using third-party modules (jpm) install and use additional modules which don't ship with the sdk itself. localization writing localizable code. mobile development develop add-ons for firefox mobile on android. add-on debugger debug your add-on's javascript. putting it together annotator add-on ...
Miscellaneous - Archive of obsolete content
is defined at //github.com/realityripple/pale-moon/blob/master/palemoon/base/content/browser.js#l5113. note that it returns the empty string (""), not false, when nothing is selected. getbrowserselection() is not implemented on some platforms, such as thunderbird and songbird. see also http://mxr.mozilla.org/seamonkey/source/browser/base/content/browser.js#4674 discovering which element in the loaded document has focus // focusedcontrol stores the focused field, or null if there is none. // this excludes textareas for simplicity, but onpageload() can easily be // modified to cycle through textareas as well. further enhancements would include // handling for fields dynamically added to the page (e.g., by page javascript). var focusedcontrol; window.addeventlistener("load", function(e) { onw...
...am.readbytearray(stream.available()); var poststr = string.fromcharcode.apply(null, postbytes); //do anything to your poststr alert(poststr); getting a string from the input stream is made somewhat simpler in firefox 4, by the addition of netutil.readinputstreamtostring() getting postdata of a request before the request is sent the above code will get the postdata for a page that has already loaded. to see what the postdata looks like before the request is even sent, use the 'http-on-modify-request' observer topic: observerservice.addobserver(observer, 'http-on-modify-request', false); where "observer" is an object that has a method "observe": function observe(subject, topic, data) { subject.queryinterface(components.interfaces.nsiuploadchannel); postdata = subject.uploadstream; } h...
View Source for XUL Applications - Archive of obsolete content
ontaining the document that we would like to view the source of. this is optional if outerwindowid is not passed. outerwindowid (optional) the outerwindowid of the content window containing the document that we want to view the source of. pass this if you want to attempt to load the document source out of the network cache. linenumber (optional) the line number to focus on once the source has loaded. deprecated api this api is likely to go away in the future, and should no longer be used. the viewsource method will also accept the following arguments in place of the object: aurl a string url for the document to view the source of. apagedescriptor (optional) a "descriptor" that allows the source to be retrieved from the network cache. this is usually gotten from the nsiwebpagedes...
... ...
Displaying web content in an extension without security issues - Archive of obsolete content
s, ideally an extension that needs to display web content (which is always potentially dangerous) will use all of them. displaying untrusted data as content in firefox, there is a distinction between chrome and content documents. the top document in a window is always a chrome document. if you look at the frames it loads, those will usually be chrome documents as well. however, if the document is loaded into <iframe type="content"> or <browser type="content">, it will be considered a content document, and so will be all the frames it loads (the "type" attribute is ignored at that point). so if we look at the frame hierarchy there is a boundary between chrome and content, and at that boundary a number of security mechanisms apply. in particular, a content document can only go up in the frame hier...
...restricting what documents that contain untrusted data can do there are several restrictions that can be applied per frame. here it is most important to disable javascript and plugins. it won’t harm disabling everything else as well unless it is really required: frame.docshell.allowauth = false; frame.docshell.allowimages = false; frame.docshell.allowjavascript = false; frame.docshe...
Downloading JSON and JavaScript in extensions - Archive of obsolete content
this practice is dangerous and will not, in fact, pass an amo review. so the extension will not be allowed to move out of the amo sandbox. the practice is dangerous because the decoded javascript has full chrome privileges and could perform some nasty actions. ...
...() 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 the rest of the extension, and host application. sandboxing is done using compon...
Extension Packaging - Archive of obsolete content
extensions use a directory structure which can provide chrome, components, and other files to extend the functionality of an xul program. every extension must provide an install.rdf file, which contains metadata about the extension, such as its unique id, version, author, and compatibility information. ...
...sion for installation: zip the extension directory into a user-installable xpi (xpinstall) file, unpack the extension directly into the user's application or profile directory, or register the extension in the windows registry. note: starting in gecko 2.0, xpi files are no longer unpacked when extensions are installed. instead, the xpi itself is placed in the extensions directory, and files are loaded directly out of the package. making an extension xpi an xpi (xpinstall) file is simply a zip file, containing the extension files, with the install.rdf file at the root of the zip. users can download xpi files from a website, or from a local file, and install by opening it, or dragging it into the extension manager window. the xpi file must contain only uncompressed files, or files compressed ...
Extension Etiquette - Archive of obsolete content
xtensions manager. coding practices namespace conflicts there are many namespaces which extensions often must share with other consumers, be they other add-ons, web code, or the browser itself. these often include areas such as: object prototypes, such as string.prototype, which are often extended to add methods to native objects. global variables, such as top-level declarations on scripts loaded into shared windows or web pages. expando properties of shared objects, such as document objects, or dom nodes. ids and class names in html and xul documents, when extensions add elements to web pages or browser windows. chrome: or resource: packages, which are often defined in chrome.manifest files. about: page urls. xpcom contract ids, which are often registered in chrome.manifest files. ...
...t files. while these are among the most common examples of namespaces in which conflicts can occur, there are many others. in general, care must be taken whenever defining a name anywhere that other code might do likewise. strategies to avoid such conflicts include: avoid shared namespaces where possible many naming conflicts are best avoided by simply not sharing namespaces. scripts can be loaded into their own globals, such as commonjs modules, javascript modules, or sandboxes, to avoid most global variable and prototype conflicts. expando properties are best avoided using tools such as weakmaps. prefix names in shared namespaces when shared namespaces can't be avoided, the simplest solution to prevent conflicts is to use a distinct prefix for all of your names. class names for html ...
Install Manifests - Archive of obsolete content
form. translator the name(s) of translators. you may specify more than one of this value to specify multiple translators. ...
...application whether the extension requires its files be unpacked into a directory in order to work or whether the extension can be loaded direct from the xpi. in versions before gecko 2.0 all extensions were unpacked, in gecko 2.0 and later the default is to not unpack. if an extension includes the following then it must request unpacking: binary xpcom components plugins search plugins dlls loaded with ctypes dictionaries window icons examples <description about="urn:mozilla:install-manifest"> <em:id>extension@mysite.com</em:id> <em:unpack>true</em:unpack> ... </description> updatekey to ensure the security of update rdf data that is retrieved over plain http you must use a digital signature to verify the contents of the data. in order to do so you must include the publi...
Installing Extensions and Themes From Web Pages - Archive of obsolete content
onurl property specifies an icon to be displayed in the installation dialog. this property is optional. if you do not specify an icon, the default icon will be used, usually a green puzzle piece. the icon can be any image format supported by firefox, and should be 32x32 pixels in size. hash the hash property specifies a cryptographic hash of the xpi file contents. this is used to verify the downloaded file, to protect against a corrupted file being served by a mirror download server, for example. you can use any hash function supported by nsicryptohash. the hash is specified as hash function:hash value, for example, sha1:28857e60d043447c5f4550853f2d40770b326a13. tostring() the tostring() property should return the xpi url, for compatibility with firefox browsers older than version 1.0, and o...
...pdateenabled that some of you may be calling before you call installtrigger.install. this is not necessary as install calls updateenabled itself internally. furthermore, calling updateenabled may lead to problems if your distribution site is not in the user's whitelist, because firefox only displays the "installation blocked" message when install or installchrome are called, or when a xpi file is loaded. so, if you have code that looks like this: if (installtrigger.updateenabled()) installtrigger.install({"foo": "foo.xpi"}); ... and your site is not in the whitelist, when the user invokes that code, updateenabled will return false because your site isn't whitelisted, and since it was updateenabled that discovered this, not a call to install, there will be no notification to the user. thus ...
Adding Events and Commands - Archive of obsolete content
« previousnext » event handlers just like with html, most javascript code execution is triggered by event handlers attached to dom elements. the most commonly used event is the onload event, which is used in overlays and other windows to detect when the window has loaded and then run initialization code: // rest of overlay code goes here. window.addeventlistener( "load", function() { xulschoolchrome.browseroverlay.init(); }, false); you can do something similar with the onunload event, to do any cleanup you may need. please read appendix a for recommendations on how to use the load event to initialize your add-on without having a negative performance impact on firefox. another way to attach event handlers, just like html, is to place the handler in the xul code: <overlay id="xul...
...ful tool that you should know, even if it isn't that frequently used. the dom createevent function allows you to create custom events that you can dispatch and capture. custom events serve as a good communication mechanism, specially when dealing with a somewhat common problem: communication between window xul and web page content. it isn't hard for xul code to control the content on pages being loaded or displayed, as we will see later on, but it can be hard for your extension xul code to receive information from pages in a secure manner. this is because it would be very insecure to have a website js controlling the behavior of firefox and running javascript code with chrome privileges. suppose your extension interacts with pages from a website, and you want some actions on this site to trigg...
Appendix F: Monitoring DOM changes - Archive of obsolete content
ore recently via the history.pushstate method. the former triggers a hashchange event while the latter triggers a popstate event. event listeners for those events are the preferred method for detecting dom modifications when feasible. often times, this must be used in combination with a slight delay, or even polling, via settimeout, for cases where the url change happens before the page is fully loaded. this method works particularly well with services like google instant, and the gawker family of sites. network listeners ajax-based page changes are almost universally tied to xmlhttprequests. these requests can be tracked from chrome code using a variety of methods, including web progress listeners, http observers, and content policies. while these are not exceptionally efficient (they run f...
...d', listener, false); }; } } xbl xbl is similar in approach to the above animation-based method. bindings are attached to dom nodes via css and are given the opportunity to run code via their constructors when new matching dom nodes are created. while it is no longer possible for web sites to use xbl directly, chrome code can still attach xbl bindings to web content from stylesheets loaded via the stylesheet service. as it is currently possible to attach only a single binding to a given dom node at once, it is important when using this method to detach your binding from a node once your constructor has run. this is most easily done by adding a :not clause to the css selector that attaches your binding. for instance, when using the selector div:not([foo-binding-done]), you can deta...
Signing an XPI - Archive of obsolete content
you will need to apply for a code signing certificate and satisfy the issuer's identity verification procedures. they will then issue a signed certificate. when you receive the signed certificate it must be imported into the certificate database. your browser will generate a new private key and code signing request (csr) in the background without you necessarily realising it. the csr will be uploaded to the issuer. later, you must use the same browser when installing the new certificate because the key and certificate pair must be together. hint: when applying for a certificate ensure that the organisation (o) contains your name and not the issuer's default text, because this is what is displayed to users. for this guide i applied for a free certificate from unizeto certum. after completing...
... can view the details of your certificate in mozilla firefox and get this information from the issued by common name (unizeto certum's free certificate ca is certum level iii ca). download the root ca and any intermediate certificates used to sign your certificate from the issuer; their web site will have a link somewhere to their root cas and public certificates. (certum public key page). i downloaded the certum root ca and certum level iii ca digital id for web and ssl/tls servers, copied the text and saved them to the files c:\projects\codesigning\certum root ca.cer and c:\projects\codesigning\certum level iii ca.cer. open a command prompt (ensure the paths to the nss tools are set as described above) in the codesigning folder, install the issuer ca certificates, and check they have been ad...
Using Dependent Libraries In Extension Components - Archive of obsolete content
(&lib); if (ns_failed(rv)) return rv; nsgetmoduleproc getmoduleproc = (nsgetmoduleproc) pr_findfunctionsymbol(lib, ns_get_module_symbol); if (!getmoduleproc) return ns_error_failure; return getmoduleproc(acompmgr, alocation, aresult); } extensions/stub/bdsstubloader.cpp (for mac os x) the code as written above won't work for mac os x. dependant libraries on the mac must be loaded with a special system function nsaddimage() with the flag nsaddimage_option_match_filename_by_installname. the following are the necessary modifications you will need in order to write a stub loader for an os x extension. you will also need to make sure you are properly linking the xpcom glue libraries. see xpcom glue for the proper flags on how to link to the glue libraries. /* * os x stubl...
...pendencies 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 rv; const mach_header * componentlib = nsaddimage(path.get(), nsaddimage_option_return_on_error | nsaddimage_option_with_searching | nsaddimage_option_match_filename_by_installname); if (componentlib == null) return ns_error_unexpected; ...
Add-ons - Archive of obsolete content
for complex extensions, it may be necessary to create components in c++ that provide additional functionality. extension etiquette this article describes best practices when making extensions, including how to be kind to your users. it assumes that you are already familiar with building an extension. extension packaging extensions are packaged in a form of installable bundle which can be downloaded and installed by a user, or provided pre-packaged with an application or by an external program. extensions use a directory structure which can provide chrome, components, and other files to extend the functionality of an xul program. extensions support in seamonkey 2 starting with seamonkey 2 alpha 1 seamonkey supports toolkit/-style extensions. these type of extensions have many advantages fo...
...ted). hotfix extension this document has been moved to the add-ons wiki. how to convert an overlay extension to restartless first off, what kind of add-on are we talking about here? well, xul overlays and windows, jsm files, chrome & resource mappings with localization, default preferences, but no xpcom components of your own. some of that will have to be replaced and the rest will need to be loaded differently. inline options firefox 7 supports a new syntax for defining extensions' preferences for both bootstrapped and traditional extensions. the user interface for the preferences defined with this new syntax appears in the extension's detail view in the add-on manager. this functionality originally appeared in firefox mobile and is now available in firefox on the desktop as well. instal...
Adding preferences to an extension - Archive of obsolete content
cript code in order to monitor changes to our preferences, we need to install an observer using the nsiprefbranch2 interface. to do that, we need to reimplement our code into an object. that involves turning each function into a member of the stockwatcher class. let's take a look at each function in the class. startup() the stockwatcher.startup() function is called when our extension is first loaded. its job is to start up the observer to watch for changes to our preferences, instantiate an object to use to manage our preferences, and install an interval routine to update the stock information periodically. var stockwatcher = { prefs: null, tickersymbol: "", // initialize the extension startup: function() { // register to receive notifications of preference changes ...
...'t refer to the right object. see method binding for detailed explanation. once we have the symbol in the local variable symbol, we use that to construct the url and the string to display in the status bar panel. installing the event listeners the only thing left to do is to install the event listeners needed to run the startup() and shutdown() routines automatically when the browser window is loaded and unloaded. window.addeventlistener("load", function(e) { stockwatcher.startup(); }, false); window.addeventlistener("unload", function(e) { stockwatcher.shutdown(); }, false); design the preference dialog now that we've written all the code, we need to build the xul file for the options dialog. <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <prefwin...
Localizing an extension - Archive of obsolete content
odify the stockwatcher2.xul file to reference this property file. we do this by creating a string bundle, using the following code: <stringbundleset id="stringbundleset"> <stringbundle id="string-bundle" src="chrome://stockwatcher2/locale/stockwatcher2.properties"/> </stringbundleset> this establishes a new string bundle, referenced by the id "string-bundle", whose keys and values are to be loaded from the stockwatcher2.properties file we've already created. note: you should use a unique id for each string bundle element for each file you use to avoid conflicts. (e.g. id="myextensionname-filename") update the javascript code now we're ready to revise the javascript code to load the strings from the string bundle instead of using literal strings. this involves rewriting the refreshinforma...
...nique id for each string bundle element for each file you use to avoid conflicts. (e.g. id="myextensionname-filename") update the javascript code now we're ready to revise the javascript code to load the strings from the string bundle instead of using literal strings. this involves rewriting the refreshinformation() function to load the strings, and its enclosed inforeceived() function to use the loaded, localized, strings instead of string literals. we add to refreshinformation() the following code: var stringsbundle = document.getelementbyid("string-bundle"); var changestring = stringsbundle.getstring('changestring') + " "; var openstring = stringsbundle.getstring('openstring') + " "; var lowstring = stringsbundle.getstring('lowstring') + " "; var highstring = stringsbundle.getstring('hig...
Same-origin policy for file: URIs - Archive of obsolete content
8 or earlier, any two file: uris are considered to be same-origin. in other words, any html file on your local disk can read any other file on your local disk. starting in gecko 1.9, files are allowed to read only certain other files. specifically, a file can read another file only if the parent directory of the originating file is an ancestor directory of the target file. directories cannot be loaded this way, however. for example, if you have a file foo.html which accesses another file bar.html and you have navigated to it from the file index.html, the load will succeed only if bar.html is either in the same directory as index.html or in a directory contained within the same directory as index.html. this policy affects anything that does same-origin checks, including xmlhttprequest, xslt, an...
...avigated to it from the file index.html, the load will succeed only if bar.html is either in the same directory as index.html or in a directory contained within the same directory as index.html. this policy affects anything that does same-origin checks, including xmlhttprequest, xslt, and xbl. for cross-window dom access, each file is treated as a separate origin, with one exception: if a file is loaded from another file that would otherwise be able to load it following this same-origin policy, they are considered to have the same origin. this load can occur through a subframe, link, location set, call to window.open(), or the like. for example, if the file /home/user/foo.html is a frameset and one of the frames is /home/user/subdir/bar.html, the frame and frameset are considered to share the s...
Working with BFCache - Archive of obsolete content
) stays right where it is. it just has its inner window and document replaced. the inner nsidomwindow (the global scope object in content js) is either thrown away when gc happens, or frozen and placed in the bfcache. when the user hits the 'back' button, either the window in bfcache is thawed or a new inner window is created, depending on whether there's a window in the bfcache. q: is the page reloaded? loaded from cache? or is the dom saved in some way as if the window was there but invisible? are scripts recompiled? where do they live while the page was invisible? a: in the non-bfcache case, the page is reloaded in the sense of reparsing from the original html source. that might come from the http cache or not, depending on whether it's been evicted; typically it does come from the http cache...
...in the bfcache case, freezing the window just marks it as frozen; the dom is preserved, as are compiled script objects. thawing marks it as thawed. freezing suspends timeouts and interval timers on the frozen window, so they won't execute. ...
Downloading Nightly or Trunk Builds - Archive of obsolete content
ed by automatic tests and their main purpose is to check that nothing is horridly wrong with the latest change to the source: what they are doing is to constantly check that the current source can be built into an executable and that that executable passes a certain more-or-less fixed set of tests. nightly builds. the same machines produce about every 24 hours a "nightly" build which can be downloaded by anyone if you know where to get it: these are the nightly builds, and testers all over the world download them and test them, reporting as they go along on any bugs that hit them. anyone can be a tester, you don't need to get approval before you can start testing. when people talk of "nightlies", they often mean "trunk nightlies", though there exist also "branch nightlies" which are somewhat l...
...eated for every platform for every night. if one has questions about the way a particular nightly was built, the best way to get that information is to download the executable, launch it, and then go to the "about:buildconfig" page, by typing this into the location bar. this should provide all the build flags and configuration settings used for building this executable. nightly builds can be downloaded from https://archive.mozilla.org/pub/firefox/nightly/. if you need to download builds often, most builds can be downloaded semi-automatically and saved with a convenient name using mozdownload. ...
Simple Storage - Archive of obsolete content
rious standard javascript functions and operators. the jetpack.simple.storage object is automatically and periodically flushed to disk. how and when it is flushed is an implementation detail. jetpacks can flush it manually, however, by calling jetpack.storage.simple.sync(). the object can also be forced to reload its data from disk by calling jetpack.storage.simple.open(), although the data comes loaded automatically. don't abuse these methods, since they cause firefox -- all of firefox -- to drop what it's doing to make a trip to the disk. if you call them too often, firefox may become unresponsive for some of your users. unless you are doing something strange, let jetpack flush your data for you. the namespace currently lives in the future and must be imported before it is used: jetpack.future...
...in the future and must be imported before it is used: jetpack.future.import("storage.simple"); methods sync()as described above, the jetpack.storage.simple object is automatically written to disk, but a feature may force flush by calling jetpack.storage.simple.sync(). don't abuse this method. open()as described above, the jetpack.storage.simple object is automatically populated when a feature is loaded, but a feature may force the object to read from disk by calling jetpack.storage.simple.open(). don't abuse this method. examples this code persistently stores some data: jetpack.future.import("storage.simple");var mystorage = jetpack.storage.simple;mystorage.fribblefrops = [1, 3, 3, 7];mystorage.heimelfarbs = { bar: "baz" }; and this code -- pretend it's in the same jetpack as the code above -- ...
Tabs - Archive of obsolete content
Archive › Mozilla › Jetpack › UI › Tabs
cusedstringtostringstringpopstringpushstringreversestringshiftstringsortstringsplicestringunshiftstring)this is some default text lengththe number of open tabsstring focusedthe current tab in your browserstring tostringstuffstring popstuffstring pushstuffstring reversestuffstring shiftstuffstring sortstuffstring splicestuffstring unshiftstuffstring onready()when the inherited document is fully loaded. onfocus()changing the focus of a tab. methods open(urlstring)opens a new tab in your browser with a defined url. urlurl to be openedstring jetpack.tabs.open("http://www.example.com/"); blah(lengthstringfocusedstringtostringstringpopstringpushstringreversestringshiftstringsortstringsplicestringunshiftstring)this is some default text lengththe number of open tabsstring focusedthe current tab i...
...onfocus()changing the focus of a tab. ...
Simple Storage - Archive of obsolete content
rious standard javascript functions and operators. the jetpack.simple.storage object is automatically and periodically flushed to disk. how and when it is flushed is an implementation detail. jetpacks can flush it manually, however, by calling jetpack.storage.simple.sync(). the object can also be forced to reload its data from disk by calling jetpack.storage.simple.open(), although the data comes loaded automatically. don't abuse these methods, since they cause firefox -- all of firefox -- to drop what it's doing to make a trip to the disk. if you call them too often, firefox may become unresponsive for some of your users. unless you are doing something strange, let jetpack flush your data for you. the namespace currently lives in the future and must be imported before it is used: jetpack.future...
...in the future and must be imported before it is used: jetpack.future.import("storage.simple"); methods sync()as described above, the jetpack.storage.simple object is automatically written to disk, but a feature may force flush by calling jetpack.storage.simple.sync(). don't abuse this method. open()as described above, the jetpack.storage.simple object is automatically populated when a feature is loaded, but a feature may force the object to read from disk by calling jetpack.storage.simple.open(). don't abuse this method. examples this code persistently stores some data: jetpack.future.import("storage.simple"); var mystorage = jetpack.storage.simple; mystorage.fribblefrops = [1, 3, 3, 7]; mystorage.heimelfarbs = { bar: "baz" }; and this code -- pretend it's in the same jetpack as the code above...
Migrate apps from Internet Explorer to Mozilla - Archive of obsolete content
ronous or not. if the call is asynchronous, then give the onload member a function reference, which is called once the request has completed. synchronous request: var myxmlhttprequest = new xmlhttprequest(); myxmlhttprequest.open("get", "data.xml", false); myxmlhttprequest.send(null); var myxmldocument = myxmlhttprequest.responsexml; asynchronous request: var myxmlhttprequest; function xmlloaded() { var myxmldocument = myxmlhttprequest.responsexml; } function loadxml(){ myxmlhttprequest = new xmlhttprequest(); myxmlhttprequest.open("get", "data.xml", true); myxmlhttprequest.onload = xmlloaded; myxmlhttprequest.send(null); } table 7 features a list of available methods and properties for mozilla's xmlhttprequest. table 7. xmlhttprequest methods and properties name ...
...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. domdocument responsexml dom document containing the response. void...
Running Tamarin acceptance tests - Archive of obsolete content
nment 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/test/acceptance $ export asc=/users/build/hg/tamarin-red...
...nning 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' stands for android debug bridge. adb is used to access yo...
Running Tamarin performance tests - Archive of obsolete content
able to the path of the builtin.abc. (in the tamarin-redux/generated directory) set the shellabc environment variable to the path of the shell_toplevel.abc. (in tamarin-redux/generated directory) set the asc environment variable to the path of the asc.jar compiler. you may download the latest asc.jar 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. (optional) you may compare the performance of the avmshell to another avmshell. for example you may download or build the latest checked in avmshell to compare against a local change. to compare a build against another build set the avm2 environment variable to the other avmshell or use the "-s --avm2" options. results from t...
...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' stands for android debug bridge. adb is used to access your a...
XPJS Components Proposal - Archive of obsolete content
e will ask the component manager to create an object instance for some clsid (or progid). the component manager will load up the xpjsmanager's module and call the native nsgetfactory it finds there. that native nsgetfactory function will check the information it stored in the registry to see that the js factory for the given clsid is in a given .js file. it will load that .js file (if not already loaded) and call the nsgetfactory function. our friend xpconnect will convert the js object returned from the js module's nsgetfactory function into an xpcom object. the component manager (and anyone else with a reference to that factory) can then call the factory's createinstance method at will. the js module is free to implement factories and components and services that the factories construct on c...
...ule is free to implement factories and components and services that the factories construct on command. any code anywhere and implemented in any language can get to these things via the component and service managers. the xpjsmanager is loosely in charge of the lifetime of each xpjs module. javascript is garbage collected and one can not force an object to be deleted or the compiled code to be unloaded [except by deleting the jsruntime; i.e. erasing the entire js universe]. in c if a module gets unloaded when there are still references to objects created by the module then a crash is likely to happen soon after. js does not have this problem. if the xpjsmanager is asked to trim itself back (by whatever means) it will call the nscanunload method (if present) on each module. it the module oks it ...
validate - Archive of obsolete content
...
...e of the values below this attribute indicates whether to load the image from the cache or not. this would be useful if the images are stored remotely or you plan on swapping the image frequently. the following values are accepted, or leave out the attribute entirely for default handling: always the image is always checked to see whether it should be reloaded. never the image will be loaded from the cache if possible. ...
Introduction to XUL - Archive of obsolete content
in fact, most of mozilla's windows (and dialogs) will be described using this mechanism. ...
...acement of widgets, their interactions with each other, and optionally some of their configuration, will be controlled by a ui layout specified in a script whose structure is defined in this and related documents. widgets are pieces of the application largely self-contained, generally corresponding to a rectangle of window real estate. widgets will generally live grouped in separate, dynamically loaded libraries. a widget may expect to own a piece of a window (a toolbar or toolbar set), or it may be expected to work within or without a window (menubars, depending on the platform). it may not be a part of the application ui at all. widgets will have predefined behaviour, set at compilation. buttons will respond to the mouse; toolbars will act as containers for buttons. the effect a widget will ...
RDF Modifications - Archive of obsolete content
ts/1.1/description"); var target = rdf.getliteral("one of the thirty or so egyptian obelisks"); datasource.assert(source, predicate, target, true); the assert call adds a new triple to the rdf datasource. when this happens, any templates observing the datasource will be notified via the rdf observer's onassert method. the second situation when notifications are made is when a datasource is being loaded or reloaded. actually, internally, 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 ...
...ples intact, and only modifies the datasource based on what has changed. when parsing, any triples that already exist are not added again. if a triple does not exist yet, it will be added. any triples that don't exist in the new data but were there before are removed. this means that the observer will be called only for the triples that differ between the new and old version of the data. if the reloaded datasource hasn't changed, the builder won't receive any notifications. this saves a lot of extra work. the rdf observer also has two methods onbeginupdatebatch and onendupdatebatch. these are called when performing a lot of operations on a datasource. when changing the datasource, the changes are surrounded by begin and end batch calls. then, rather than notify on every change, the datasource wi...
Template Logging - Archive of obsolete content
d. remember to use the logging flag as described above to see whether any results are being generated. unfortunately, detecting network or parsing errors with the data itself can be difficult. naturally, semantic errors in the data in the datasource can't be easily detected automatically. ...
...ny results are being generated. unfortunately, detecting network or parsing errors with the data itself can be difficult. naturally, semantic errors in the data in the datasource can't be easily detected automatically. however, for xml datasources, you can at least check the builder's datasource to see whether the xml data was loaded and parsed correctly. if null, then the datasource could not be loaded, or hasn't yet been loaded. if the datasource load and parsing was successful, the datasource will be set to the xml document. for example: if (root.builder.datasource instanceof xmldocument) alert("xml datasource loaded ok"); be careful, as the datasource will only be set once the document has finished loading and has been parsed, so don't check this property too early. you may also get an er...
Adding Methods to XBL-defined Elements - Archive of obsolete content
tion to adding script properties to the xbl-defined element, you can also add methods. these methods can be called from a script. methods are the functions of objects, such as window interface's open() method loads the specified resource into the browsing context (window, <iframe> or tab) with the specified name. if the name doesn't exist, then a new window is opened and the specified resource is loaded into its browsing context.">window.open(). you can define custom methods for your elements using the method element. the general syntax of methods is as follows: <implementation> <method name="method-name"> <parameter name="parameter-name1"/> <parameter name="parameter-name2"/> . . . <body> <-- method script goes here --> </body> </method> </implementation> ...
... 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 relied upon, as they are loaded from various files. the window's onload handler is not called until after all the bindings have been attached and their constructors finished. the second point is when a binding is attached by changing the -moz-binding style property of an element. the existing binding will be removed, after its destructor is called. then, the new binding will be added in its place and its constructor invoked. t...
Creating an Installer - Archive of obsolete content
plugin as an extension. « previousnext » this section will describe packaging a xul application into an installer. xpinstall packages mozilla provides a mechanism which can be used to package xul windows, scripts, skins and other files into single file installers. you can place this installer file somewhere for users to download. a simple script can be used to have the package downloaded and installed. this mechanism is called xpinstall (cross platform install). xpinstall installers are packaged into jar files. inside the jar file, you can add all the various files that you want to have installed. in addition, installers should contain an install script (a file named install.js) which can be used to script the installation process. this script has access to various install funct...
...will contain an install trigger which is a small piece of script which launches the install. the user is presented with a dialog which indicates the package being installed. it is possible for the install trigger to launch multiple installers. in this case, they will be presented in a list. the user may choose to continue or cancel. if the user chooses to continue, the installer xpi file is downloaded. a progress bar is displayed to the user during this process. the file install.js is extracted from the install archive and executed. this script will call install functions which will indicate which files from the archive should be installed. once the script is complete, the new package has been installed. if multiple packages are being installed, their scripts will run in sequence. install ...
Document Object Model - Archive of obsolete content
« previousnext » the document object model (dom) can be used with xul elements to get information about them or modify them. dom introduction the document object model (dom) is used to store the tree of xul nodes. when an xul file is loaded, the tags are parsed and converted into a hierarchical document structure of nodes, one for each tag and block of text. the dom structure may be examined and modified using various methods provided for this purpose. specific xul elements also provide additional functions which may be used. each xul file that is loaded will have its own document displayed in a window or frame. although there is only ever one document associated with a window at a time, you may load additional documents using various methods. in mozilla, the dom may be acc...
...trieve the opener window and call the gettext() function declared in a script used there. note that we qualified the property with the 'window' identifier just to be clearer. the window's open() method also returns a reference to the new window so you can call functions of the new window from the opener. it is important to note, however, that the open() method returns before the window has fully loaded, so functions will not typically be available yet. the window object isn't defined by any dom specification, but in mozilla is sometimes considered part of dom level 0, a name used by some developers to refer to the dom-like functions before they were added to specifications. the actual document displayed in a window can be retrieved using the window's document property. since it is one of the m...
Features of a Window - Archive of obsolete content
second window for your application in the same manner as you would create the first one. just create a second xul file with the window code in it. as in html, you can use the window interface's open() method loads the specified resource into the browsing context (window, <iframe> or tab) with the specified name. if the name doesn't exist, then a new window is opened and the specified resource is loaded into its browsing context.">window.open() function to open the second window. this function will return a reference to the newly opened window. you can use this reference to call functions of the other window. the open function takes three arguments. the first is the url of the file you wish to open. the second is an internal name of the window. the third is a list of display flags. the flag 'ch...
... the dialog is modal. the window that opened the modal window can't be interacted with until the modal window is closed. resizable the user can resize the window. see also window interface's open() method loads the specified resource into the browsing context (window, <iframe> or tab) with the specified name. if the name doesn't exist, then a new window is opened and the specified resource is loaded into its browsing context.">window.open() next, we'll look at how to open secondary dialogs. « previousnext » ...
Using Remote XUL - Archive of obsolete content
sipermissionmanager.allow_action); xul (pronounced like "zool"), which is short for xml-based user interface language, is an xml-based language for describing application interfaces. it contains elements for all common ui widgets (menus, buttons, toolbars, etc.) and many sophisticated ones (trees, browsers, color pickers). ...
...based user interface language, is an xml-based language for describing application interfaces. it contains elements for all common ui widgets (menus, buttons, toolbars, etc.) and many sophisticated ones (trees, browsers, color pickers). xul is often used by desktop applications like mozilla but can also be loaded from a web server and rendered inside the content pane of a compatible browser. xul loaded and rendered in this way is called remote xul and can be used for basic functions like web site navigation as well as to build sophisticated web-based applications. [***aw: we should have a screenshot here of a xul document loaded in a content window***] this tutorial walks you through the process of building xul-based navigation for the mozilla.org web site. after completing the tutorial you s...
The Implementation of the Application Object Model - Archive of obsolete content
to the file, and then the user would pick them up. however, in order for this to work, the local bookmarks have to be merged in with the remote bookmarks specified by the site. the second reason to have local/remote merging is to save state and/or to record customizations that the user has made to his or her user interface. imagine a remote file that describes the user's personal toolbar. the downloaded file contains an aol instant messenger button, and the user really doesn't want that on the toolbar. now since the aol bookmark was specified by the remote file, the user has no way of going off to the site and changing that file just to get rid of the button (even though the user might wish that he or she could!). what the user needs to be able to do is make a local annotation to the remote file...
...user has no way of going off to the site and changing that file just to get rid of the button (even though the user might wish that he or she could!). what the user needs to be able to do is make a local annotation to the remote file, e.g., to save somewhere on the local hard drive the fact that the aol instant messenger button shouldn't be on the toolbar. when the remote file is subsequently downloaded, these local annotations are sucked in and superimposed on top of the structure described by the file. the resulting structure is what the user actually ends up viewing. forget xul! let's just use serialized rdf! well, that's just plain cool! i say forget xul! let's just use serialized rdf to represent the ui! that would be an unwise decision for a variety of reasons. rdf is a graph structur...
tab - Archive of obsolete content
Archive › Mozilla › XUL › tab
this attribute is set to true if the tab is currently in the process of being restored by the session store service. once the tab is restored, this attribute is removed. you can determine if a tab is being restored by checking to see if hasattribute("pending") is true. if the user has turned on the "don't load tabs until selected" preference, the pending attribute is set on tabs until they get loaded. pinned type: boolean this attribute is set to true if the tab has been pinned (that is, if it's an app tab). the tabbrowser element's pintab and unpintab methods handle pinning and unpinning tabs. selected type: boolean this attribute is set to true if the tab is selected by default. tabindex type: integer the tab order of the element. the tab order is the order in whic...
... unread. validate type: one of the values below this attribute indicates whether to load the image from the cache or not. this would be useful if the images are stored remotely or you plan on swapping the image frequently. the following values are accepted, or leave out the attribute entirely for default handling: always the image is always checked to see whether it should be reloaded. never the image will be loaded from the cache if possible. properties accesskey type: character gets and sets the value of the accesskey attribute. accessibletype type: integer a value indicating the type of accessibility object for the element. command type: element id gets and sets the value of the command attribute. cont...
Using LDAP XPCOM with XULRunner - Archive of obsolete content
t directory of the build package: on windows: nsldap32v50.dll nsldappr32v50.dll on linux: libldap50.so libprldap50.so those are the native ldap library. if you copy as usual those files in the components directory of your xul app, this can't work. actually, the ldap interfaces are available (for exemple, components.interfaces.nsildapconnection is not null), but the components can't be loaded (for example, components.classes["@mozilla.org/network/ldap-connection;1"] is null). this is due to the fact that the native ldap library files are not found by the xulrunner process. the solution is to use the bsmedberg stub, described in using dependent libraries in extension components: the component library is just a loader of the real library and all its dependencies, so as all the needed li...
...e, components.classes["@mozilla.org/network/ldap-connection;1"] is null). this is due to the fact that the native ldap library files are not found by the xulrunner process. the solution is to use the bsmedberg stub, described in using dependent libraries in extension components: the component library is just a loader of the real library and all its dependencies, so as all the needed libraries are loaded. create a subdirectory extensions/ldapstub in the mozilla source code directory, containing two files, makefile.in and ldapstubloader.cpp: makefile.in: # copyright (c) 2005 benjamin smedberg <benjamin@smedbergs.us> depth = ../.. srcdir = @srcdir@ topsrcdir = @top_srcdir@ vpath = @srcdir@ include $(depth)/config/autoconf.mk module = mozldapstub library_name = mozldap_stub is_component = 1 force...
Archived Mozilla and build documentation - Archive of obsolete content
information on creating extension in earlier browsers. creating a hybrid cd creating a microsummary a microsummary generator is a set of instructions for creating a microsummary from the content of a page. web pages can reference generators via <link rel="microsummary"> elements in their <head> elements. generators can also be independently downloaded and installed by users if they include a list of pages to which they apply. creating a mozilla extension a mozilla extension is an installable enhancement to the mozilla browser that provides additional functionality (for example linky, which adds an item to the context menu for opening multiple links in a document or selection). this tutorial walks you...
... xtech 2006 presentations xul explorer xul explorer is a xulrunner application that provides an easy way to experiment with xul. it’s a simple editor that can preview xul inline or in a separate popup window. it has a list of code snippets (small fragments of xul or javascript) that can be quickly inserted into the editor. the xul can be loaded from and saved to files. a xul validator and the error console are both available to help debug problems. the help menu provides access to xul information on mdc. there is even simple “keyword” help lookup for xul elements. xulrunner xulrunner is a mozilla runtime package that can be used to bootstrap xul+xpcom applications that are as rich as firef...
NPN_PostURL - Archive of obsolete content
d after use. data in buffer cannot be posted for a protocol that requires a header. file a boolean value that specifies whether to post a file. values: true: post the file whose path is specified in buf, then delete the file. false: post the raw data in buf. returns if successful, the function returns nperr_no_error. if unsuccessful, the plug-in is not loaded and the function returns an error code. for possible values, see error codes. description npn_posturl works similarly to npn_geturl, but in reverse. npn_geturl reads data from the url and either displays it in the target window or delivers it to the plug-in. npn_posturl writes data from a file or buffer to the url and either displays the server's response in the target window or delivers it...
... use npn_posturl to send data to the server, you can handle the response in several different ways by specifying different target parameters. if target is null, the server response is sent back to the plug-in. you can get the data and save it in a file or use it in a program. if you specify _current, _self, or _top, the response data is written to the same plug-in window and the plug-in is unloaded. if you specify _new or _blank, the response data is written to a new browser window. you can also write the response data to a frame by specifying the frame name as the target parameter. for http urls only, the browser resolves this method as the http server method post, which transmits data to the server. the data to post can be contained either in a local temporary file or a new memory buff...
NPN_SetValue - Archive of obsolete content
rameter and false for the value parameter. to specify a transparent mode, the value parameter should be set to true. nppvjavascriptpushcallerbool sets whether you are pushing or popping the appropriate jscontext off the stack (see the two-way scriptability article on the mozilla plugins project page for more details). nppvpluginkeeplibraryinmemory specifies that the plugin does not want to be unloaded from memory after the page which initiated it has gone. normally, when the browser navigates away from the page containing the plugin, all plugin instances get an npp_destroy call, and if there are no more instances of the plugin active, the plugin calls its np_shutdown method and the plugin dll gets unloaded from memory. if this is not desired, the plugin can instruct the browser not to unload t...
... remarks all four variable values are boolean. although the function prototype has type of value void *, the actual boolean should be placed there, not a pointer to a boolean. ...
Table Reflow Internals - Archive of obsolete content
the container posts a dirty reflow command with itself as the target. ...
...the container posts a dirty reflow command with itself as the target. ...
Building a Theme - Archive of obsolete content
tor rule to select this class. open up the file chrome/browser/browser.css in your theme. search this file for the #navigator-toolbox selector, and add a background: orange; rule to it. save the file. chrome uris next, we have to tell firefox where to find the theme files for your theme. css, xul, and other files are part of "chrome packages" - bundles of user interface components which are loaded via chrome:// uris. rather than load the browser from disk using a file:// uri (since the location of firefox on the system can change from platform to platform and system to system), mozilla developers came up with a solution for creating uris to content that the installed add-on knows about. the browser window is: chrome://browser/content/browser.xul. try typing this url into the location bar ...
...er versions available to users of your existing versions when you upload them. in addition, mozilla add-ons allows users to comment and provide feedback on your theme. it is highly recommended that you use mozilla add-ons to distribute your themes! visit https://addons.mozilla.org/developers/ to create an account and begin distributing your themes! note: your theme will be passed faster and downloaded more if you have a good description and some screenshots of the theme in action. themes ______________________________ ...
Back to the Server: Server-Side JavaScript On The Rise - Archive of obsolete content
h some basic java knowledge, you can extend javascript to include some of the most desired capability such as database access, remote web requests, and xml processing. we’ll start by taking a look at querying a sql database. this first example we’ll demonstrate is querying a mysql database for some employee contact information. it is assumed that you have already downloaded, extracted, and consumed the necessary documentation to get up and running with some basic rhino scripts. if you don’t already have it, you’ll need to also download the jdbc driver for mysql, extract the class files, and include the path in your classpath environment variable. the code in listing 1 is a sample javascript script which incorporates java classes to handle the database query. ...
...lumnname( i ) + ": " + rs.getobject( i ) + "\n" ); } print( "----------\n" ); } // cleanup rs.close(); stmt.close(); conn.close(); this code starts off by using a rhino function named importpackage which is just like using the import statement in java. here, we’re including all the classes in the java.sql namespace in the script. the appropriate database driver for mysql is loaded and the connection string to a database named rhino on my local machine is configured using the user account urhino with the password of prhino. the sql statement is prepared, executed, and printed with the help of the metadata obtained from the resultset. sample output is shown in listing 2. id: 1 first_name: sammy last_name: hamm department: it title: network administrator ---------- id: 2 fir...
Displaying a graphic with audio samples - Archive of obsolete content
controls="true" style="width: 512px;"> </audio> <div><canvas id="fft" width="512" height="200"></canvas></div> <img id="mozlogo" style="display:none" src="mozilla2.png"></img> <script> var canvas = document.getelementbyid('fft'), ctx = canvas.getcontext('2d'), channels, rate, framebufferlength, fft; function loadedmetadata() { channels = audio.mozchannels; rate = audio.mozsamplerate; framebufferlength = audio.mozframebufferlength; fft = new fft(framebufferlength / channels, rate); } function audioavailable(event) { var fb = event.framebuffer, t = event.time, /* unused, but it's there */ signal = new ...
... // draw rectangle bars for each frequency bin ctx.fillrect(i * 4, canvas.height, 3, -magnitude); } ctx.drawimage(document.getelementbyid('mozlogo'),0,0, canvas.width, canvas.height); } var audio = document.getelementbyid('audio-element'); audio.addeventlistener('mozaudioavailable', audioavailable, false); audio.addeventlistener('loadedmetadata', loadedmetadata, false); </script> </body> </html> ...
Buttons - Game development
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 the button to the game adding the new button to the game is done by using the add.b...
...ariable and make the paddle movable only when the game has started. to do that, adjust the update() function like so: function update() { game.physics.arcade.collide(ball, paddle, ballhitpaddle); game.physics.arcade.collide(ball, bricks, ballhitbrick); if(playing) { paddle.x = game.input.x || game.world.width*0.5; } } that way the paddle is immovable after everything is loaded and prepared, but before the start of the actual game. compare your code you can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: next steps the last thing we will do in this article series is make the gameplay even more interesting by adding some randomization to the way the ball bounces off the paddle. « previousnex...
Visual typescript game engine - Game development
b app without any networking then setup: appusenetwork: boolean = false; you want to use communication for multiplayer but you don't want to use server database account sessions. the setup this on false in main client config class. appuseaccountssystem: boolean = false; networking is disabled by default. find configuration at ./src/lib/client-config.ts /** * addson * all addson are ansync loaded scripts. * - cache is based on webworkers. * - hackertimer is for better performace also based on webworkers. * - dragging is script for dragging dom elements. */ private addson: addson = [ { name: "cache", enabled: true, scriptpath: "externals/cacheinit.ts", }, { name: "hackertimer", enabled: true, scriptpath: "externals/hack-timer.js", },...
...on 'src/**/*.ts' --fix tslint -c tslint.json 'src/**/*.ts' the external licence in this project : - networking based on : muaz khan mit license www.webrtc-experiment.com/licence - base physics based on : original source: matter.js https://github.com/liabru/matter-js matter.ts used because typescript orientation. https://www.npmjs.com/package/@types/matter-js crypto icons downloaded from https://www.behance.net/junikstudio todo list for 2019 i'm still far away from the project objective : make visual nodes for editor mode in gameplay. item's selling for crypto values. create examples demos in minimum 20 gameplay variants (table games, actions, platformers, basic demo throw the api doc etc.). implementing ar and webgl2. live demo platformer ...
Plug-in Development Overview - Gecko Plugin API Reference
atform-specific discovery and registration: ms windows unix mac os x ms windows on windows, plug-ins are found according to the section how gecko finds plug-ins. to determine the mime types and file extensions that the plug-in handles, the browser normally uses the content of the registry entries for the plug-in described below in installation using the registry. but when the plug-in is loaded from a well-known directory, a different method must be used. in this case to ensure the plug-in file will be loaded, it should have a name in the form of "np*.dll". also, the windows version information for the plug-in dll will be used to determines the mime types, file extensions, file open template, plug-in name, and description. for this the version stamp of the embedded resource of the plug...
... the resource code for this language and character set combination is 040904e4. unix on unix, plug-ins are found according to the section how gecko finds plug-ins. to determine the mime types and file extensions that the plug-in handles, the browser...
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 supporte...
...ly 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 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 ...
Prefetch - MDN Web Docs Glossary: Definitions of Web-related terms
dns prefetching domain lookups can be slow, especially with network latency on mobile phones. they are most relevant when there are a plethora of links to external websites that 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. ...
...h 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 <link> tag directs it to, giving the developer control over what resources should be prefetched. <link rel="prefetch" href="https://www.example.com/solutions" /> ...
Practical positioning examples - Learn web development
e running live at info-box.html (source code). check it out to get an idea of what you will be building in this section of the article. you might be thinking "why not just create the separate tabs as separate webpages, and just have the tabs clicking through to the separate pages to create the effect?" this code would be simpler, yes, but then each separate "page" view would actually be a newly-loaded webpage, which would make it harder to save information across views, and integrate this feature into a larger ui design. in addition, so-called "single page apps" are becoming very popular — especially for mobile web uis — because having everything served as a single file cuts down on the number of http requests required to view all the content, thereby improving performance. note: some we...
...integrate this feature into a larger ui design. in addition, so-called "single page apps" are becoming very popular — especially for mobile web uis — because having everything served as a single file cuts down on the number of http requests required to view all the content, thereby improving performance. note: some web developers take things even further, only having one page of information loaded at once, and dynamically changing the information shown using a javascript feature such as xmlhttprequest. at this point in your learning however we want to keep things as simple as possible. there is some javascript later on, but only a tiny bit. to start with, we'd like you to make a local copy of the starting html file — info-box-start.html. save this somewhere sensible on your local compu...
Web fonts - Learn web development
you can use the font stack to specify preferable fonts, followed by web-safe alternatives, followed by the default system font, but this adds overhead in terms of testing to make sure that your designs look ok with each font, etc. web fonts but there is an alternative, which works very well, right back to ie version 6. web fonts are a css feature that allows you to specify font files to be downloaded along with your website as it is accessed, meaning that any browser that supports web fonts can have exactly the fonts you specify available to it. amazing! the syntax required looks something like this: first of all, you have a @font-face block at the start of the css, which specifies the font file(s) to download: @font-face { font-family: "myfont"; src: url("myfont.woff"); } below this y...
...t and font-style to keep your css 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 fo...
What are browser developer tools? - Learn web development
this article explains how to use the basic functions of your browser's devtools. note: before you run through the examples below, open the beginner's example site that we built during the getting started with the web article series. you should have this open as you follow the steps below. ...
...dditemclick function. find out more find more out about the javascript debugger in different browsers: firefox javascript debugger microsoft edge debugger chrome debugger safari debugger the javascript console the javascript console is an incredibly useful tool for debugging javascript that isn't working as expected. it allows you to run lines of javascript against the page currently loaded in the browser, and reports the errors encountered as the browser tries to execute your code. to access the console in any browser: if the developer tools are already open, click or press the console tab. if not, firefox allows you to open the console directly using ctrl + shift + k or using the menu command: menu ➤ web developer ➤ web console, or tools ➤ web developer ➤ web console. o...
Sending form data - Learn web development
thod attribute to post because file content can't be put inside url parameters. set the value of enctype to multipart/form-data because the data will be split into multiple parts, one for each file plus one for the text data included in the form body (if text is also entered into the form). include one or more <input type="file"> controls to allow your users to select the file(s) that will be uploaded. for example: <form method="post" action="https://www.foo.com" enctype="multipart/form-data"> <div> <label for="file">choose a file</label> <input type="file" id="file" name="myfile"> </div> <div> <button>send the file</button> </div> </form> note: servers can be configured with a size limit for files and http requests in order to prevent abuse. security issues each ti...
...ters. the specific characters you should be cautious with vary depending on the context in which the data is used and the server platform you employ, but all server-side languages have functions for this. things to watch out for are character sequences that look like executable code (such as javascript or sql commands). limit the incoming amount of data to allow only what's necessary. sandbox uploaded files. store them on a different server and allow access to the file only through a different subdomain or even better through a completely different domain. you should avoid many/most problems if you follow these three rules, but it's always a good idea to get a security review performed by a competent third party. don't assume that you've seen all the possible problems. summary as we'd allu...
UI pseudo-classes - Learn web development
ted 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. ...
...hat the default option was, and style the radio buttons when indeterminate. both of these have the following html structure for the inputs: <p> <input type="radio" name="fruit" value="cherry" id="cherry"> <label for="cherry">cherry</label> <span></span> </p> for the :default example, we've added the checked attribute to the middle radio button input, so it will be selected by default when loaded. we then style this with the following css: input ~ span { position: relative; } input:default ~ span::after { font-size: 0.7rem; position: absolute; content: "default"; color: white; background-color: black; padding: 5px 10px; right: -65px; top: -3px; } this provides a little "default" label on the one the was originally selected when the page loaded. note here we are using ...
JavaScript basics - Learn web development
= 'hello world!'; make sure the html and javascript files are saved. then load index.html in your browser. you should see something like this: note: the reason the instructions (above) place the <script> element near the bottom of the html file is that the browser reads code in the order it appears in the file. if the javascript loads first and it is supposed to affect the html that hasn't loaded yet, there could be problems. placing javascript near the bottom of an html page is one way to accommodate this dependency. to learn more about alternative 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 variabl...
...nclick event handler property equal to a function with no name (an "anonymous" function). so every time this element is clicked: the code retrieves the value of the image's src attribute. the code uses a conditional to check if the src value is equal to the path of the original image: if it is, the code changes the src value to the path of the second image, forcing the other image to be loaded inside the <img> element. if it isn't (meaning it must already have changed), the src value swaps back to the original image path, to the original state. adding a personalized welcome message next, let's change the page title to a personalized welcome message when the user first visits the site. this welcome message will persist. should the user leave the site and return later, we will...
Adding vector graphics to the Web - Learn web development
quilateral.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 for browsers that don't support svg (ie 8 an...
... by wrapping it in an <a> element. cons this method is only suitable if you're using the svg in only one place. duplication makes for resource-intensive maintenance. extra svg code increases the size of your html file. the browser cannot cache inline svg as it would cache regular image assets, so pages that include the image will not load faster after the first page containing the image is loaded. you may include fallback in a <foreignobject> element, but browsers that support svg still download any fallback images. you need to weigh whether the extra overhead is really worthwhile, just to support obsolescent browsers. how to embed an svg with an <iframe> you can open svg images in your browser just like webpages. so embedding an svg document with an <iframe> is done just like we s...
Introduction to web APIs - Learn web development
ce. as a real-world example, think about the electricity supply in your house, apartment, or other dwellings. if you want to use an appliance in your house, you simply plug it into a plug socket and it works. you don't try to wire it directly into the power supply — to do so would be really inefficient and, if you are not an electrician, difficult and dangerous to attempt. image source: overloaded plug socket by the clear communication people, on flickr. in the same way, if you want to say, program some 3d graphics, it is a lot easier to do it using an api written in a higher-level language such as javascript or python, rather than try to directly write low level code (say c or c++) that directly controls the computer's gpu or other graphics functions. note: see also the api glossary en...
...s code. what can apis do? there are a huge number of apis available in modern browsers that allow you to do a wide variety of things in your code. you can see this by taking a look at the mdn apis index page. common browser apis in particular, the most common categories of browser apis you'll use (and which we'll cover in this module in greater detail) are: apis for manipulating documents loaded into the browser. the most obvious example is the dom (document object model) api, which allows you to manipulate html and css — creating, removing and changing html, dynamically applying new styles to your page, etc. every time you see a popup window appear on a page or some new content displayed, for example, that's the dom in action. find out more about these types of api in manipulating doc...
Video and Audio APIs - Learn web development
s available to both <audio> and <video> elements, as the features you'll want to implement are nearly identical. let's go through an example, adding features as we go. our finished example will look (and function) something like the following: getting started to get started with this example, download our media-player-start.zip and unzip it into a new directory on your hard drive. if you downloaded our examples repo, you'll find it in javascript/apis/video-audio/start/ at this point, if you load the html you should see a perfectly normal html5 video player, with the native controls rendered. exploring the html open the html index file. you'll see a number of features; the html is dominated by the video player and its controls: <div class="player"> <video controls> <source src="vid...
...v> <span aria-label="timer">00:00</span> </div> <button class="rwd" data-icon="b" aria-label="rewind"></button> <button class="fwd" data-icon="f" aria-label="fast forward"></button> </div> </div> the whole player is wrapped in a <div> element, so it can all be styled as one unit if needed. the <video> element contains two <source> elements so that different formats can be loaded depending on the browser viewing the site. the controls html is probably the most interesting: we have four <button>s — play/pause, stop, rewind, and fast forward. each <button> has a class name, a data-icon attribute for defining what icon should be shown on each button (we'll show how this works in the below section), and an aria-label attribute to provide an understandable descript...
CSS performance optimization - Learn web development
previous overview: performance next painting an unstyled page, and then repainting it once styles are parsed would be bad user experience. for this reason, css is render blocking, unless the browser knows the css is not currently needed. the browser can paint the page once it has downloaded the css and built the css object model. browsers follow a specific rendering path: paint only occurs after layout, which occurs after the render tree is created, which in turn requires both the dom and the cssom trees. to optimize the cssom construction, remove unnecessary styles, minify, compress and cache it, and split css not required at page load into additional files to reduce css render blocking. optimizing for render blocking css can scope styles to particular conditions with media ...
...will-change property tells browsers which properties of an element are expected to change enabling browsers to set up optimizations before the element is actually changed, improving performance by doing potentially expensive work before it is required. will-change: opacity, transform; the font-display property applied to the @font-face rule, the font-display property defines how font files are loaded and displayed by the browser, allowing text to appear with a fallback font while a font loads, or fails to load. this improves performance by making the text visible instead of having a blank screen, with a trade-off being a flash of unstyled text. @font-face { font-family: somefont; src: url(/path/to/fonts/somefont.woff) format('woff'); font-weight: 400; font-style: normal; font-displ...
Measuring performance - Learn web development
erforming, both for mobile and desktop. this is a good start for getting an idea about what you are already doing well and what could be improved. at the time of writing, mdn's performance report summary looks similar to the following: a performance report contains information about things like how long a user has to wait before anything is displayed on the page, how many bytes need to be downloaded to display a page, and much more. it also lets you know it the measured values are considered good or bad. webpagetest.org is another example of a tool that automatically tests your site and returns useful metrics. try running your favorite website now, on both webpagetest.org and pagespeed insights, and see what the scores are. network tools most browsers have tools available that you can us...
...e, and much more. it also lets you know it the measured values are considered good or bad. webpagetest.org is another example of a tool that automatically tests your site and returns useful metrics. try running your favorite website now, on both webpagetest.org and pagespeed insights, and see what the scores are. network tools most browsers have tools available that you can use to run against loaded pages and determine how they are performing. for example, the firefox network monitor returns detailed information on all the assets downloaded form the network, along with a time graph that shows how long each one took to download. you can also use the performance monitor to measure the performance of a web app or site's user interface as you perform different actions. this indicates the feat...
What is web performance? - Learn web development
. the download of additional assets linked to from the index file is generally sequential, based on source order, but this can be manipulated and should definitely be optimized, realizing that some resources block additional downloads until their content is parsed and executed. the critical path. this is the process that the browser uses to construct the web document once the files have been downloaded from the server. the browser follows a well-defined set of steps, and optimizing the critical rendering path to prioritize the display of content that relates to the current user action will lead to significant improvements in content rendering time. see critical rendering path for more information. the document object model. the document object model, or dom, is a tree structure that represents...
...n will lead to significant improvements in content rendering time. see critical rendering path for more information. the document object model. the document object model, or dom, is a tree structure that represents the content and elements of your html as a tree of nodes. this includes all the html attributes and the relationships between the nodes. extensive dom manipulation after the pages has loaded (e.g., adding, deleting, or moving of nodes) can affect performance, so it is worth understanding how to dom works, and how such issues can be mitigated. find out more at document object model. latency. we mention this briefly earlier on, but in brief, latency is the time it takes for your website assets to travel from the server to a user's computer. there is overhead involved in establishing t...
Multimedia: video - Learn web development
we have already taken a look at optimizing images. this article looks at optimizing video to improve web performance. prerequisites: basic computer literacy, basic software installed, and basic knowledge of client-side web technologies. ...
...to remove audio: ffmpeg -i original.mp4 -an -c:v copy audiofreeversion.mp4 video preload the preload attribute has three available options: auto|metadata|none. the default setting is metadata. these settings control how much of a video file downloads with page load. you can save data by deferring download for less popular videos. setting preload="none" results in none of the video being downloaded until playback. it delays startup, but offers significant data savings for videos with a low probability of playback. offering more modest bandwidth savings, setting preload="metadata" may download up to 3% of the video on page load. this is a useful option for some small or moderately sized files. changing the setting to auto tells the browser to automatically download the entire video. do thi...
The "why" of web performance - Learn web development
ght 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 structure) at 31.86 seconds. and it isn't just the time taken to download that is a major problem. a lot of countries still have internet connections that bill per megabyte. our example 22.6 mb cnn.com experience would cost about 11% of the average indian's daily wage to download. from a mobile device in northwest africa, it might cost two days of an average salary.
...e html structure) at 31.86 seconds. and it isn't just the time taken to download that is a major problem. a lot of countries still have internet connections that bill per megabyte. our example 22.6 mb cnn.com experience would cost about 11% of the average indian's daily wage to download. from a mobile device in northwest africa, it might cost two days of an average salary. and if this site were loaded on a us carrier's international roaming plan? the costs would make anyone cry. (see how much your site costs to download.) improve conversion rates reducing the dowload and render time of a site improves conversion rates and user retention. a conversion rate is the rate at which site visitors perform a measured or desired action. for example, this might be making a purchase, reading an artic...
Ember resources and troubleshooting - Learn web development
ebugging, check out our guides on javascript debugging as well as interacting with the browser's other debugging tools. in any default ember project, there will be two main javascript files, vendor.js and {app-name}.js. both of these files are generated with sourcemaps, so when you open the vendor.js or {app-name}.js to search for relevant code, when a debugger is placed, the sourcemap will be loaded and the breakpoint will be placed in the pre-transpiled code for easier correlation to your project code. for more information on sourcemaps, why they're needed, and what the ember-cli does with them, see the advanced use: asset compilation guide. note that sourcemaps are enabled by default. ember-data comes pre-installed; do i need it? not at all. while ember-data solves the most common probl...
... 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 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.
Introducing a complete toolchain - Learn web development
you to branch out your project code, creating a separate version and try out new functionality on, without those changes affecting your original code. finally, it can help you undo changes or revert your code back to a time "when it was working" if a mistake has been introduced somewhere and you are having trouble fixing it — something all developers need to do once in a while! git can be downloaded and installed via the git-scm website — download the relevant installer for your system, run it, and follow the on-screen prompts. this is all you need to do for now. you can interact with git in a number of different ways, from using the command line to issue commands, to using a git gui app to issue the same commands by pushing buttons, or even from directly inside your code editor, as seen...
...d the entire project as a zip file by selecting clone or download > download zip. now copy the contents of the project's src directory to your currently empty src directory. we have our project files in place. that’s all we need to do for now! note: if you want to just take our existing project and set it up, ready to use, you could go into the root directory of the unzipped downloaded, and run one single installation command to install all of the project’s dependencies: npm install. this is possible because we installed all the tools locally, not globally, and highlights why it is such a powerful option. installing our tools now it's time to install the initial set of tools we'll be using in our dev environment. run the following from inside your project's root directory:...
Package management basics - Learn web development
not work right out of the box and you will likely need some modern tooling to bundle your code and dependencies together when they are released on the web. a bundle is the term that’s generally used to refer to a single file on your web server that contains all the javascript for your software — typically compressed as much as possible to help reduce the time it takes to get your software downloaded and displayed in your visitors’ browser. in addition, what happens if you find a better tool that you want to use instead of the current one, or a new version of your dependency is released that you want to update to? this is not too painful for a couple of dependencies, but in larger projects with many dependencies this kind of thing can become really challenging to keep track of. it makes mo...
...t's worth questioning whether they're doing the right thing for you. in this case, the bundle is nearly 200k because it has in fact included the entire date-fns library, not just the function we're using. if we had avoided any development tools and pointed a <script src=””> element to a hosted version of date-fns, roughly the same thing would have happened — all of the library would be downloaded when our example page is loaded in a browser. however, this is where development tooling has a chance to shine. whilst the tooling is on our machine, we can ask the software to inspect our use of the code and only include the functions that we're actually using in production — a process known as "tree shaking". this makes a lot of sense as we want to reduce file size and thus make our app loa...
Mozilla accessibility architecture
cessible is not created directly in the widget code where it's needed is that the widget code has no knowledge what nsidomnode is associated with the current window's document object. there must be a document for the current widget (nswindow/nsiwidget) for the pres shell to create a doc accessible for it. one benefit of this approach is that accessibility.dll/libaccessibility.so does not need get loaded until the accessibility service gets used, and for most users it is never loaded. all other accessibles for the individual objects are created on demand as well. the assistive technology can choose to get the entire tree by using a depth- or breadth- first search, it can choose to get accessibles only based on events like focus, or it can get the accessible at a given point on the screen. no matt...
...uld not afford to use 4 bytes on dom or layout nodes to point back to accessible objects. therefore, ownership is reversed -- accessible nodes own their dom objects. however, this creates instability when mozilla wants to shut down but an assistive technology client still holds onto accessibles. these crashes occur when the assistive techology releases after some gecko modules have already been unloaded, when the necessary destructors no longer exist in memory. performance: by caching the accessible node for each dom node in a hash table, we can hand back accessibles extremely quickly, and avoid recalculating and creating new accessibles every time one is requested for a certain dom node. we also avoid calculating the children of an accessible twice, once for getaccchildcount() and again when ...
Debugging on Windows
browser to open as soon as it starts, starting the profile manager, or selecting a profile. you can also redirect the console output to a file (by adding "> filename.txt" for example, without the quotes). in vc 7 and 8 this option is called project > properties > debugging > command arguments. vc 8 also allows you to set environment variables there. setting breakpoints in dlls which are not yet loaded in memory vc++ 6.0: go to project > settings..., debug tab and select "additional dlls" from the drop down list. check "locate additional dlls" option. for each dll, click the "new" button which creates a new entry and then hit the "..." buttons which lets you browse to the dll. you will only be able to add one dll at a time. vc++ 7.0 automatically finds additional dlls. customizing the debugg...
...ncheck 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 debugging tools). find the directory where visual studio caches downloaded symbols; in vc++ 10 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...
mach
mach, please add [mach] to the whiteboard. mach is relatively new and the api is changing. so, the best way to figure out how to implement a new mach command is probably to look at an existing one. start by looking at the source for the mach driver. you will see a list defining paths to python files (likely named mach_commands.py). these are the python files that implement mach commands and are loaded by the mach driver. these are relative paths in the source repository. simply find one you are interested in and dig in! mach command providers a mach command provider is simply a python module. when these modules are loaded, mach looks for specific signatures to detect mach commands. currently, this is implemented through python decorators. here is a minimal mach command module: from __future...
...mach command for approval once you've authored a mach command, submit the patch for approval. please flag firefox-build-system-reviewers for review. mach command modules useful information command modules are not imported into a reliable python package/module "namespace." therefore, you can't rely on the module name. all imports must be absolute, not relative. because mach command modules are loaded at mach start-up, it is important that they be lean and not have a high import cost. this means that you should avoid global import statements as much as possible. instead, defer your import until inside the @command decorated method. mach ships with a toolbox of mix-in classes to facilitate common actions. see python/mach/mach/mixin. if you find yourself reinventing the wheel or doing something...
Error codes returned by Mozilla APIs
_available (0x80040111) an operation could not be completed because some other necessary component or resource was not available. ns_error_factory_not_registered (0x80040154) returned when a service could not be found. ns_error_factory_register_again (0x80040155) this error is returned when registering a component and the registration should try registering again later. ...
...03e9) ns_error_uconv_noconv (0x80500001) ns_error_udec_illegalinput (0x8050000e) ns_imagelib_error_failure (0x80540005) ns_imagelib_error_no_decoder (0x80540006) ns_imagelib_error_not_finished (0x80540007) ns_imagelib_error_load_aborted (0x80540008) ns_error_wont_handle_content (0x805d0001) moz_error_storage_error (0x80630001) ns_error_schemavalidator_no_schema_loaded (0x80640001) ns_error_schemavalidator_no_dom_node_specified (0x80640002) ns_error_schemavalidator_no_type_found (0x80640003) ns_error_schemavalidator_type_not_found (0x80640004) note: there are other errors in these files: gfx/public/nsidevicecontext.h base/public/nsneterror.h parser/htmlparser/public/nsiparser.h layout/base/nslayouterrors.h profile/public/nsiprofileintern...
Experimental features in Firefox
see bug 1335970 for more details. release channel version added enabled by default? nightly 60 no developer edition 60 no beta 60 no release 60 no preference name security.insecure_connection_text.enabled for normal browsing mode; security.insecure_connec...
... name security.insecure_connection_text.enabled for normal browsing mode; security.insecure_connection_text.pbmode.enabled for private browsing mode upgrading mixed display content when enabled, this preference causes firefox to automatically upgrade requests for media content from http to https on secure pages. the intent is to prevent mixed-content conditions in which some content is loaded securely while other content is insecure. if the upgrade fails (because the media's host doesn't support https), the media is not loaded. see bug 1435733 for more details. this also changes the console warning; if the upgrade succeeds, the message indicates that the request was upgraded, instead of showing a warning. release channel version added enabled by default? ...
Frame script environment
may be null (see below) docshell the nsidocshell associated with the browser. addeventlistener() listen to events from content. removeeventlistener() stop listening to events from content. addmessagelistener() listen to messages from chrome. removemessagelistener() stop listening to messages from chrome. sendasyncmessage() send an asynchronous message to chrome. ...
...ing unload events from content. does not bubble. domwindowcreated fires when a new content object is created. this can be used if a framescript needs to interact with individual dom windows instead of simply listening for events bubbling up from content. another use is to interact with the content very early in the page load process, long before domcontentloaded event is fired. ...
Frame script environment
addeventlistener() listen to events from content. removeeventlistener() stop listening to events from content. addmessagelistener() listen to messages from chrome. removemessagelistener() stop listening to messages from chrome. sendasyncmessage() send an asynchronous message to chrome. ...
... object to avoid handling unload events from content. domwindowcreated fires when a new content object is created. this can be used if a framescript needs to interact with individual dom windows instead of simply listening for events bubbling up from content. another use is to interact with the content very early in the page load process, long before domcontentloaded event is fired. ...
Limitations of frame scripts
ll here will fail. if you want a chrome window: send a message from the content process using the message manager. the target property of the object passed into the message handler in the chrome process is the xul <browser> receiving the message, and you can get the chrome window from that (i'm not sure how). nsiaboutmodule by default, custom about: pages registered using nsiaboutmodule are loaded in the chrome process. this means that you can't access their content from the content process (via xhr, for example). there is a shim for this that makes the content of about: pages registered by the add-on transparently available in the content process. to avoid the shim: if you need to access the content of your about page from the content process, you need to register the nsiaboutmodule in ...
...xample). there is a shim for this that makes the content of about: pages registered by the add-on transparently available in the content process. to avoid the shim: if you need to access the content of your about page from the content process, you need to register the nsiaboutmodule in the content process as well as the chrome process. by default, about: pages (except for a small whitelist) are loaded in the chrome process when browsed to from the awesomebar. javascript code modules (jsms) in multiprocess firefox, a jsm loaded into the content process does not share any state with the same jsm loaded into the chrome process. see the entry in the limitations on chrome scripts page. ...
Performance best practices for Firefox front-end engineers
fox 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. ...
...mpacts the performance of the browser. ...
mozbrowserloadend
ellable or not. details read only object a custom object. detail the detail property returns an anonymous javascript object with the following properties: backgroundcolor a domstring representing the main background color of the browser <iframe> content, expressed as an rgb value. can be used to make the theme of the surrounding ui complement the theme of the currently loaded content, for example. example in this example the mozbrowserloadstart and mozbrowserloadend events are used to change the icon shown on the stop/reload button between stop (x) and reload (r), as appropriate. in addition, the background of the controls ui bar is changed to the background color of the site that has just loaded, to provide a more integrated experience. when the front page of http...
...ple in this example the mozbrowserloadstart and mozbrowserloadend events are used to change the icon shown on the stop/reload button between stop (x) and reload (r), as appropriate. in addition, the background of the controls ui bar is changed to the background color of the site that has just loaded, to provide a more integrated experience. when the front page of https://developer.mozilla.org is loaded, for example, the e.detail.backgroundcolor value reported is rgb(0, 83, 159). var browser = document.queryselector("iframe"); browser.addeventlistener('mozbrowserloadend',function(e) { stopreload.textcontent = 'r'; console.log(e.detail.backgroundcolor); controls.style.background = e.detail.backgroundcolor; }); browser.addeventlistener('mozbrowserloadend',function() { stopreload.textcon...
mozbrowsersecuritychange
boolean whether the event is cancellable or not. details read only object a custom object. details the details property returns an anonymous javascript object with the following properties: state a domstring representing the current state of ssl security. possible values are: broken: indicates an unknown security 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: ...
... 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 active content has been loaded. blocked_mixed_active_conten...
How to get a stacktrace with WinDbg
ownload. this may take some time depending on your connection speed; the total size of the mozilla and microsoft symbols download is around 1.4gb. windbg will show "busy" at the bottom of the application window until the download is complete. once the download is complete, you need to configure windbg to examine child processes, ignore a specific event caused by flash player, and record a log of loaded modules. you will also want to open a log file to save data you collect. to do this, enter these four commands, pressing enter after each one. .logopen /t c:\temp\firefox-debug.log .childdbg 1 .tlist sxn gp lm if you see firefox.exe listed in the output from .tlist more than once, then you are already running the application and need to close the running instance first before you start debuggi...
...firefox hangs and there is no command prompt available in the debugger, open the debug menu and choose break. once the browser has crashed or been stopped, continue with the steps below. after the crash or hang you need to capture the debug information to include in a bug comment or support request. enter these three commands, one at a time, to get the stacktrace, crash/hang analysis and log of loaded modules. (again, press enter after each command.) ~* kp !analyze -v -f lm after these steps are completed, find the file c:\temp\firefox-debug-(today's date).txt on your hard drive. to provide the information to the development community, submit this file with a support request or attach it to a related bug on bugzilla. producing a minidump sometimes the stacktrace alone is not enough informa...
DownloadTarget
mic property, which is updated when the download is completed or when the download.refresh() method is called. you can use this instead of using file system calls to check for the existence of the file in order to reduce io overhead. path read only string the path of the target file. partfilepath read only string the path of the ".part" file containing the data downloaded so far, or null to disable the use of a ".part" file to keep partially downloaded data. size read only number the size of the target file, in bytes, or zero if the download has not yet been completed. it is possible for this property to have a non-zero value even if the target file no longer exists, if the value is available in download metadata. if that metadata is no ...
... state of a finished, failed, or canceled download based on the current state as indicated by the file system. if the download is in progress or has been finalized, this method does nothing and returns a resolved promise. calling this method lets the download object's properties be updated if the user moves or deletes the target file or its associated ".part" file, which contains a partially-downloaded file's contents. promise refresh(); parameters none. promise resolves to undefined when the state of the download has been updated. promise can be rejected with never. ...
Examples
the ...
...the error = ' + uneval(e)); } myimage.onabort = function(e) { loadthisimagepromise.reject('image load was aborted loading path = "' + path + '".'); } ...
XPCOMUtils.jsm
to use this, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/xpcomutils.jsm"); using xpcomutils exposing a javascript class as a component using these utility methods requires four key steps: import xpcomutils.jsm, as explained previously. declare the class (or multiple classes) implementing the component(s). create an array of component constructors. define the nsgetfactory() or nsgetmodule() entry point. ...
...sn't need to return a value. ...
Bootstrapping a new locale
ties history sidebar migration tabbrowser.dtd openlocation.dtd tabbrowser.properties openlocation.properties as a localizer, you are responsible for localizing each of the ".dtd" and ".properties" in *all* of the sub-directories found in your ab-cd directory. ...
...following directories: ab-cd/browser/ ab-cd/dom/ ab-cd/netwerk/ ab-cd/other-licenses/branding/firefox/ ab-cd/security/manager/ ab-cd/toolkit/ translating to start editing, you will need a text editing application. you can choose to use: notepad++ or notepad2 on windows, vim, gedit or kate on gnu/linux, textwrangler on mac os x. (read more about tools at l10n:tools.) after you have downloaded your editor of choice, type the following command in the same path from above (~/ab-cd/browser/chrome/browser) $ edit ab-cd/browser/chrome/browser/aboutcerterror.dtd read the top of the file to get any context on how to translate contained in the notes written by the developers or l10n-drivers. localization notes will look like this: <!-- localization notes... --> after the localization note...
Using the viewport meta tag to control layout on mobile browsers
can be set to a specific number of pixels like width=600 or to the special value device-width, which is the width of the screen in css pixels at a scale of 100%. (there are corresponding height and device-height values, which may be useful for pages with elements that change size or position based on the viewport height.) the initial-scale property controls the zoom level when the page is first loaded. the maximum-scale, minimum-scale, and user-scalable properties control how users are allowed to zoom the page in or out. usage of user-scalable=no can cause accessibility issues to users with visual impairments such as low vision. a pixel is not a pixel in recent years, screen resolutions have risen to the size that individual pixels are hard to distinguish with the human eye. for example, ...
...attributes that are available are minimum-scale, maximum-scale, and user-scalable. these properties affect the initial scale and width, as well as limiting changes in zoom level. not all mobile browsers handle orientation changes in the same way. for example, mobile safari often just zooms the page when changing from portrait to landscape, instead of laying out the page as it would if originally loaded in landscape. if web developers want their scale settings to remain consistent when switching orientations on the iphone, they must add a maximum-scale value to prevent this zooming, which has the sometimes-unwanted side effect of preventing users from zooming in: <meta name="viewport" content="initial-scale=1, maximum-scale=1"> suppress the small zoom applied by many smartphones by setting the...
PR_FindSymbol
pr_findsymbol() will return an untyped reference to a symbol in a particular library given the identity of the library and a textual representation of the symbol in question. syntax #include <prlink.h> void* pr_findsymbol ( prlibrary *lib, const char *name); parameters the function has these parameters: lib a valid reference to a loaded library, as returned by pr_loadlibrary, or null. name a textual representation of the symbol to resolve. returns an untyped pointer. description this function finds and returns an untyped reference to the specified symbol in the specified library. if the lib parameter is null, all libraries known to the runtime and the main program are searched in an unspecified order. use this function to look up functions or data symbols in a shared lib...
... ...
PR_FindSymbolAndLibrary
finds a symbol in one of the currently loaded libraries, and returns both the symbol and the library in which it was found. syntax #include <prlink.h> void* pr_findsymbolandlibrary ( const char *name, prlibrary **lib); parameters the function has these parameters: name the textual representation of the symbol to locate. lib a reference to a location at which the runtime will store the library in which the symbol was discovered. this location must be pre-allocated by the caller. returns if successful, returns a non-null pointer to the found symbol, and stores a pointer to the library in which it was found at the location pointed to by lib. if the symbol could not be found, returns null. ...
...store the library in which the symbol was discovered. this location must be pre-allocated by the caller. returns if successful, returns a non-null pointer to the found symbol, and stores a pointer to the library in which it was found at the location pointed to by lib. if the symbol could not be found, returns null. description this function finds the specified symbol in one of the currently loaded libraries. it returns the address of the symbol. upon return, the location pointed to by the parameter lib contains a pointer to the library that contains that symbol. the location must be pre-allocated by the caller. the function returns null if no such function can be found. the order in which the known libraries are searched in not specified. this function is equivalent to calling first pr_lo...
PKCS #11 Module Specs
params" nss_params are themselves name/value pairs, parsed with the same rules described above. valid names inside nss_params are: 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 roll...
...n also cause nss to miss certificates in a token until that token is explicitly logged in. rootflags - comma separated of flags describing any root certs that may be stored (case-insensitive). valid flags are: hasrootcerts - claims that this token has the default root certs and trust values. at init time nss, will try to look for a default root cert device if one has not already been loaded. hasroottrust - parsed but ignored. timeout - time in minutes before the current authentication should be rechecked. this value is only used if askpwd is set to 'timeout'. (default = 0). askpwd - case-insensitive flag describing how password prompts should be manages. only one of the following can be specified. every - prompt whenever the a private key on this token needs to be a...
JSErrorReport
st char * indicates the source file or url that produced the error condition. if null, the error is local to the script in the current html page. lineno unsigned line number in the source that caused the error. column unsigned zero-based column index in line in the source that caused the error. ismuted bool the web platform allows scripts to be loaded from arbitrary cross-origin sources. this allows an attack by which a malicious website loads a sensitive file (say, a bank statement) cross-origin (using the user's cookies), and sniffs the generated syntax errors (via a window.onerror handler) for juicy morsels of its contents. to counter this attack, html5 specifies that script errors should be sanitized ("muted") when the script is not sa...
... allows an attack by which a malicious website loads a sensitive file (say, a bank statement) cross-origin (using the user's cookies), and sniffs the generated syntax errors (via a window.onerror handler) for juicy morsels of its contents. to counter this attack, html5 specifies that script errors should be sanitized ("muted") when the script is not same-origin with the global for which it is loaded. callers should set this flag for cross-origin scripts, and it will be propagated appropriately to child scripts and passed back in jserrorreports. linebuf const char * text of the line that caused the error, minus the trailing newline character. tokenptr const char * pointer to the error token in *linebuf. uclinebuf const char16_t * unicode line b...
FUEL
the object needs to be accessed like any other xpcom service: var application = components.classes["@mozilla.org/fuel/application;1"].getservice(components.interfaces.fueliapplication); ...
...the object needs to be accessed like any other xpcom service: var application = components.classes["@mozilla.org/fuel/application;1"].getservice(components.interfaces.fueliapplication); ...
Bundling multiple binary components
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 configuration. it's pretty simple to do and the concept can be used to load third-party shared libraries (dll, so, d...
..., so, dylib) used in xpcom components. in this case, we would use the stub to load the right binary component instead. some key points: the real components have the same iids but have different filenames. one for each version of gecko and os platform. the real components are not in the "components" folder, but are in a side folder ("libraries" in the sample). the 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...
An Overview of XPCOM
s software easier to develop and maintain and has some well-known advantages: benefit description reuse modular code can be reused in other applications and other contexts. updates you can update components without having to recompile the whole application. performance when code is modularized, modules that are not necessary right away can be "lazy loaded", or not loaded at all, which can improve the performance of your application. maintenance even when you are not updating a component, designing your application in a modular way can make it easier for you to find and maintain the parts of the application that you are interested in. mozilla has over four million lines of code, and no single individual understands the entire cod...
... way, with state being held by global variables, but there are benefits to using classes for factories. when you use a class to implement the functionality of a factory, for example, you derive from the nsisupports interface, which allows you to manage the lifetime of the factory objects themselves. this is important when you want to group sets of factories together and determine if they can be unloaded. another benefit of using the nsisupports interface is that you can support other interfaces as they are introduced. as we'll show when we discuss nsiclassinfo, some factories support querying information about the underlying implementation, such as what language the object is written in, interfaces that the object supports, etc. this kind of "future-proofing" is a key advantage that comes along ...
Finishing the Component
nsmemory::free(previous); return rv; } this code adds a new category entry under the topic "content-policy," and it calls addcategoryentry in the same way we did in registering for notifications. a similar step is required for unregistration. implementing the nsicontentpolicy at this point, you can take the weblock component and install it into a gecko installation. when the component is loaded, gecko calls the nsicontentpolicy implementation in weblock on every page load, and this prevents pages from displaying by returning the proper value when the load method is called. the web locking policy that we are going to put into place is quite simple: for every load request that comes through, we will ensure that the uri is in the list of "good" urls on the white list. if you care to ext...
... white list. if you care to extend this implementation so that the list of urls is held remotely on a server somewhere - 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...
Starting WebLock
ay to register directly for a notification via the observer service is to instantiate an nsiobserver object. this works for most cases, but consider the case when you have this notification create a component. since the component hasn't been created yet, there are no instantiated nsiobserver objects that can be passed into the nsiobserverservice, nor can the component code do anything until it is loaded. registering for notifications the nsiobserverservice interface has methods for registering and unregistering an nsiobserver object. these two methods are used to dynamically add or remove an observer to a notification topic. but weblock needs to be instantiated and added to the observer service automatically, which also implies some sort of persistent data (after all, we want to have the compo...
...ritance - something that all scriptable objects must deal with. interface 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 i...
nsIBrowserSearchService
dded to the list upon successful load, but it will not be selected as the current engine. callback a nsisearchinstallcallback that will be notified when the addition is complete, or if the addition fails. it will not be called if addengine throws an exception. exceptions thrown ns_error_failure if the type is invalid, or if the description file cannot be successfully loaded. addenginewithdetails() adds a new search engine, without asking the user for confirmation and without starting to use it right away. void addenginewithdetails( in astring name, in astring iconurl, in astring alias, in astring description, in astring method, in astring url ); parameters name the search engine's name. must be unique. must not be null. iconurl ...
...search engine. description optional: a description of the search engine. method the http request method used when submitting a search query. must be a case insensitive value of either "get" or "post". url the url to which search queries should be sent. must not be null. getdefaultengines() returns an array of all default search engines. this includes all loaded engines that aren't in the user's profile directory (ns_app_user_search_dir). void getdefaultengines( [optional] out unsigned long enginecount, [retval, array, size_is(enginecount)] out nsisearchengine engines ); parameters enginecount the number of default search engines. engines an array of the default nsisearchengines. getenginebyalias() returns an engine wit...
nsICachingChannel
o access the cache. load_only_from_cache 1 << 30 this load flag inhibits fetching from the net if the data in the cache has been evicted. an error of ns_error_document_not_cached will be sent to the listener's onstoprequest in this case. this flag is set automatically when the application is offline. load_only_if_modified 1 << 31 this load flag controls what happens when a document would be loaded from the cache to satisfy a call to asyncopen. if this attribute is set to true, then the document will not be loaded from the cache. a stream listener can check isfromcache() to determine if the asyncopen will actually result in data being streamed. if this flag has been set, and the request can be satisfied via the cache, then the ondataavailable events will be skipped. the listener will only s...
...ta being streamed. if this flag has been set, and the request can be satisfied via the cache, then the ondataavailable events will be skipped. the listener will only see onstartrequest followed by onstoprequest. methods isfromcache() obsolete since gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) this method finds out whether or not this channel's data is being loaded from the cache. boolean isfromcache(); parameters none. return value returns true if this channel's data is being loaded from the cache, otherwise returns false. this value is undefined before the channel fires its onstartrequest notification and after the channel fires its onstoprequest notification. see also nsicache ...
nsICategoryManager
let...
...entries = []; while (enumerator.hasmoreelements()) { var item = enumerator.getnext(); var entry = item.queryinterface(components.interfaces.nsisupportscstring) entries.push(entry.tostring()); } entries.sort(); var entriesstring = entries.join("\n"); dump(entriesstring + "\n"); disable currently loaded plugins by type this snippet here shows how to disable plugins that are currently loaded for the file type of pdf. 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.nsi...
nsICharsetResolver
methods notifyresolvedcharset() some implementations may request that they be notified when the charset is actually detected. void notifyresolvedcharset( in acstring charset, in nsisupports closure ); parameters charset the detected charset. closure the closure returned by requestcharset(). requestcharset() called to resolve the charset that should be used for parsing the document being loaded from achannel. if the charset cannot be resolved, but the implementation of nsicharsetresolver wants to be notified of the final resolved charset when one is available, it can set awantcharset to true. if this is done, the caller of requestcharset is responsible for calling notifyresolvedcharset() and passing it the final resolved charset and the closure that requestcharset set. acstring requestc...
.... if this is done, the caller of requestcharset is responsible for calling notifyresolvedcharset() and passing it the final resolved charset and the closure that requestcharset set. acstring requestcharset( in nsiwebnavigation awebnavigation, in nsichannel achannel, out boolean awantcharset, out nsisupports aclosure ); parameters awebnavigation the nsiwebnavigation the document is being loaded in. may be null. achannel the channel the document is coming in from. awantcharset gets set to true if notifyresolvedcharset() should be called with the given aclosure object. aclosure a resulting object which should be passed to notifyresolvedcharset() if awantcharset is set to true. return value the resolved charset, or an empty string if no charset could be determined. ...
nsIExternalProtocolService
heme found? return value an nsihanderinfo for the protocol. isexposedprotocol() check whether a handler for a specific protocol is "exposed" as a visible feature of the current application. an exposed protocol handler is one that can be used in all contexts. a non-exposed protocol handler is one that can only be used internally by the application. for example, a non-exposed protocol would not be loaded by the application in response to a link click or a x-remote openurl command. instead, it would be deferred to the system's external protocol handler. boolean isexposedprotocol( in string aprotocolscheme ); parameters aprotocolscheme the scheme from a url: http, ftp, mailto, and so on. return value true if the protocol is exposed, false otherwise. loaduri() used to load a uri via an external...
...ue true if the protocol is exposed, false otherwise. loaduri() used to load a uri via an external application. might prompt the user for permission to load the external application. void loaduri( in nsiuri auri, [optional] in nsiinterfacerequestor awindowcontext ); parameters auri the uri to load. awindowcontext the window to parent the dialog against, and, if a web handler is chosen, it is loaded in this window as well. this parameter may be ultimately passed nsiuriloader.openuri() in the case of a web handler, and awindowcontext is null or not present, web handlers will fail. loadurl() used to load a url via an external protocol handler (if one exists). void loadurl( in nsiuri aurl ); parameters aurl the url to load. setprotocolhandlerdefaults() set some sane defaults for a protoco...
nsIFaviconService
ageuri ); parameters apageuri uri of the page whose favicon is desired. return value returns a uri that will give you the icon image. this is not the uri of the icon as set on the page, but a uri that will give you the data out of the favicon service. for a normal page with a favicon we've stored, this will be an annotation uri which will then cause the corresponding favicon data to be loaded from this service. for pages where we don't have a favicon, this will be a chrome uri of the default icon for a web page. getfaviconlinkforicon() this method, for a given icon uri will return a uri that will result in the image. in most cases, this is an annotation uri. for chrome, this will do nothing and return the input uri. no validity checking is done. if you pass an icon uri that we've neve...
...nuri ); parameters afaviconuri the uri of an icon in the favicon service. return value returns a uri that will load the desired icon. this is not the uri of the icon as set on the page, but a uri that will give you the data out of the favicon service. for a normal page with a favicon we've stored, this will be an annotation uri which will then cause the corresponding favicon data to be loaded from this service. for pages where we don't have a favicon, this will be a chrome uri of the default icon for a web page. for chrome, the output will be the same as the input. for chrome, the output will be the same as the input. no validity checking is done. if you pass an icon uri that we've never seen, you'll get back a uri that references an invalid icon. the moz-anno protocol handler's speci...
nsIMicrosummaryGenerator
read only. localuri nsiuri for generators installed by the user or bundled with the browser, the local uri points to the location of the local file containing the generator's xml. read only. name autf8string an arbitrary descriptive name for this microsummary generator. read only. needspagecontent boolean whethe...
...read only. ...
nsIMicrosummaryObserver
/nsimicrosummaryservice.idlscriptable this interface provides methods for observing changes to micrummaries. ...
...lete gecko 6.0 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) warning: microsummary support was removed in gecko 6.0 (firefox 6.0 / thunderbird 6.0 / seamonkey 2.3) method overview void oncontentloaded(in nsimicrosummary microsummary); void onelementappended(in nsimicrosummary microsummary); void onerror(in nsimicrosummary microsummary); methods oncontentloaded() called when an observed microsummary updates its content. since an observer might watch multiple microsummaries at the same time, the microsummary whose content has been updated gets passed to this handler. void oncontentloaded( in nsimicrosummary microsummary ); parameters microsummary the microsummary whose content has just been updated. onelementappended() called when an element is appe...
nsIMsgMessageService
ng amessageuri, in nsisupports adisplayconsumer, in nsimsgwindow amsgwindow, in nsiurllistener aurllistener, in string acharsetoverride, out nsiuri aurl); parameters amessageuri a uri representing the message to display. adisplayconsumer is (for now) an nsidocshell which the message is loaded into. amsgwindow nsimsgwindow for progress and status feedback aurllistener an nsiurllistener acharsetoverride (optional) character set over ride to force the message to use. return values aurl the new nsiuri of the message. openattachment() downloads and opens an attachment. void openattachment(in string acontenttype, in string afilename, ...
...ng(in string amessageuri, in nsisupports adisplayconsumer, in nsimsgwindow amsgwindow, in nsiurllistener aurllistener, out nsiuri aurl); parameters amessageuri a uri representing the message to display. adisplayconsumer for now, a nsidocshell which the message is loaded into. amsgwindow nsimsgwindow for progress and status feedback aurllistener return values aurl the new nsiuri of the message. search() void search(in nsimsgsearchsession asearchsession, in nsimsgwindow amsgwindow, in nsimsgfolder amsgfolder, in string asearchuri); parameters asearchsession the nsimsgsearchsession to use. amsgwindow ns...
nsINavHistoryQuery
annotation autf8string the annotation name. annotationisnot boolean test for existance or non-existance of a given annotation. we don't currently support >1 annotation name per query. if annotationisnot is true, we test for the ...
... annotation autf8string the annotation name. ...
nsIParserUtils
ties. 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 sanitizerdropnoncsspresentation and/or sanitizerdropforms. by default, comments and css is removed. to preserve comments, use sanitizerallowcomments. to preserve <style> elements and style attributes on other elements, use sanitizerallowstyle. ...
... style attributes on other elements, use sanitizerallowstyle. -moz-binding is removed from <style> elements and style attributes if present. in this case, properties that gecko doesn't recognize can get removed as a side effect. note: if -moz-binding is not present, <style> elements and style attributes, and if sanitizerallowstyle is specified, the sanitized content may still be xss dangerous if loaded into a non-gecko web engine! astring sanitize( in astring src, in unsigned long flags ); parameters src the html source to parse (c++ callers are allowed but not required to use the same string for the return value). flags sanitization option flags defined above. return value the resulting text. ...
nsIProtocolProxyService
ect 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 nsiproxiedprotocolhandler.newproxiedchannel() method to create a nsichannel to the given uri that uses the specified proxy. however, if the nsiproxyinfo type is "http", then it means that the given uri should be loaded using the http protocol handler, which also supports nsiproxiedprotocolhandler. nsiproxyinfo resolve( in nsiuri auri, in unsigned long aflags ); parameters auri the uri to test. aflags a bit-wise combination of the resolve_ flags defined above. pass 0 to specify the default behavior. any additional bits that do not correspond to a resolve_ flag are reserved for future use. retu...
... unsigned long aflags ); parameters auri the uri to test. aflags a bit-wise combination of the resolve_ flags defined above. pass 0 to specify the default behavior. any additional bits that do not correspond to a resolve_ flag are reserved for future use. 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. u...
nsISHistory
n handle to the next object in the list. the object returned by this step is of type nsisupports. perform a queryinterface on the object returned by step #2 to nsishentry. use nsishentry to access properties of each history entry. read only. methods addshistorylistener() called to register a listener for the session history component. listeners are notified when pages are loaded or purged from history. note: a listener object must implement nsishistorylistener and nssupportsweakreference. void addshistorylistener( in nsishistorylistener alistener ); parameters alistener listener object to be notified for all page loads that initiate in session history. getentryatindex() called to obtain handle to the history entry at a given index. nsishentry getentryatindex...
...uments are removed from history. exceptions thrown ns_error_failure numentries is invalid or out of bounds with the size of history. ns_success_loss_of_insignificant_data purge was vetoed. reloadcurrententry() void reloadcurrententry(); parameters none. removeshistorylistener() called to remove a listener for the session history component. listeners are notified when pages are loaded from history. note: a listener object must implement nsishistorylistener and nssupportsweakreference. void removeshistorylistener( in nsishistorylistener alistener ); parameters alistener listener object to be removed from session history. ...
nsIUpdateItem
is item. read only. version astring the version of the item, in fvf format. read only. xpihash astring the string hash for the xpi file. can be null and if supplied must be in the format of "type:hash" (see the types in nsicryptohash and nsixpinstallmanager.initmanagerwithhashes(). read only. xpiurl astring the url of the xpi where this item can be downloaded. read only. constants item type constants constants representing types of update checks. constants that callers can use to indicate the reason for an add-on update check. internal code uses other constants in nsextensionmanager.js.in. constant gecko version description 1.8 1.8.1 1.9 1.9.1 1.9.2 type_app 0x01 type_extension ...
...); parameters id the item's guid. version the item's version. installlocationkey the name of the install location at which the item is installed. minappversion the minimum application version with which the item is compatible. maxappversion the maximum application version with which the item is compatible. name the item's name downloadurl the url from which the item is to be downloaded. xpihash the string hash for the xpi file. iconurl the url of the icon that can be shown for the item. updateurl the url of the update rdf for the item. updatekey the public key to use to verify updates for the item. type the type of item; see item type constants. targetappid the application id of the target application. ...
nsIUploadChannel
he notion of uploading a data stream. 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. 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 cont...
...tion prepended to the stream (by plugins) as well as clients (composer, uploading application) that want to upload data streams without any knowledge of protocol specifications. for this reason, we have a special meaning for the acontenttype parameter. void setuploadstream( in nsiinputstream astream, in acstring acontenttype, in long acontentlength ); parameters astream the stream to be uploaded by this channel. acontenttype if acontenttype is empty, the protocol will assume that no content headers are to be added to the uploaded stream and that any required headers are already encoded in the stream. in the case of http, if this parameter is non-empty, then its value will replace any existing content-type header on the http request. in the case of ftp and file, this parameter is ignored.
nsIUploadChannel2
icle. 1.0 66 introduced gecko 1.9.2 inherits from: nsisupports last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) method overview void explicitsetuploadstream(in nsiinputstream astream, in acstring acontenttype, in long long acontentlength, in acstring amethod, in boolean astreamhasheaders); methods explicitsetuploadstream() sets a stream to be uploaded by this channel with the specified content-type and content-length header values. most implementations of this interface require that the stream: implement threadsafe addref and release implement nsiinputstream.readsegments() implement nsiseekablestream.seek(). void explicitsetuploadstream( in nsiinputstream astream, in acstring acontenttype, in long long acontentlength, in acstring ame...
...s. most implementations of this interface require that the stream: implement threadsafe addref and release implement nsiinputstream.readsegments() implement nsiseekablestream.seek(). void explicitsetuploadstream( in nsiinputstream astream, in acstring acontenttype, in long long acontentlength, in acstring amethod, in boolean astreamhasheaders ); parameters astream the stream to be uploaded by this channel. acontenttype this value will replace any existing content-type header on the http request, regardless of whether or not its empty. acontentlength a value of -1 indicates that the length of the stream should be determined by calling the stream's available method. amethod the http request method to set on the stream. astreamhasheaders true if the stream already contains headers for...
nsIWebPageDescriptor
inherits from: nsisupports last changed in gecko 1.7 method overview void loadpage(in nsisupports apagedescriptor, in unsigned long adisplaytype); attributes attribute type description currentdescriptor nsisupports retrieves the page descriptor for the current document. read only. constants display type constants constant value description display_as_source 0x0001 generates an optionally syntax-highlighted (for xml/html documents) source of the original page. ...
... ...
nsIWindowWatcher
ll effectively act as if aparent were null. aurl the url to open in the new window. must already be escaped, if applicable. can be null. aname a window name assigned using window interface's open() method loads the specified resource into the browsing context (window, <iframe> or tab) with the specified name. if the name doesn't exist, then a new window is opened and the specified resource is loaded into its browsing context.">window.open. can be null. if a window with this name already exists, the openwindow call may just load aurl in it (if aurl is not null) and return it. afeatures window features. see window interface's open() method loads the specified resource into the browsing context (window, <iframe> or tab) with the specified name. if the name doesn't exist, then a new window is ...
...pen. can be null. if a window with this name already exists, the openwindow call may just load aurl in it (if aurl is not null) and return it. afeatures window features. see window interface's open() method loads the specified resource into the browsing context (window, <iframe> or tab) with the specified name. if the name doesn't exist, then a new window is opened and the specified resource is loaded into its browsing context.">window.open for details. can be null. list of feature options aarguments extra argument(s) to be attached to the new window as the window.arguments property. an nsisupportsarray will be unwound into multiple arguments (but not recursively!). can be null, in which case the window.arguments property will not be set on the new window. as of gecko 1.9 alpha 1, can also b...
Troubleshooting XPCOM components registration
often the first time you create an xpcom component, it may fail to register correctly. there are several common reasons that registration can fail: a component that is a binary (shared library) fails to load a javascript component has parsing errors the shared library loaded correctly, but registration was not successful did registration succeed? it is important to not misdiagnose the problem. you can be certain that a component has failed to register by going to the error console and evaluating components.classes["contract-id"].name where contract-id is your contract id. if the response is your contract id instead of an error, the component was successfully registered and this is the wrong page. load failure of binary components on the mozilla trunk (firefox 3, xulrunner 1.9)...
...tion (or other vendor-supplied build), look for -dev packages from them. remember to check that the directory the component is in is named correctly i.e. $profile/extensions/$plugindirectory/components! double check your guids in your install.rdf with your sourcecode, and then check them again. windows-specific hints use dependency walker to check that your dependent libraries are loaded correctly. in dependency walker, open the options menu and select configure module search order.... in the bottom right corner of the new dialog, click browse... and select the directory firefox.exe (or equivalent) is in. in the bottom left corner, click add directory. do not add any other directories; in particular, do not add your extension's (or xulrunner application's) compone...
Mail composition back end
the first attachment is provided via `attachment1_type' `attachment1_body' and `attachment1_body_length'. these may all be 0 if all attachments are provided externally. const struct nsmsgattachmentdata *attachments, - subsequent attachments are provided as urls to load, described in the nsmsgattachmentdata structures. ...
... these may all be 0 if all attachments are provided externally. const struct nsmsgattachmentdata *attachments, - subsequent attachments are provided as urls to load, described in the nsmsgattachmentdata structures. const struct nsmsgattachedfile *preloaded_attachments, - attachments that are already locally stored on disk (note: both attachments and preloaded_attachments cannot be specified on a single call void *relatedpart /* nsmsgsendpart */, - a related part for multipart related operations nsimsgsendlistener **alistenerarray) = 0; - an array of listeners for the send operation. this can be nsnull if you want to do the delivery operation "blind" se...
Main Windows
ear confusing when you're just beginning to look at it. as such, i've always thought it would be nice to have a list of what xul, js, or other files are that are here, what they do, and where they overlay at different points within the client. things appear confusing for several reasons: much of the code is written to be portable, so instead of duplicating it, its been put in overlays that are loaded over many different types of windows. some of the code was written based off of early firefox code, but is not exactly the same. you’ll sometimes see reimplementations of things that are already in toolkit, written specially for thunderbird. messenger.xul the base mail window that you see when you first open thunderbird is messenger.xul: messenger.xul itself doesn’t contain a lot. its ma...
...ot exactly the same. you’ll sometimes see reimplementations of things that are already in toolkit, written specially for thunderbird. messenger.xul the base mail window that you see when you first open thunderbird is messenger.xul: messenger.xul itself doesn’t contain a lot. its main focus is on handling the folderpane, threadpane, and the message preview sections shown above. the rest is loaded from overlays: mailwindowoverlay.xul this is the red sections shown in the interface above (where?), including the toolbars, notification bars, and the status bar, but also includes most of the commands, keysets, and context menus of thunderbird, along with a whole lot of javascript. mailoverlay.xul a really small overlay that only adds a few “new message” and “new card” commands to...
XPI
is a zip file used to install packages, utilizing the xpinstall technology. xpi modules (so called "bundles") are employed to install a wide variety of software, including plugins, extensions, themes, and thunderbird dictionaries. an xpi contains installation instructions (install.js or install.rdf) as well as the actual software to install, which is often itself packaged as a jar file. when downloaded or dropped into an extension manager, xpinstall automatically interacts with the installation instructions contained in the xpi, and installs the contained software. xpi archives only support files stored uncompressed or compressed using the "deflate" method. note: starting in gecko 2.0, xpi files are no longer unpacked when extensions are installed. instead, the xpi itself is placed in the ex...
...ger, xpinstall automatically interacts with the installation instructions contained in the xpi, and installs the contained software. xpi archives only support files stored uncompressed or compressed using the "deflate" method. note: starting in gecko 2.0, xpi files are no longer unpacked when extensions are installed. instead, the xpi itself is placed in the extensions directory, and files are loaded directly out of the package. see updating extensions for firefox 4 for details. when xpi files are served via http, the application/x-xpinstall mime type should be matched with the xpi file extension. see also bundles xpinstall creating xpi installer modules ...
ctypes.open
any work can commence. there are two options: custom native file (dll, so, dylib, etc.) standard os libraries custom native file for this method, a native file must be created. a native file for use on unix systems is an so file, which is created and a c function called add() is written. int add(int a, int b) { return a + b; } to make this a shared library, a native file which can be loaded and used from js-ctypes, compile it with these commands: gcc -fpic -c mycfuntionsforunix.c gcc -shared -o mycfuntionsforunix.so mycfuntionsforunix.o a file named mycfuntionsforunix.so is successfully created. 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 r...
...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. ...
Plug-in Development Overview - Plugins
atform-specific discovery and registration: ms windows unix mac os x ms windows on windows, plug-ins are found according to the section how gecko finds plug-ins. to determine the mime types and file extensions that the plug-in handles, the browser normally uses the content of the registry entries for the plug-in described below in installation using the registry. but when the plug-in is loaded from a well-known directory, a different method must be used. in this case to ensure the plug-in file will be loaded, it should have a name in the form of "np*.dll". also, the windows version information for the plug-in dll will be used to determines the mime types, file extensions, file open template, plug-in name, and description. for this the version stamp of the embedded resource of the plug...
... the resource code for this language and character set combination is 040904e4. unix on unix, plug-ins are found according to the section how gecko finds plug-ins. to determine the mime types and file extensions that the plug-in handles, the browser...
DOM Inspector FAQ - Firefox Developer Tools
how do i inspect a web site/window? the file menu contains approaches which will allow you to inspect a document. inspect content document inspect content, e.g., unprivileged web pages loaded in a browser tab. inspect chrome document inspect application chrome, including open xul windows, e.g., the browser window. inspect a url this just focuses the dom inspector's address bar, which allow you to inspect arbitrary documents which can be accessed via a url. this causes the document to be loaded in the browser pane. these can include chrome documents, but it's not suggested that you inspect xul documents by directly inspecting them via url, since some behavior may rely on the document being contained in another xul document, or the converse, where it won't behave correctly because...
...instead, get the xul document to load as you normally would (e.g., by invoking commands or opening windows via standard application use), then locate it in the inspect chrome document menu. ...
Access debugging in add-ons - Firefox Developer Tools
we are planning to deprecate the use by firefox add-ons of the techniques described in this document. don't write new add-ons that use these techniques. the following items are accessible in the context of chrome://browser/content/debugger.xul (or, in version 23 beta, chrome://browser/content/devtools/debugger.xul): window.addeventlistener("debugger:editorloaded") - called when the read-only script panel loaded. ...
...echniques described in this document. don't write new add-ons that use these techniques. the following items are accessible in the context of chrome://browser/content/debugger.xul (or, in version 23 beta, chrome://browser/content/devtools/debugger.xul): window.addeventlistener("debugger:editorloaded") - called when the read-only script panel loaded. ...
Tree map view - Firefox Developer Tools
(tree-structured) data as a set of nested rectangles". the size of the rectangles corresponds to some quantitative aspect of the data. for the treemaps shown in the memory tool, things on the heap are divided at the top level into four categories: objects: javascript and dom objects, such as function, object, or array, and dom types like window and htmldivelement. scripts: javascript sources loaded by the page. strings other: this includes internal spidermonkey objects. each category is represented with a rectangle, and the size of the rectangle corresponds to the proportion of the heap occupied by items in that category. this means you can quickly get an idea of roughly what sorts of things allocated by your site are using the most memory. within top-level categories: objects is fu...
...rs, each monster having a randomly-generated name. you can see that most of the heap is occupied by the strings used for the monsters' names, and the objects used to contain the monsters' other attributes. this treemap is from http://www.bbc.com/, and is probably more representative of real life than the examples. you can see the much larger proportion of the heap occupied by scripts, that are loaded from a large number of origins. ...
Edit fonts - Firefox Developer Tools
note: the updated font tools as shown in this article are available in firefox 63 onwards; if you are using an older version of firefox the tools will not look or behave quite the same, but they will be similar (most notably the font editor will not be available). ...
..., shows an expandable list of all of the fonts in use on the page. the list is useful because you can easily determine whether a font is a web font or a font hosted on your system. each font listed in this section shows you: the font-family identifier and full name of the font. the url to the font file in the case of web fonts not available on your system, or "system" in the case of fonts loaded from your computer (either default system fonts, or web fonts that you've also got installed on your system). you can copy the url to the font file by clicking on the icon to the right of the url. the @font-face descriptor that loads the font into the page, in the case of web fonts. the descriptor is expandable — when opened it shows its full syntax as defined in the stylesheet. a text sample...
Responsive Design Mode - Firefox Developer Tools
reloading on these changes can be helpful because certain page behaviors would otherwise not be applied. for example, many pages check f...
...de and returns to regular browsing the settings menu includes the following commands: left-align viewport - when checked moves the rdm viewport to the left side of the 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 fe...
about:debugging (before Firefox 68) - Firefox Developer Tools
s 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. updating a temporary add-on if you install the add-on in this way, what happens when you update the add-on's files? before firefox 48 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. 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 ar...
... 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 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...
AudioProcessingEvent - Web APIs
uffer the buffer where the output audio data should be written. the number of channels is defined as a parameter, numberofoutputchannels, of the factory method audiocontext.createscriptprocessor(). note the the returned audiobuffer is only valid in the scope of the onaudioprocess function. example the following example shows basic usage of a scriptprocessornode to take a track loaded via audiocontext.decodeaudiodata(), process it, adding a bit of white noise to each audio sample of the input track (buffer) and play it through the audiodestinationnode. for each channel and each sample frame, the scriptnode.onaudioprocess function takes the associated audioprocessingevent and uses it to loop through each channel of the input buffer, and each sample in each channel, and add a sm...
...n() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; }, function(e){"error with decoding audio data" + e.err}); } request.send(); } // give the node a function to process audio events scriptnode.onaudioprocess = function(audioprocessingevent) { // the input buffer is the song we loaded earlier var inputbuffer = audioprocessingevent.inputbuffer; // the output buffer contains the samples that will be modified and played var outputbuffer = audioprocessingevent.outputbuffer; // loop through the output channels (in this case there is only one) for (var channel = 0; channel < outputbuffer.numberofchannels; channel++) { var inputdata = inputbuffer.getchanneldata(channe...
BaseAudioContext.createScriptProcessor() - Web APIs
this node's output, defaults to 2. values of up to 32 are supported. important: webkit currently (version 31) requires that a valid buffersize be passed when calling this method. note: it is invalid for both numberofinputchannels and numberofoutputchannels to be zero. returns a scriptprocessornode. example the following example shows basic usage of a scriptprocessornode to take a track loaded via audiocontext.decodeaudiodata(), process it, adding a bit of white noise to each audio sample of the input track (buffer) and play it through the audiodestinationnode. for each channel and each sample frame, the scriptnode.onaudioprocess function takes the associated audioprocessingevent and uses it to loop through each channel of the input buffer, and each sample in each channel, and add a sm...
...n() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; }, function(e){"error with decoding audio data" + e.err}); } request.send(); } // give the node a function to process audio events scriptnode.onaudioprocess = function(audioprocessingevent) { // the input buffer is the song we loaded earlier var inputbuffer = audioprocessingevent.inputbuffer; // the output buffer contains the samples that will be modified and played var outputbuffer = audioprocessingevent.outputbuffer; // loop through the output channels (in this case there is only one) for (var channel = 0; channel < outputbuffer.numberofchannels; channel++) { var inputdata = inputbuffer.getchanneldata(channe...
CSSStyleSheet - Web APIs
eet given the selector to which the style applies and the style block to apply to the matching elements. this differs from insertrule(), which simply takes the textual representation of the entire rule as a single string. removerule() functionally identical to deleterule(); removes the rule at the specified index from the stylesheet's rule list. notes in some browsers, if a stylesheet is loaded from a different domain, accessing cssrules results in securityerror. a stylesheet is associated with at most one document, which it applies to (unless disabled). a list of cssstylesheet objects for a given document can be obtained using the document.stylesheets property. a specific style sheet can also be accessed from its owner object (node or cssimportrule), if any. a cssstylesheet object is...
...ument, which it applies to (unless disabled). a list of cssstylesheet objects for a given document can be obtained using the document.stylesheets property. a specific style sheet can also be accessed from its owner object (node or cssimportrule), if any. a cssstylesheet object is created and inserted into the document's document.stylesheets list automatically by the browser, when a stylesheet is loaded for a document. as the stylesheet list cannot be modified directly, there's no useful way to create a new cssstylesheet object manually (although constructable stylesheet objects is coming to the web platform soon and is already supported in blink). to create a new stylesheet, insert a <style> or <link> element into the document. a (possibly incomplete) list of ways a stylesheet can be associate...
CanvasRenderingContext2D.drawImage() - Web APIs
raw the image in the destination canvas. this allows scaling of the drawn image. if not specified, the image is not scaled in height when drawn. exceptions thrown index_size_err if the canvas or source rectangle width or height is zero. invalid_state_err the image has no image data. type_mismatch_err the specified source element isn't supported. ns_error_not_available the image is not loaded yet. use .complete === true and .onload to determine when it is ready. examples drawing an image to the canvas this example draws an image to the canvas using the drawimage() method. html <canvas id="canvas"></canvas> <div style="display:none;"> <img id="source" src="https://udn.realityripple.com/samples/db/f374e9c6fc.jpg" width="300" height="227"> </div> javascript the s...
...ther than element.width and element.height. the same goes for videowidth and videoheight if the element is a <video> element, and so on. ...
Document: readystatechange event - Web APIs
living standard ...
... living standard ...
Introduction to the DOM - Web APIs
en of that document, which are the various elements in the web page. your dom programming may be something as simple as the following, which displays an alert message by using the alert() function from the window object, or it may use more sophisticated dom methods to actually create new content, as in the longer example below. ...
... this following javascript will display an alert when the document is loaded (and when the whole dom is available for use): <body onload="window.alert('welcome to my home page!');"> another example. ...
FetchEvent.preloadResponse - Web APIs
to a response or otherwise to undefined. example this code snippet is from the navigation preload page. the serviceworkerglobalscope.onfetch event handler listens for the fetch event. when fired, pass a promise that back to the controlled page to fetchevent.respondwith(). this promise resolves to the first matching url request in the cache object. ...
...tching url request in the cache object. if no match is found, the code checks for a preloaded response. else it fetches a response from the network. addeventlistener('fetch', event => { event.respondwith(async function() { // respond from the cache if we can const cachedresponse = await caches.match(event.request); if (cachedresponse) return cachedresponse; // else, use the preloaded response, if it's there const response = await event.preloadresponse; if (response) return response; // else try the network. return fetch(event.request); }()); }); specifications specification status comment service workersthe definition of 'preloadresponse' in that specification. working draft initial definition. ...
FetchEvent.navigationPreload - Web APIs
d read-only property of the fetchevent interface returns a promise that resolves to the instance of navigationpreloadmanager associated with the current service worker registration. syntax var promise = fetchevent.navigationpreload value a promise that resolves to the instance of navigationpreloadmanager. ...
...the instance of navigationpreloadmanager. example the following example shows the implementation of a fetch event that uses a preloaded response. addeventlistener('fetch', event => { event.respondwith(async function() { // respond from the cache if we can const cachedresponse = await caches.match(event.request); if (cachedresponse) return cachedresponse; // else, use the preloaded response, if it's there const response = await event.preloadresponse; if (response) return response; // else try the network. return fetch(event.request); }()); }); specifications specification status comment service workersthe definition of 'navigationpreload' in that specification. working draft initial definition. browser compatibility...
Using Fetch - Web APIs
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 => response.json()) .then(result => { ...
... 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/posts', { method: 'post', body: fo...
FileRequest.onprogress - Web APIs
a callback function to be run repeatedly while the operation represented by a filerequest object is in progress. syntax instanceoffilerequest.onprogress = function; where instanceoffilerequest is a filerequest object and function is the javascript function to execute. each time the function callback is called, it gets an object as its first parameter. ...
...ects contain two properties: loaded a number representing the current amount of bytes processed by the operation. total a number representing the total amount of bytes that will be processed by the operation. example // assuming 'request' which is a filerequest object request.onprogress = function (status) { var progress = document.queryselector('progress'); progress.value = status.loaded; progress.max = status.total; } specification not part of any current specification. ...
FontFace.display - Web APIs
Web › API › FontFace › display
the display property of the fontface interface determines how a font face is displayed based on whether and when it is downloaded and ready to use. this property is equivalent to the css font-display descriptor. when this property is used, font loading has a timeline with three periods. 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. swap period if the font face is still not loaded, the fallback font will be shown. ...
...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. swap period if the font face is still not loaded, the fallback font will be shown. when the font face loads, the fallback will be swaped for the downloaded font. failure period if the font face still is not loaded, the fallback font will be shown and no swap will occur. syntax var display = fontface.display fontface.display = display value a cssomstring with one of the following values. 'auto': use the font display strategy provided by the user agent. 'block': gives the font face a short block period and an infinite swap period. the spec ...
FontFace - Web APIs
Web › API › FontFace
the fontface interface represents a single usable font face. it allows control of the source of the font face, being a url to an external resource, or a buffer; it also allows control of when the font face is loaded and its current status. constructor fontface() constructs and returns a new fontface object, built from an external resource described by an url or from an arraybuffer. properties this interface doesn't inherit any property. fontface.display a cssomstring that determines how a font face is displayed based on whether and when it is downloaded and ready to use. fontface.family a cssomstring that retrieves or sets the family of the font. it is equivalent to the font-family descriptor. fontface.featuresettings a cssomstring that retrieves or sets infrequently used font...
...whether and when it is downloaded and ready to use. fontface.family a cssomstring that retrieves or sets the family of the font. it is equivalent 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...
FontFaceSet.load() - Web APIs
Web › API › FontFaceSet › load
parameters font: a font specification using the css value syntax, e.g. "italic bold 16px roboto" text: limit the font faces to those whose unicode range contains at least one of the characters in text. this does not check for individual glyph coverage. ...
... parameters font: a font specification using the css value syntax, e.g. "italic bold 16px roboto" text: limit the font faces to those whose unicode range contains at least one of the characters in text. this does not check for individual glyph coverage. ...
FontFaceSet - Web APIs
fontfaceset.ready read only promise which resolves once font loading and layout operations have completed. events fontfaceset.onloading an eventlistener called whenever an event of type loading is fired, indicating a font-face set has started loading. ...
...led whenever an event of type loadingdone is fired, indicating that a font face set has finished loading. fontfaceset.onloadingerror an eventlistener called whenever an event of type loadingerror is fired, indicating that an error occurred whilst loading a font-face set. methods fontfaceset.add() adds a font to the font set. fontfaceset.check() a boolean that indicates whether a font is loaded, but doesn't initiate a load when it isn't. fontfaceset.clear() removes all manually-added fonts from the font set. css-connected fonts are unaffected. fontfaceset.delete() removes a manually-added font from the font set. css-connected fonts are unaffected. fontfaceset.load() returns a promise which resolves to a list of font-faces for a requested font. specifications specificat...
Fullscreen API - Web APIs
ides optional settings you can specify when calling requestfullscreen(). controlling access the availability of full-screen mode can be controlled using feature policy. the full-screen mode feature is identified by the string "fullscreen", with a default allow-list value of "self", meaning that full-screen mode is permitted in top-level document contexts, as well as to nested browsing contexts loaded from the same origin as the top-most document. see using feature policy to learn more about using feature policy to control access to an api. usage notes users can choose to exit full-screen mode simply by pressing the esc (or f11) key, rather than waiting for the site or app to programmatically do so. make sure you provide, somewhere in your user interface, appropriate user interface elements...
...gating to another page, changing tabs, or switching to another application using any application switcher (or alt-tab) will likewise exit full-screen mode. example in this example, a video is presented in a web page. pressing the return or enter key lets the user toggle between windowed and full-screen presentation of the video. view live examples watching for the enter key when the page is loaded, this code is run to set up an event listener to watch for the enter key. document.addeventlistener("keypress", function(e) { if (e.keycode === 13) { togglefullscreen(); } }, false); toggling full-screen mode this code is called by the event handler above when the user hits the enter key. function togglefullscreen() { if (!document.fullscreenelement) { document.documentelemen...
GlobalEventHandlers.onload - Web APIs
syntax target.onload = functionref; value functionref is the handler function to be called when the window’s load event fires. ...
...window.onload = load; </script> </head> <body> <p>the load event fires when the document has finished loading!</p> </body> </html> notes the load event fires at the end of the document loading process. at this point, all of the objects in the document are in the dom, and all the images, scripts, links and sub-frames have finished loading. there are also dom events like domcontentloaded and domframecontentloaded (which can be handled using eventtarget.addeventlistener()) which are fired after the dom for the page has been constructed, but do not wait for other resources to finish loading. specifications specification status comment html living standardthe definition of 'onload' in that specification. living standard initial definition ...
HTMLImageElement.alt - Web APIs
this may be the case because of an error, because the user has disabled the loading of images, or because the image simply hasn't finished loading yet. perhaps the most important reason to use the alt tag is to support accessibility, as the alt text may be used by screen readers and other assistive technologies to help differently-abled users make full use of your content. it will be read aloud or sent to the touch device, for example, to support visually impaired users. ...
...eone over the phone without mentioning that there's an image on the page. the alternate text is displayed in the space the image would occupy and should be able to take the place of the image without altering the meaning of the page. syntax htmlimageelement.alt = alttext; let alttext = htmlimageelement.alt; value a domstring which contains the alternate text to display when the image is not loaded or for use by assistive devices. the alt attribute is officially mandatory; it's meant to always be specified. if the image doesn't require a fallback (such as for an image which is simply decorative or an advisory icon of minimal importance), you may specify an empty string (""). for compatibility reasons, browsers generally will accept an image without an alt attribute, but you should try to g...
HTMLImageElement.crossOrigin - Web APIs
when fetching the image resource. if you don't specify crossorigin, the image is fetched without cors (the fetch no-cors mode). permitted values are: anonymous requests by the <img> element have their mode set to cors and their credentials mode set to same-origin. this means that cors is enabled and credentials are sent if the image is fetched from the same origin 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 ...
...sts 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.queryselector(".container"); function loadimage(url) { cons...
HTMLTrackElement - Web APIs
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 some way. some or all of the cues are likely missing and will not be obtained. htmltrackelement.track read only returns texttrack is the track element's text track data. m...
...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 (to initially display the track). you can then change the mode as desired later. specifications speci...
Using microtasks in JavaScript with queueMicrotask() - Web APIs
this.dispatchevent(new event("load")); }); } }; the problem introduced here is that by using a task in one branch of the if...else statement (in the case in which the image is available in the cache) but having promises involved in the else clause, we have a situation in which the order of operations can vary; for example, as seen below. ...
...low. element.addeventlistener("load", () => console.log("loaded data")); console.log("fetching data..."); element.getdata(); console.log("data fetched"); executing this code twice in a row gives the results shown in the table below: results when data isn't cached (left) vs. when it is found in the cache data isn't cached data is cached fetching data data fetched loaded data fetching data loaded data data fetched even worse, sometimes the element's data property will be set and other times it won't be by the time this code finishes running. we can ensure consistent ordering of these operations by using a microtask in the if clause to balance the two clauses: customelement.prototype.getdata = url => { if (this.cache[url]) { queuem...
Timing element visibility with the Intersection Observer API - Web APIs
build a mock blog which has a number of ads interspersed among the contents of the page, then use the intersection observer api to track how much time each ad is visible to the user. when an ad exceeds one minute of visible time, it will be replaced with a new one. although many aspects of this example will not match real world usage (in particular, the articles all have the same text and aren't loaded from a database, and there are just a handful of simple text-only ads that are selected from an array), this should provide enough understanding of the api to quickly learn how to apply the intersection observer api to your own site. there's a good reason why the notion of tracking visibility of ads is being used in this example. it turns out that one of the most common uses of flash or other sc...
...riable loremipsum contains the text we'll use for the body of all of our articles. obviously in the real world, you'd have some code to pull articles from a database or the like, but this does the job for our purposes. every article uses the same text; you could of course change that easily enough. buildcontents() creates a page with five articles. following every odd-numbered article, an ad is "loaded" and inserted into the page. articles are inserted into the content box (that is, the <main> element that contains all the site content) after being created using a method called createarticle(), which we'll look at next. the ads are created using a function called loadrandomad(), which both creates the ad and inserts it into the page. we'll see later that this same function can also replace an ...
Intersection Observer API - Web APIs
h 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 the result. implementing intersection detection in the past involved event handlers and loops calling methods like element.getbound...
...erform tasks or animation processes based on whether or not the user will see the result. implementing intersection detection in the past involved event handlers and loops calling methods like element.getboundingclientrect() to build up the needed information for every element affected. since all this code runs on the main thread, even one of these can cause performance problems. when a site is loaded with these tests, things can get downright ugly. consider a web page that uses infinite scrolling. it uses a vendor-provided library to manage the advertisements placed periodically throughout the page, has animated graphics here and there, and uses a custom library that draws notification boxes and the like. each of these has its own intersection detection routines, all running on the main thre...
LargestContentfulPaint - Web APIs
or text paint before user input on a web page. the timing of this paint is a good heuristic for when the main page content is available during load. properties largestcontentfulpaint.element the element that is the current largest contentful paint. largestcontentfulpaint.rendertime the time the element was rendered to the screen. may not be available if the element is a cross-origin image loaded without the timing-allow-origin header. largestcontentfulpaint.loadtime the time the element was loaded. largestcontentfulpaint.size the intrinsic size of the element returned as the area (width * height). largestcontentfulpaint.id the id of the element. this property returns an empty string when there is no id. largestcontentfulpaint.url if the element is an image, the request url of the...
.... // https://bugs.webkit.org/show_bug.cgi?id=209216 try { let lcp; const po = new performanceobserver((entrylist) => { const entries = entrylist.getentries(); const lastentry = entries[entries.length - 1]; // update `lcp` to the latest value, using `rendertime` if it's available, // otherwise using `loadtime`. (note: `rendertime` may not be available on // image elements loaded cross-origin without the `timing-allow-origin` header.) lcp = lastentry.rendertime || lastentry.loadtime; }); po.observe({type: 'largest-contentful-paint', buffered: true}); // send data to the server. addeventlistener('visibilitychange', function fn() { if (lcp && document.visibilitystate === 'hidden') { console.log('lcp:', lcp); removeeventlistener('visibilitychang...
Capabilities, constraints, and settings - Web APIs
it calls navigator.mediadevices.getusermedia(), passing in the constraints objects for the video and audio tracks. this returns a medias...
...he audio and video from a source matching the inputs (typically a webcam, although if you provide the right constraints you can get media from other sources). when the stream is obtained, it's attached to the <video> element so that it's visible on screen, and we grab the audio track and video track into the variables audiotrack and videotrack. then we set up a promise which resolves when the onloadedmetadata event occurs on the video element. when that happens, we know the video has started playing, so we call our getcurrentsettings() function (described above) to display the actual settings that the browser decided upon after considering our constraints and the capabilities of the hardware. if an error occurs, we log it using the handleerror() method that we'll look at farther down in this...
MessageChannel() - Web APIs
or of the messagechannel interface returns a new messagechannel object with two new messageport objects. note: this feature is available in web workers. syntax var channel = new messagechannel(); returns a newly created messagechannel object. example in the following code block, you can see a new channel being created using the messagechannel.messagechannel constructor. when the iframe has loaded, we pass port2 to the iframe using messageport.postmessage along with a message. the handlemessage handler then responds to a message being sent back from the iframe (using messageport.onmessage), putting it into a paragraph. messagechannel.port1 is listened to, to check when the message arrives. var channel = new messagechannel(); var para = document.queryselector('p'); var ifr = document.quer...
...ssage handler then responds to a message being sent back from the iframe (using messageport.onmessage), putting it into a paragraph. messagechannel.port1 is listened to, to check when the message arrives. var channel = new messagechannel(); var para = document.queryselector('p'); var ifr = document.queryselector('iframe'); var otherwindow = ifr.contentwindow; ifr.addeventlistener("load", iframeloaded, false); function iframeloaded() { otherwindow.postmessage('hello from the main page!', '*', [channel.port2]); } channel.port1.onmessage = handlemessage; function handlemessage(e) { para.innerhtml = e.data; } for a full working example, see our channel messaging basic demo on github (run it live too). specifications specification status comment html living stan...
MessageChannel.port1 - Web APIs
t attached to the context that originated the channel. note: this feature is available in web workers. syntax channel.port1; value a messageport object, the first port of the channel, that is the port attached to the context that originated the channel. example in the following code block, you can see a new channel being created using the messagechannel() constructor. when the <iframe> has loaded, we pass messagechannel.port2 to the <iframe> using messageport.postmessage along with a message. the handlemessage handler then responds to a message being sent back from the <iframe> (using messageport.onmessage), putting it into a paragraph. the handlemessage method is associated to the port1 to listen when the message arrives. var channel = new messagechannel(); var para = document.querysele...
... responds to a message being sent back from the <iframe> (using messageport.onmessage), putting it into a paragraph. the handlemessage method is associated to the port1 to listen when the message arrives. var channel = new messagechannel(); var para = document.queryselector('p'); var ifr = document.queryselector('iframe'); var otherwindow = ifr.contentwindow; ifr.addeventlistener("load", iframeloaded, false); function iframeloaded() { otherwindow.postmessage('hello from the main page!', '*', [channel.port2]); } channel.port1.onmessage = handlemessage; function handlemessage(e) { para.innerhtml = e.data; } specifications specification status comment html living standardthe definition of 'port1' in that specification. living standard ...
MessageChannel.port2 - Web APIs
the message is initially sent to. note: this feature is available in web workers. syntax channel.port2; value a messageport object representing the second port of the channel, the port attached to the context at the other end of the channel. example in the following code block, you can see a new channel being created using the messagechannel.messagechannel constructor. when the iframe has loaded, we pass port2 to the iframe using messageport.postmessage along with a message. the handlemessage handler then responds to a message being sent back from the iframe (using messageport.onmessage), putting it into a paragraph. messagechannel.port1 is listened to, to check when the message arrives. var channel = new messagechannel(); var para = document.queryselector('p'); var ifr = document.quer...
...ssage handler then responds to a message being sent back from the iframe (using messageport.onmessage), putting it into a paragraph. messagechannel.port1 is listened to, to check when the message arrives. var channel = new messagechannel(); var para = document.queryselector('p'); var ifr = document.queryselector('iframe'); var otherwindow = ifr.contentwindow; ifr.addeventlistener("load", iframeloaded, false); function iframeloaded() { otherwindow.postmessage('hello from the main page!', '*', [channel.port2]); } channel.port1.onmessage = handlemessage; function handlemessage(e) { para.innerhtml = e.data; } for a full working example, see our channel messaging basic demo on github (run it live too). specifications specification status comment html living stan...
MessagePort.onmessage - Web APIs
rt interface is an eventlistener, called whenever an messageevent of type message is fired on the port — that is, when the port receives a message. note: this feature is available in web workers. syntax channel.onmessage = function() { ... }; example in the following code block, you can see a new channel being created using the messagechannel.messagechannel constructor. when the iframe has loaded, we pass messagechannel.port2 to the iframe using messageport.postmessage along with a message. the handlemessage handler then responds to a message being sent back from the iframe using onmessage, putting it into a paragraph — messagechannel.port1 is listened to, to check when the message arrives. var channel = new messagechannel(); var para = document.queryselector('p'); var ifr = document.
...he handlemessage handler then responds to a message being sent back from the iframe using onmessage, putting it into a paragraph — messagechannel.port1 is listened to, to check when the message arrives. var channel = new messagechannel(); var para = document.queryselector('p'); var ifr = document.queryselector('iframe'); var otherwindow = ifr.contentwindow; ifr.addeventlistener("load", iframeloaded, false); function iframeloaded() { otherwindow.postmessage('hello from the main page!', '*', [channel.port2]); } channel.port1.onmessage = handlemessage; function handlemessage(e) { para.innerhtml = e.data; } for a full working example, see our channel messaging basic demo on github (run it live too). specifications specification status comment html living stan...
MessagePort.postMessage() - Web APIs
iple data items can be sent as an array. transferlist optional transferable objects to be transferred — these objects have their ownership transferred to the receiving browsing context, so are no longer usable by the sending browsing context. example in the following code block, you can see a new channel being created using the messagechannel.messagechannel constructor. when the iframe has loaded, we pass messagechannel.port2 to the iframe using window.postmessage along with a message. the handlemessage handler then responds to a message being sent back from the iframe using onmessage, putting it into a paragraph — messagechannel.port1 is listened to, to check when the message arrives. var channel = new messagechannel(); var para = document.queryselector('p'); var ifr = document.query...
...he handlemessage handler then responds to a message being sent back from the iframe using onmessage, putting it into a paragraph — messagechannel.port1 is listened to, to check when the message arrives. var channel = new messagechannel(); var para = document.queryselector('p'); var ifr = document.queryselector('iframe'); var otherwindow = ifr.contentwindow; ifr.addeventlistener("load", iframeloaded, false); function iframeloaded() { otherwindow.postmessage('hello from the main page!', '*', [channel.port2]); } channel.port1.onmessage = handlemessage; function handlemessage(e) { para.innerhtml = e.data; } for a full working example, see our channel messaging basic demo on github (run it live too). specifications specification status comment html living stan...
msFirstPaint - Web APIs
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. msfirstpaint is a read-only property which gets the time when the document loaded by the window object began to be displayed to the user. put another way, msfirstpaint utilizes the browser to measure when the first content completes being painted in the window. it is available from javascript and can be reported from the field. this proprietary property is specific to internet explorer and microsoft edge. syntax p = object.msfirstpaint; value an integer value that represents the time when t...
...zes the browser to measure when the first content completes being painted in the window. it is available from javascript and can be reported from the field. this proprietary property is specific to internet explorer and microsoft edge. syntax p = object.msfirstpaint; value an integer value that represents the time when the document began to be displayed or 0 if the document could not be loaded. the numerical value reported represents the number of milliseconds between the recorded time and midnight january 1, 1970 (utc). this property is supported only for documents displayed in ie9 standards mode. example the following example shows how to calculate the time that is required to request the document before the document begins to display for the user. var otiming = window.perform...
Navigator.getUserMedia() - Web APIs
invoked when the request for media access is approved. the function is called with one parameter: the mediastream object that contains the media stream. your callback can then assign the stream to the desired object (such as an <audio> or <video> element), as shown in the following example: function(stream) { var video = document.queryselector('video'); video.srcobject = stream; video.onloadedmetadata = function(e) { // do something with the video here. }; } errorcallback when the call fails, the function specified in the errorcallback is invokedwith a mediastreamerror object as its sole argument; this object is is modeled on domexception. see {anch("errors")}} below for a list of the errors which can occur. return value undefined. errors examples width and height ...
...vigator.getusermedia = navigator.getusermedia || navigator.webkitgetusermedia || navigator.mozgetusermedia; if (navigator.getusermedia) { navigator.getusermedia({ audio: true, video: { width: 1280, height: 720 } }, function(stream) { var video = document.queryselector('video'); video.srcobject = stream; video.onloadedmetadata = function(e) { video.play(); }; }, function(err) { console.log("the following error occurred: " + err.name); } ); } else { console.log("getusermedia not supported"); } ...
ProgressEvent.initProgressEvent() - Web APIs
t("progressevent") method. progressevent created that way are untrusted. note: this method has been dropped during the standard process. it has been deprecated and removed from most implementation. do not use it anymore, use the standard constructor, progressevent(), to create a synthetic progressevent syntax progress.initprogressevent(typearg, canbubblearg, cancelablearg, lengthcomputable, loaded, total); parameters typearg is a domstring identifying the specific type of animation event that occurred. the following values are allowed: value meaning loadstart the operation has started. progress the operation still is in progress. error the operation failed and didn't complete. abort the operation w...
...an flag indicating if the event can bubble (true) or not (false). cancelablearg is a boolean flag indicating if the event associated action can be avoided (true) or not (false). lengthcomputable is a 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 underlyi...
ProgressEvent - Web APIs
progressevent() creates a progressevent event with the given parameters. properties also inherits properties from its parent event. progressevent.lengthcomputable read only is a 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. 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 to...
...nt("progressevent") method. examples the following example adds a progressevent to a new xmlhttprequest and uses it to display the status of the request. var progressbar = document.getelementbyid("p"), client = new xmlhttprequest() client.open("get", "magical-unicorns") client.onprogress = function(pe) { if(pe.lengthcomputable) { progressbar.max = pe.total progressbar.value = pe.loaded } } client.onloadend = function(pe) { progressbar.value = pe.loaded } client.send() specifications specification status comment xmlhttprequestthe definition of 'progressevent' in that specification. living standard ...
ScriptProcessorNode.bufferSize - Web APIs
rns an integer representing both the input and output buffer size, in sample-frames. its value can be a power of 2 value in the range 256–16384. syntax var audioctx = new audiocontext(); var scriptnode = audioctx.createscriptprocessor(4096, 1, 1); console.log(scriptnode.buffersize); value an integer. example the following example shows basic usage of a scriptprocessornode to take a track loaded via audiocontext.decodeaudiodata(), process it, adding a bit of white noise to each audio sample of the input track (buffer) and play it through the audiodestinationnode. for each channel and each sample frame, the scriptnode.onaudioprocess function takes the associated audioprocessingevent and uses it to loop through each channel of the input buffer, and each sample in each channel, and add a sm...
...tion() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; }, function(e){"error with decoding audio data" + e.err}); } request.send(); } // give the node a function to process audio events scriptnode.onaudioprocess = function(audioprocessingevent) { // the input buffer is the song we loaded earlier var inputbuffer = audioprocessingevent.inputbuffer; // the output buffer contains the samples that will be modified and played var outputbuffer = audioprocessingevent.outputbuffer; // loop through the output channels (in this case there is only one) for (var channel = 0; channel < outputbuffer.numberofchannels; channel++) { var inputdata = inputbuffer.getchanneldata(channe...
ScriptProcessorNode.onaudioprocess - Web APIs
the audioprocess event that is dispatched to scriptprocessornode node types. an event of type audioprocessingevent will be dispatched to the event handler. syntax var audioctx = new audiocontext(); var scriptnode = audioctx.createscriptprocessor(4096, 1, 1); scriptnode.onaudioprocess = function() { ... } example the following example shows basic usage of a scriptprocessornode to take a track loaded via audiocontext.decodeaudiodata(), process it, adding a bit of white noise to each audio sample of the input track (buffer) and play it through the audiodestinationnode. for each channel and each sample frame, the scriptnode.onaudioprocess function takes the associated audioprocessingevent and uses it to loop through each channel of the input buffer, and each sample in each channel, and add a sm...
...n() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; }, function(e){"error with decoding audio data" + e.err}); } request.send(); } // give the node a function to process audio events scriptnode.onaudioprocess = function(audioprocessingevent) { // the input buffer is the song we loaded earlier var inputbuffer = audioprocessingevent.inputbuffer; // the output buffer contains the samples that will be modified and played var outputbuffer = audioprocessingevent.outputbuffer; // loop through the output channels (in this case there is only one) for (var channel = 0; channel < outputbuffer.numberofchannels; channel++) { var inputdata = inputbuffer.getchanneldata(channe...
ScriptProcessorNode - Web APIs
audionode. events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface: audioprocess fired when an input buffer of a scriptprocessornode is ready to be processed. also available via the onaudioprocess event handler property. examples the following example shows basic usage of a scriptprocessornode to take a track loaded via audiocontext.decodeaudiodata(), process it, adding a bit of white noise to each audio sample of the input track (buffer) and play it through the audiodestinationnode. for each channel and each sample frame, the scriptnode.onaudioprocess function takes the associated audioprocessingevent and uses it to loop through each channel of the input buffer, and each sample in each channel, and add a sm...
...tion() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; }, function(e){"error with decoding audio data" + e.err}); } request.send(); } // give the node a function to process audio events scriptnode.onaudioprocess = function(audioprocessingevent) { // the input buffer is the song we loaded earlier var inputbuffer = audioprocessingevent.inputbuffer; // the output buffer contains the samples that will be modified and played var outputbuffer = audioprocessingevent.outputbuffer; // loop through the output channels (in this case there is only one) for (var channel = 0; channel < outputbuffer.numberofchannels; channel++) { var inputdata = inputbuffer.getchanneldata(channe...
Storage Access API - Web APIs
d to request access to their first-party storage from the user agent. concepts and usage most browsers implement a number of storage access policies that restrict access to cookies and site data for embedded, cross-origin resources. these restrictions range from giving embedded resources under each top-level origin a unique storage space to outright blocking of storage access when resources are loaded in a third-party context. the semantics around third-party cookie blocking policies in particular differ from browser to browser, but the core functionality is similar: cross-origin resources embedded in a third-party context are not given access to the same cookies and site storage that they would have access to when loaded in a first-party context. these cookie blocking policies are known to ...
...ge, and will require the user to sign in on each site separately (or completely break) if those cookies are not available. in the case of breakage, site owners have often encouraged users to add their site as an exception or to disable the policy entirely. as a consequence, users who wish to continue to interact with embedded content are forced to greatly relax their blocking policy for resources loaded from all embedded origins and possibly across all websites. the storage access api is intended to solve this problem; embedded cross-origin content can request unrestricted access to its first-party storage on a site-by-site basis via the document.requeststorageaccess() method, and check whether it already has access via the document.hasstorageaccess() method. in addition, sandboxed <iframe>s c...
Using textures in WebGL - Web APIs
the above configuration, webgl requires all samples of npot textures to fail by returning transparent black: rgba(0,0,0,0). to load the image, add a call to our loadtexture() function within our main() function. this can be added after the initbuffers(gl) call. // load texture const texture = loadtexture(gl, 'cubetexture.png'); mapping the texture onto the faces at this point, the texture is loaded and ready to use. but before we can use it, we need to establish the mapping of the texture coordinates to the vertices of the faces of our cube. this replaces all the previously existing code for configuring colors for each of the cube's faces in initbuffers(). const texturecoordbuffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, texturecoordbuffer); const texturecoordinates = [ ...
... at this point, the rotating cube should be good to go. view the complete code | open this demo on a new page cross-domain textures loading of webgl textures is subject to cross-domain access controls. in order for your content to load a texture from another domain, cors approval needs to be be obtained. see http access control for details on cors. because webgl now requires textures to be loaded from secure contexts, you can't use textures loaded from file:/// urls in webgl. that means that you'll need a secure web server to test and deploy your code. for local testing, see our guide how do you set up a local testing server? for help. see this hacks.mozilla.org article for an explanation of how to use cors-approved images as webgl textures, with a self-contained example. note: cors su...
window.location - Web APIs
Web › API › Window › location
: location = 'http://www.example.com' is a synonym of location.href = 'http://www.example.com'. see location for all available properties. syntax var oldlocation = location; location = newlocation; examples basic example alert(location); // alerts "/docs/web/api/window/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. location.assign("http://www.mozilla.org"); // or location = "http://www.mozilla.org"; example #2: force reloading the current page from the server location.reload(true); example #3 consider the following example, which will reload the p...
... example #6: using bookmarks without changing the hash property: <!doctype html> <html> <head> <meta charset="utf-8"/> <title>mdn example</title> <script> function shownode (onode) { document.documentelement.scrolltop = onode.offsettop; document.documentelement.scrollleft = onode.offsetleft; } function showbookmark (sbookmark, busehash) { if (arguments.le...
Window.openDialog() - Web APIs
Web › API › Window › openDialog
the call to opendialog() returns immediately. if you want the call to block until the user has closed the dialog, supply modal as a windowfeatures parameter. note that this also means the user won't be able to interact with the opener window until he closes the modal dialog. syntax newwindow = opendialog(url, name, features, arg1, arg2, ...) newwindow the opened window url the url to be loaded in the newly opened window. name the window name (optional). see window.open() description for detailed information. features see window.open() for details. arg1, arg2, ... the arguments to be passed to the new window (optional). example var win = opendialog("http://example.tld/zzz.xul", "dlg", "", "pizza", 6.98); notes new features all - initially activates (or deactivates ("all=no"...
...ters from within dialog code, use the following scheme: var food = window.arguments[0]; var price = window.arguments[1]; note that you can access this property from within anywhere in the dialog code. (another example). returning values from the dialog since window.close() erases all properties associated with the dialog window (i.e. the variables specified in the javascript code which gets loaded from the dialog), it is not possible to pass return values back past the close operation using globals (or any other constructs). to be able to pass values back to the caller, you have to supply some object via the extra parameters. you can then access this object from within the dialog code and set properties on it, containing the values you want to return or preserve past the window.close() op...
window.postMessage() - Web APIs
able to window and worker contexts: if (crossoriginisolated) { // post sharedarraybuffer } else { // do something else } see also planned changes to shared memory which is starting to roll out to browsers (firefox 79, for example). example /* * in window a's scripts, with a being on <http://example.com:8080>: */ var popup = window.open(/* popup details */); // when the popup has fully loaded, if not blocked by a popup blocker: // this does nothing, assuming the window hasn't changed its location. popup.postmessage("the user is 'bob' and the password is 'secret'", "https://secure.example.net"); // this will successfully queue a message to be sent to the popup, assuming // the window hasn't changed its location. popup.postmessage("hello there!", "http://example.com"...
...nsistently unicode or punycode; for greatest compatibility check for both the idn and punycode values when using this property if you expect messages from idn sites. this value will eventually be consistently idn, but for now you should handle both idn and punycode forms. the value of the origin property when the sending window contains a javascript: or data: url is the origin of the script that loaded the url. using window.postmessage in extensions window.postmessage is available to javascript running in chrome code (e.g., in extensions and privileged code), but the source property of the dispatched event is always null as a security restriction. (the other properties have their expected values.) it is not possible for content or web context scripts to specify a targetorigin to communicat...
Window: unload event - Web APIs
bubbles no cancelable no interface event event handler property onunload it is fired after: beforeunload (cancelable event) pagehide the document is in the following state: all the resources still exist (img, iframe etc.) nothing is visible anymore to the end user ui interactions are ineffective (window.open, alert, confirm, etc.) an error won't stop the unloading workflow please note that the unload event also follows the document tree: parent frame unload will happen before child frame unload (see example below). ...
... specifications specification status comment ui eventsthe definition of 'unload' in that specification. working draft ...
WindowOrWorkerGlobalScope.setTimeout() - Web APIs
(1,000 ms) in inactive tabs. firefox implements this behavior since version 5 (see bug 633421, the 1000ms constant can be tweaked through the dom.min_background_timeout_value preference). chrome implements this behavior since version 11 (crbug.com/66078). firefox for android uses a timeout value of 15 minutes for background tabs since bug 736602 in firefox 14, and background tabs can also be unloaded entirely. firefox 50 no longer throttles background tabs if a web audio api audiocontext is actively playing sound. firefox 51 further amends this such that background tabs are no longer throttled if an audiocontext is present in the tab at all, even if no sound is being played. these resolve a number of issues with apps which play note-based music not being able to time or synchronize the musi...
...firefox 55, tracking scripts (e.g. google analytics, any script url that firefox recognises as a tracking script through its tp lists) have been subject to further throttling. when running in the foreground, the throttling minimum delay is still 4ms. in background tabs, however, the throttling minimum delay is 10,000 ms, or 10 seconds, which comes into effect 30 seconds after a document has first loaded. the prefs that control this behaviour are: dom.min_tracking_timeout_value: 4 dom.min_tracking_background_timeout_value: 10000 dom.timeout.tracking_throttling_delay: 30000 late timeouts in addition to "clamping", the timeout can also fire later when the page (or the os/browser itself) is busy with other tasks. one important case to note is that the function or code snippet cannot be exec...
Sending and Receiving Binary Data - Web APIs
ns in line 5, which overrides the mime type, forcing the browser to treat it as plain 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-...
...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 text, but you can imagine the data being a binary file instead. var oreq = new xmlhttprequest(); oreq.open("post", url, true); oreq.onload = function (oevent) { // uploaded. }; var blob = new blob(['abc123'], {type: 'text/plain'}); oreq.send(blob); sending typed arrays as binary data you can send javascript typed arrays as binary data as well. var myarray = new arraybuffer(512); var longint8view = new uint8array(myarray); // generate some data for (var i=0; i< longint8view.length; i++) { longint8view[i] = i % 256; } var xhr = new xmlhttprequest; xhr.open("...
XMLHttpRequestEventTarget.onprogress - Web APIs
the xmlhttprequesteventtarget.onprogress is the function called periodically with information when an xmlhttprequest before success completely. syntax xmlhttprequest.onprogress = callback; values callback is the function to be called periodically before the request is completed. event event.loaded the amount of data currently transfered. event.total the total amount of data to be transferred. ...
...iodically with information when an xmlhttprequest before success completely. syntax xmlhttprequest.onprogress = callback; values callback is the function to be called periodically before the request is completed. event event.loaded the amount of data currently transfered. event.total the total amount of data to be transferred. ...
Web applications and ARIA FAQ - Accessibility
ce toolkits, including: dojo/dijit jquery ui fluid infusion google closure google web toolkit bbc glow yahoo! user interface library (yui) for more information about javascript toolkit accessibility: steve faulkner's wai-aria implementation in javascript ui libraries can you show me an example of aria in action? sure. here's the markup for a progress bar widget: <div id="percent-loaded" role="progressbar" aria-valuenow="75" aria-valuemin="0" aria-valuemax="100" /> this progress bar is built using a <div>, which is not very descriptive. unfortunately, there isn't a more semantic tag available to developers in html 4, so we need to include aria roles and properties. these are specified by adding attributes to the element. in this example, the role="progressbar" attribute informs...
...aluemin and aria-valuemax attributes specify the minimum and maximum values for the progress bar, and the aria-valuenow describes the current state of it. along with placing them directly in the markup, aria attributes can be added to the element and updated dynamically using javascript code like this: // find the progress bar <div> in the dom. var progressbar = document.getelementbyid("percent-loaded"); // set its aria roles and states, so that assistive technologies know what kind of widget it is. progressbar.setattribute("role", "progressbar"); progressbar.setattribute("aria-valuemin", 0); progressbar.setattribute("aria-valuemax", 100); // create a function that can be called at any time to update the value of the progress bar. function updateprogress(percentcomplete) { progressbar.seta...
ARIA - Accessibility
porated into html5, and developers should prefer using the correct semantic html element over using aria, if such an element exists. for instance, native elements have built-in keyboard accessibility, roles and states. however, if you choose to use aria, you are responsible for mimicking (the equivalent) browser behaviour in script. here's the markup for a progress bar widget: <div id="percent-loaded" role="progressbar" aria-valuenow="75" aria-valuemin="0" aria-valuemax="100"> </div> this progress bar is built using a <div>, which has no meaning. unfortunately, there isn't a more semantic tag available to developers in html 4, so we need to include aria roles and properties. these are specified by adding attributes to the element. in this example, the role="progressbar" attribute infor...
...nimum and maximum values for the progress bar, and the aria-valuenow describes the current state of it and therefore must be kept updated with javascript. along with placing them directly in the markup, aria attributes can be added to the element and updated dynamically using javascript code like this: // find the progress bar <div> in the dom. var progressbar = document.getelementbyid("percent-loaded"); // set its aria roles and states, // so that assistive technologies know what kind of widget it is. progressbar.setattribute("role", "progressbar"); progressbar.setattribute("aria-valuemin", 0); progressbar.setattribute("aria-valuemax", 100); // create a function that can be called at any time to update // the value of the progress bar. function updateprogress(percentcomplete) { progressba...
unicode-range - CSS: Cascading Style Sheets
the unicode-range css descriptor sets the specific range of characters to be used from a font defined by @font-face and made available for use on the current page. if the page doesn't use any character in this range, the font is not downloaded; if it uses at least one, the whole font is downloaded. syntax /* <unicode-range> values */ unicode-range: u+26; /* single codepoint */ unicode-range: u+0-7f; unicode-range: u+0025-00ff; /* codepoint range */ unicode-range: u+4??; /* wildcard range */ unicode-range: u+0025-00ff, u+4??; /* multiple values */ values single codepoint a single unicode character code point, for example u+26. codepoint range a range of unicode code points. so for example, u+0025-00ff means include all characters in the range u+0025 to...
...criptor is to allow the font resources to be segmented so that a browser only needs to download the font resource needed for the text content of a particular page. for example, a site with many localizations could provide separate font resources for english, greek and japanese. for users viewing the english version of a page, the font resources for greek and japanese fonts wouldn't need to be downloaded, saving bandwidth. formal definition related at-rule@font-faceinitial valueu+0-10ffffcomputed valueas specified formal syntax <unicode-range># examples using a different font for a single character in this example we create a simple html containing a single <div> element, including an ampersand, that we want to style with a different font. to make it obvious, we will use a sans-serif font,...
prefers-reduced-data - CSS: Cascading Style Sheets
ser agent implements this feature, although various operating systems do support such preferences and if this media query is ever implemented user agents will likely rely on the settings provided by the operating system. examples note: no browser currently implements this feature so the following example will not work. ...
...ments this feature, although various operating systems do support such preferences and if this media query is ever implemented user agents will likely rely on the settings provided by the operating system. examples note: no browser currently implements this feature so the following example will not work. ...
Using CSS animations - CSS: Cascading Style Sheets
he @keyframes at-rule describing the animation’s keyframes. animation-duration configures the length of time that an animation should take to complete one cycle. animation-timing-function configures the timing of the animation; that is, how the animation transitions through keyframes, by establishing acceleration curves. animation-delay configures the delay between the time the element is loaded and the beginning of the animation sequence. animation-iteration-count configures the number of times the animation should repeat; you can specify infinite to repeat the animation indefinitely. animation-direction configures whether or not the animation should alternate direction on each run through the sequence or reset to the start point and repeat itself. animation-fill-mode configures w...
...e: slidein; animation-iteration-count: 3; animation-direction: alternate; } @keyframes slidein { from { margin-left:100%; width:300% } to { margin-left:0%; width:100%; } } adding the animation event listeners we’ll use javascript code to listen for all three possible animation events. this code configures our event listeners; we call it when the document is first loaded in order to set things up. var element = document.getelementbyid("watchme"); element.addeventlistener("animationstart", listener, false); element.addeventlistener("animationend", listener, false); element.addeventlistener("animationiteration", listener, false); element.classname = "slidein"; this is pretty standard code; you can get details on how it works in the documentation for eventtarget...
cursor - CSS: Cascading Style Sheets
Web › CSS › cursor
; /* global values */ cursor: inherit; cursor: initial; cursor: unset; the cursor property is specified as zero or more <url> values, separated by commas, followed by a single mandatory keyword value. each <url> should point to an image file. the browser will try to load the first image specified, falling back to the next if it can't, and falling back to the keyword value if no images could be loaded (or if none were specified). each <url> may be optionally followed by a pair of space-separated numbers, which represent <x><y> coordinates. these will set the cursor's hotspot, relative to the top-left corner of the image. for example, this specifies two images using <url> values, providing <x><y> coordinates for the second one, and falling back to the progress keyword value if neither image c...
...f none were specified). each <url> may be optionally followed by a pair of space-separated numbers, which represent <x><y> coordinates. these will set the cursor's hotspot, relative to the top-left corner of the image. for example, this specifies two images using <url> values, providing <x><y> coordinates for the second one, and falling back to the progress keyword value if neither image can be loaded: cursor: url(one.svg), url(two.svg) 5 5, progress; values <url> a url(…) or a comma separated list url(…), url(…), …, pointing to an image file. more than one <url> may be provided as fallbacks, in case some cursor image types are not supported. a non-url fallback (one or more of the keyword values) must be at the end of the fallback list. see using url values for the cursor propert...
Getting Started - Developer guides
eived 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 response code. if (httprequest.status === 200) { ...
...me, '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 is repeated every 5 seconds, using a setinterval() call. the idea would be that a server-side script of some kind would continually update the text file with new timestamps, and our ...
Live streaming web audio and video - Developer guides
eaming audio and video on demand streaming technology is not used exclusively for live streams. it can also be used instead of the traditional progressive download method for audio and video on demand: there are several advantages to this: latency is generally lower so media will start playing more quickly adaptive streaming makes for better experiences on a variety of devices media is downloaded just in time which makes bandwidth usage more efficient streaming protocols while static media is usually served over http, there are several protocols for serving adaptive streams; let's take a look at the options. http for now, http is by far the most commonly supported protocol used to transfer media on demand or live. rtmp real time messaging protocol (rtmp) is a proprietary protocol d...
...a protocol invented by apple inc and supported on ios, safari and the latest versions of android browser / chrome. hls is also adaptive. hls can also be decoded using javascript, which means we can support the latest versions of firefox, chrome and internet explorer 10+. see this http live streaming javascript player. at the start of the streaming session, an extended m3u (m3u8) playlist is downloaded. this contains the metadata for the various sub-streams that are provided. streaming file format support browser dash hls opus (audio) firefox 32 ✓ [1] ✓ [2] ✓ 14+ safari 6+ ✓ chrome 24+ ✓ [1] ✓ opera 20+ ✓ [1] internet explorer 10+ ✓ 11 ✓ [2] fi...
<input type="color"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › color
you close the color picker, the <code>change</code> event fires, and we detect that to change every paragraph to the selected color.</p> javascript first, there's some setup. here we establish some variables, setting up a variable that contains the color we'll set the color well to when we first load up, and then setting up a load handler to do the main startup work once the page is fully loaded. ...
.../p> javascript first, there's some setup. here we establish some variables, setting up a variable that contains the color we'll set the color well to when we first load up, and then setting up a load handler to do the main startup work once the page is fully loaded. ...
<input>: The Input (Form Input) element - HTML: Hypertext Markup Language
Web › HTML › Element › input
nclude global html attributes and: attribute type or types description accept file hint for expected file type in file upload controls alt image alt attribute for the image type. ...
... 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 hidden, since hidden inputs cannot be focused. warning: automatically focusing a form control can confuse visually-impaired people using screen-reading technol...
Global attributes - HTML: Hypertext Markup Language
list of global attributes accesskey prov...
... list of global attributes accesskey provides a hint fo...
MIME types (IANA media types) - HTTP
most up-to-date and complete list at their media types page. important: browsers use the mime type, not the file extension, to determine how to process a url, so it's important that web servers send the correct mime type in the response's content-type header. if this is not correctly configured, browsers are likely to misinterpret the contents of files and sites will not work correctly, and downloaded files may be mishandled. structure of a mime type the simplest mime type consists of a type and a subtype; these are each strings which, when concatenated with a slash (/) between them, comprise a mime type. no whitespace is allowed in a mime type: type/subtype the type represents the general category into which the data type falls, such as video or text. the subtype identifies the exact kin...
...ugh any given user agent may support any or all of these, you should only use text/javascript. it's the only mime type guaranteed to work now and into the future. some content you find may have a charset parameter at the end of the text/javascript media type, to specify the character set used to represent the code's content. this is not valid, and in most cases will result in a script not being loaded. image types files whose mime type is image contain image data. the subtype specifies which specific image file format the data represents. only a few image types are used commonly enough to be considered safe for use on web pages: abbreviation file format mime type file extension(s) browser compatibility apng animated portable network graphics image/apn...
Configuring servers for Ogg media - HTTP
mation about possible media file types and the codecs used within them in our comprehensive guide to media types and formats on the web. in particular, the article on media container formats will be especially helpful when configuring serers to host media properly. handle http 1.1 byte range requests correctly in order to support seeking and playing back regions of the media that aren't yet downloaded, gecko uses http 1.1 byte-range requests to retrieve the media from the seek target position. in addition, gecko uses byte-range requests to seek to the end of the media (assuming you serve the content-length header) in order to determine the duration of the media. your server should accept the accept-ranges: bytes http header if it can accept byte-range requests. it must return 206: partial con...
...e 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 the duration of the video, gecko needs to ...
Content-Disposition - HTTP
in a multipart/form-data body, the http content-disposition general header is a header that can be used on the subpart of a multipart body to give information about the field it applies to. the subpart is delimited by the boundary defined in the content-type header. ...
...xt. header type response header (for the main body) general header (for a subpart of a multipart body) forbidden header name no syntax as a response header for the main body the first parameter in the http context is either inline (default value, indicating it can be displayed inside the web page, or as the web page) or attachment (indicating it should be downloaded; most browsers presenting a 'save as' dialog, prefilled with the value of the filename parameters if present). content-disposition: inline content-disposition: attachment content-disposition: attachment; filename="filename.jpg" as a header for a multipart body the first parameter in the http context is always form-data. additional parameters are case-insensitive and have arguments that use quo...
CSP: script-src-attr - HTTP
csp version 3 directive type fetch directive default-src fallback yes. if this directive is absent, the user agent will look for the script-src directive, and if both of them are absent, fallback to default-src directive. ...
...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. 'strict-dynamic' the strict-dynamic source expression specifies 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 allow-list or source expressions such as 'self' or 'unsafe-inline' are ignored. see script-src for an example. 'report-sample' requires a sample of the violating code to be included in the violation report. examples fallback to script-src if script-src-attr is absent, user agent falls back to the script-src directive, and if that is absent as...
Feature-Policy: unsized-media - HTTP
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 iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. 'none': the feature is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self'...
... contexts (iframes) in the same origin. the feature is not allowed in cross-origin documents in nested browsing contexts. 'none': the feature is disabled in top-level and nested browsing contexts. default value the default value for unsized-media is '*', that is unsized media elements are allowed for all origins by default. the page will re-flow every time an image with unknown dimensions is loaded. specifications specification status comment feature policy editor's draft initial definition. ...
HTTP headers - HTTP
Web › HTTP › Headers
nce for an encrypted and authenticated response, and that it can successfully handle the upgrade-insecure-requests directive. x-content-type-options disables mime sniffing and forces browser to use the type given in content-type. x-download-options the x-download-options http header indicates that the browser (internet explorer) should not display the option to "open" a file that has been downloaded from an application, to prevent phishing attacks as the file otherwise would gain access to execute in the context of the application. (note: related ms edge bug). x-frame-options (xfo) indicates whether a browser should be allowed to render a page in a <frame>, <iframe>, <embed> or <object>. x-permitted-cross-domain-policies specifies if a cross-domain policy file (crossdomain.xml) is allowe...
...in the request. accept-signature a client can send the accept-signature header field to indicate intention to take advantage of any available signatures and to indicate what kinds of signatures it supports. alt-svc used to list alternate ways to reach this service. date contains the date and time at which the message was originated. large-allocation tells the browser that the page being loaded is going to want to perform a large allocation. link the link entity-header field provides a means for serialising one or more links in http headers. it is semantically equivalent to the html <link> element. push-policy a push-policy defines the server behaviour regarding push when processing a request. retry-after indicates how long the user agent should wait before making a follow-up re...
Link prefetching FAQ - HTTP
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 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 backgro...
...k prefetching needs to be disabled then there must be something wrong with the implementation. we would rather improve the implementation if it does not work correctly, than expect users to locate and tweak some 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 p...
JavaScript modules - JavaScript
ape. in this example we've only made changes to our index.html and main.js files — the module exports remain the same as before. ...
...a module object, the class is then made a subfeature of the object, hence we now need to access the constructor with module. prepended to it, e.g. module.square( ... ). troubleshooting here are a few tips that may help you if you are having trouble getting your modules to work. feel free to add to the list if you discover more! we mentioned this before, but to reiterate: .js files need to be loaded with a mime-type of text/javascript (or another javascript-compatible mime-type, but text/javascript is recommended), otherwise you'll get a strict mime type checking error like "the server responded with a non-javascript mime type". if you try to load the html file locally (i.e. with a file:// url), you'll run into cors errors due to javascript module security requirements. you need to do your ...
background_color - Web app manifests
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. ...
... 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. ...
Critical rendering path - Web Performance
measuring how long an animation frame may take. the styles applied to each node increase the paint time, but removing style that increases the paint by 0.001ms may not give you the biggest bang for your optimization buck. remember to measure first. then you can determine whether it should be an optimization priority. optimizing for crp improve page load speed by prioritizing which resources get loaded, controlling the order in which 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 ar...
...controlling the order in which 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. ...
Populating the page: how browsers work - Web Performance
through the content available and request high priority resources like css, javascript, and web fonts. thanks to the preload scanner, we don't have to wait until the parser finds a reference to an external resource to request it. it will retrieve resources in the background so that by the time the main html parser reaches requested assets, they may possibly already be in flight, or have 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...
...ssl connection to when the page is interactive -- interactive being the point in time after the first contentful paint when the page responds to user interactions within 50ms. if the main thread is occupied parsing, compiling, and executing javascript, it is not available and therefore not able to responsd to user interactions in a timely (less than 50ms) fashion. in our example, maybe the image loaded quickly, but perhaps the anotherscript.js file was 2mb and our user's network connection was slow. in this case the user would see the page super quickly, but wouldn't be able to scroll without jank until the script was downloaded, parsed and executed. that is not a good user experience. avoid occupying the main thread, as demonstrated in this webpagetest example: in this example, the dom con...
Lazy loading - Web Performance
n 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. general code splitting javascript, css and html can be split into smaller chunks. this enables sending the minimal code required to provide value upfront, improving page-load times. the rest can be loaded on demand. entry point splitting:...
...) in order to view them. loading attribute the loading attribute on an <img> element (or the loading attribute on an <iframe>) can be used to instruct the browser to defer loading of images/iframes that are off-screen until the user scrolls near them. <img src="image.jpg" loading="lazy" alt="..." /> <iframe src="video-player.html" loading="lazy"></iframe> the load event fires when the eagerly-loaded content has all been loaded; at that time, it's entirely possible (or even likely) that there may be lazily-loaded images that are within the visual viewport that haven't yet loaded. you can determine if a given image has finished loading by examining the value of its boolean complete property. polyfill include this polyfill to provide support for older and currently incompatible browsers: lo...
Using dns-prefetch - Web Performance
why use dns-prefetch? when a browser requests 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. ...
...er than support for preconnect. browsers that don’t support preconnect will still get some added benefit by falling back to dns-prefetch. because this is an html feature, it is very fault-tolerant. if a non-supporting browser encounters a dns-prefetch hint—or any other resource hint—your site won’t break. you just won’t receive the benefits it provides. some resources such as fonts are loaded in anonymous mode. in such cases you should set the crossorigin attribute with the preconnect hint. if you omit it, the browser will only perform the dns lookup. ...
Web Performance
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 event handler on the app's main thread.performance budgetsa performance budget is a limit to prevent regressions. it can apply to a file, a file type, all files loaded on a page, a specific metric (e.g. time to interactive), a custom metric (e.g. time to hero element), or a threshold over a period of time. performance fundamentalsperformance means efficiency. in the context of open web apps, this document explains in general what performance is, how the browser platform helps improve it, and what tools and processes you can use to test and improve it.performa...
...timization, it's important to optimize to reduce causes of lacency and to test site performance emulating high latency to optimizer for users with lousy connections. this article explains what latency is, how it impacts performance, how to measure latency, and how to reduce it.using dns-prefetchdns-prefetch is an attempt to resolve domain names before resources get requested. this could be a file loaded later or link target a user tries to follow. beginner's tutorials the mdn web performance learning area contains modern, up-to-date tutorials covering performance essentials. start here if you are a newcomer to performance: web performance: brief overview overview of the web performance learning path. start your journey here. what is web performance? this article starts the modul...
Making PWAs work offline with Service workers - Progressive web apps (PWAs)
serviceworkercontainer.register() method. its contents reside in the sw.js file, and can be executed after the registration is successful. it's the only piece of service worker code that sits inside the app.js file; everything else that is service worker-specific is written in the sw.js file itself. lifecycle of a service worker when registration is complete, the sw.js file is automatically downloaded, then installed, and finally activated. installation the api allows us to add event listeners for key events we are interested in — the first one is the install event: self.addeventlistener('install', (e) => { console.log('[service worker] install'); }); in the install listener, we can initialize the cache and add files to it for offline use. our js13kpwa app does exactly that. first, ...
...after that, both arrays are merged using the array.prototype.concat() function. var gamesimages = []; for(var i=0; i<games.length; i++) { gamesimages.push('data/img/'+games[i].slug+'.jpg'); } var contenttocache = appshellfiles.concat(gamesimages); then we can manage the install event itself: self.addeventli...
Structural overview of progressive web apps - Progressive web apps (PWAs)
approach to server- or client-side rendering can be achieved with the streams api. with a little help from service workers, streams can greatly improve the way we parse content. the app shell model requires all the resources to be available before the website can start rendering. it's different with html, as the browser is actually streaming the data already and you can see when the elements are loaded and rendered on the website. to have the javascript actually work, however, it has to be downloaded in its entirety. the streams api allows developers to have direct access to data streaming from the server. if you want to perform an operation on the data (for example, adding a filter to a video), you no longer need to wait for all of it to be downloaded and converted to a blob (or whatever). in...
...wa features. the css the css for this simple example is also as plain as possible: it uses @font-face to load and use a custom font, and it applies some simple styling of the html elements. the overall approach is to have the design look good on both mobile (with a responsive web design approach) and desktop devices. app.js: the main app javascript the file app.js is run when the app is first loaded; its job is primarily to initialize the app, though it c can do other things as well. we'll look at how the app functions more closely in later articles in this guide. the first thing it does is to generate the app's displayed content using the following template: var template = "<article>\n\ <img src='data/img/slug.jpg' alt='name'>\n\ <h3>#pos. name</h3>\n\ <ul>\n\ <li><span>au...
mimeTypes.rdf corruption - SVG: Scalable Vector Graphics
r served incorrectly over the network (see the svg faq). if the blue square with the white cross displays when you load this scripting across embed demo, then you are not experiencing this problem. if it doesn't, then you almost certainly are. background mozilla decides if and how it can open files by using their media (mime) type. it obtains the media type for files in various ways. for files loaded over the network via http, it requires and uses the value assigned to the content-type http header. for files loaded locally, it first looks in a cache of filename extension to media type mappings (stored in a mozilla profile file called mimetypes.rdf), and if it doesn't find a media type there, it asks the operating system. actually, in mozilla firefox 1.5, the media type for files embedded into...
...ind a media type there, it asks the operating system. actually, in mozilla firefox 1.5, the media type for files embedded into html using the html <embed> and <object> tags is (unfortunately) obtained in the same way as it's obtained for local files instead of using the http headers as it should. this bug has been fixed in trunk builds. problems in the way mozilla obtains the media type for files loaded locally can occur in two ways. first, certain actions can cause the media types cache in mimetypes.rdf to associate a filename extension with the wrong media type. second, certain actions may cause the os to associate a filename extension with the wrong media type. if either of these things happen, then mozilla can end up with a media type for files that it doesn't recognize, but which the user k...
Types of attacks - Web security
m/withdraw?account=bob&amount=1000000&for=mallory"> now, if you are logged into your bank account and your cookies are still valid (and there is no other validation), you will transfer money as soon as you load the html that contains this image. ...
...post endpoints should not interchangeably accept get requests with parameters in the query s...
Using templates and slots - Web Components
only the first of those two <element-details> elem...
... the effect of composing different dom trees together.</span> <dl slot="attributes"> <dt>name</dt> <dd>the name of the slot.</dd> </dl> </element-details> <element-details> <span slot="element-name">template</span> <span slot="description">a mechanism for holding client- side content that is not to be rendered when a page is loaded but may subsequently be instantiated during runtime using javascript.</span> </element-details> <script> customelements.define('element-details', class extends htmlelement { constructor() { super(); const template = document .getelementbyid('element-details-template') .content; const shadowroot = this.attachs...
JavaScript/XSLT Bindings - XSLT: Extensible Stylesheet Language Transformations
javascript/xslt bindings javascript can run xslt transformations through the xsltprocessor object. once instantiated, an xsltprocessor has an xsltprocessor.importstylesheet() method that takes as an argument the xslt stylesheet to be used in the transformation. the stylesheet has to be passed in as an xml document, which means that the .xsl file has to be loaded by the page before calling xsltprocessor.importstylesheet(). this can be done via xmlhttprequest or xmldocument.load(). figure 1 : instantiating an xsltprocessor var xsltprocessor = new xsltprocessor(); // load the xsl file using synchronous (third param is set to false) xmlhttprequest var myxmlhttprequest = new xmlhttprequest(); myxmlhttprequest.open("get", "example.xsl", false); myxmlhttprequest.send(null); var...
...mlhttprequest.open("get", "example.xsl", false); myxmlhttprequest.send(null); var xslref = myxmlhttprequest.responsexml; // finally import the .xsl xsltprocessor.importstylesheet(xslref); for the actual transformation, xsltprocessor requires an xml document, which is used in conjunction with the imported xsl file to produce the final result. the xml document can be a separate xml file loaded as shown in figure 1, or it can be part of the existing page. to process part of a page's dom, it is necessary to first create an xml document in memory. assuming that the dom to be processed is contained by an element with the id example, that dom can be "cloned" using the in-memory xml document's document.importnode() method. document.importnode() allows transferring a dom fragment between docu...
WebAssembly Concepts - WebAssembly
d written by webassembly’s low-level memory access instructions. table: a resizable typed array of references (e.g. to functions) that could not otherwise be stored as raw bytes in memory (for safety and portability reasons). instance: a module paired with all the state it uses at runtime including a memory, table, and set of imported values. an instance is like an es2015 module that has been loaded into a particular global with a particular set of imports. the javascript api provides developers with the ability to create modules, memories, tables, and instances. given a webassembly instance, javascript code can synchronously call its exports, which are exposed as normal javascript functions. arbitrary javascript functions can also be synchronously called by webassembly code by passing in ...
...ries, tables, and instances. given a webassembly instance, javascript code can synchronously call its exports, which are exposed as normal javascript functions. arbitrary javascript functions can also be synchronously called by webassembly code by passing in those javascript functions as the imports to a webassembly instance. since javascript has complete control over how webassembly code is downloaded, compiled and run, javascript developers could even think of webassembly as just a javascript feature for efficiently generating high-performance 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...
Interacting with page scripts - Archive of obsolete content
for the sake of security, stability, and simplicity, this is usually what you want. you don't want arbitrary web pages to be able to access objects in content scripts, and you don't want objects created by content scripts to clash with objects created by page scripts. but sometimes, you will want to share objects between the two scopes. ...
addon-page - Archive of obsolete content
s "data" directory. note: this module has no effect on fennec. for pages like this, navigational elements such as the awesome bar, search bar, or bookmarks toolbar are not usually relevant and distract from the content you are presenting. the addon-page module provides a simple way to have a page which excludes these elements. to use the module import it using require(). after this, the page loaded from "data/index.html" will not contain navigational elements: var addontab = require("sdk/addon-page"); var data = require("sdk/self").data; require("sdk/tabs").open(data.url("index.html")); this only affects the page at "data/index.html": all other pages are displayed normally. ...
context-menu - Archive of obsolete content
(node.nodename);' + ' return true;' + '});' }); the content script is executed for every page that a context menu is shown for. it will be executed the first time it is needed (i.e. when the context menu is first shown and all of the declarative contexts for your item are current) and then remains active until you destroy your context menu item or the page is unloaded. handling menu item clicks in addition to using content scripts to listen for the "context" event as described above, you can use content scripts to handle item clicks. when the user clicks your menu item, an event named "click" is emitted in the item's content script. therefore, to handle an item click, listen for the "click" event in that item's content script like so: require("sdk/context-...
self - Archive of obsolete content
with a particular add-on. name this property contains the add-on's short name. it comes from the name property in the main package's package.json file. version this property contains the add-on's version string. it comes from the version property set in the package.json file in the main package. loadreason this property contains of the following strings describing the reason your add-on was loaded: install enable startup upgrade downgrade isprivatebrowsingsupported this property indicates whether or not the add-on supports private browsing. it comes from the private-browsing key in the add-on's package.json file. data the data object is used to access data that was bundled with the add-on. this data lives in the add-on's data/ directory, immediately below the package.json file. all f...
frame/utils - Archive of obsolete content
ocument, { uri: 'data:text/html,<script>console.log("running");</script>', allowjavascript: true }); } globals functions create(document, options) creates a xul browser element in a privileged document. parameters document : nsidomdocument options : object optional options: name type type string string that defines access type of the document loaded into it. defaults to "content". for more details and other possible values see documentation on mdn uri string uri of the document to be loaded into the new frame. defaults to about:blank. remote boolean if true separate process will be used for this frame, and all the following options are ignored. allowauth boolean whether ...
util/match-pattern - Archive of obsolete content
ches that url and any url prefixed with the pattern. example pattern example matching urls example non-matching urls "https://foo.com/*" https://foo.com/ https://foo.com/bar http://foo.com/ https://foo.com https://bar.foo.com/ a scheme followed by an asterisk matches all urls with that scheme. to match local files, use file://*, and to match files loaded from your add-on's data directory, use resource://. example pattern example matching urls "file://*" file://c:/file.html file:///home/file.png "resource://*" resource://my-addon-at-me-dot-org/my-addon/data/file.html "data:*" data:text/html,hi there regular expressions you can specify patterns using a regular expression: var { matchpatt...
jpm - Archive of obsolete content
xpi to the working directory if it passes validation. to get values for --api-key and --api-secret, you will need to create api credentials on addons.mozilla.org. on the amo key management page, these values are labeled "jwt_issuer" and "jwt_secret". here are some possible outcomes of running the sign command: your add-on passed validation, was signed by mozilla, and a new signed xpi was downloaded to your working directory. your add-on failed validation, was not signed, and you got a link to a detailed report. after fixing the validation errors, you can run the command again. you add-on passed validation but it could not be automatically signed because your add-on is listed. listed add-ons will require a manual review before they can be signed. your add-on at this exact version number a...
Creating annotations - Archive of obsolete content
data.url('selector.js')], onattach: function(worker) { worker.postmessage(annotatorison); selectors.push(worker); worker.port.on('show', function(data) { console.log(data); }); worker.on('detach', function () { detachworker(this, selectors); }); } }); make sure the name you use to load jquery matches the name of the jquery version you downloaded. the page-mod matches all pages, so each time the user loads a page the page-mod emits the attach event, which will call the listener function we've assigned to onattach. the handler is passed a worker object. each worker represents a channel of communication between the add-on code and any content scripts running in that particular page context. for a more detailed discussion of the way page-mo...
Overview - Archive of obsolete content
oved widget api and no longer works with firefox. the widget api is deprecated from firefox 29 onwards. please see the ui module for replacements. in particular, for a simple button, try the action button or toggle button apis, and for a more complex widget try the toolbar or sidebar apis. the annotator uses content scripts to build user interfaces, get user input, and examine the dom of pages loaded by the user. meanwhile the main module contains the application logic and mediates interactions between the different sdk objects. we could represent the basic interactions between the main module and the various content scripts like this: user interface the annotator's main user interface consists of a widget and three panels. the widget is used to switch the annotator on and off, and t...
Storing annotations - Archive of obsolete content
, data.url('list/annotation-list.js')], contentscriptwhen: 'ready', onshow: function() { this.postmessage(simplestorage.storage.annotations); }, onmessage: function(message) { require('sdk/tabs').open(message); } }); since this panel's content script uses jquery we will pass that in too: again, make sure the name of it matches the version of jquery you downloaded. when the panel is shown we send it the array of stored annotations. when the panel sends us a url we use the tabs module to open it in a new tab. finally we need to connect this to the widget's right-click message: var widget = widgets.widget({ id: 'toggle-switch', label: 'annotator', contenturl: data.url('widget/pencil-off.png'), contentscriptwhen: 'ready', contentscriptfile: data.
Modifying the Page Hosted by a Tab - Archive of obsolete content
k: 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 tabs = require("sdk/tabs"); require("sdk/ui/button/action").actionbutton({ id: "load-several", label: "lo...
Bootstrapped extensions - Archive of obsolete content
me:// uris with your content (using the override instruction). not all chrome.manifest instructions are supported in bootstrapped add-ons, for example you still cannot register xul overlays from a bootstrapped add-on. see the chrome.manifest documentation for details. in firefox 10 and later the chrome.manifest file located in the root of the add-on's xpi (i.e. a sibling of the install.rdf) is loaded automatically. in firefox 8 and 9 you had to load/unload the manifest manually using nsicomponentmanager.addbootstrappedmanifestlocation() and nsicomponentmanager.removebootstrappedmanifestlocation(). this feature was unavailable in firefox versions before 8. adding user interface manually if you decide to go ahead and try to develop a bootstrapped extension that modifies the application's user...
Bookmarks - Archive of obsolete content
id, aproperty, aisannotationproperty, avalue) { myextension.dosomething(); }, onitemvisited: function(abookmarkid, avisitid, time) {}, onitemmoved: function(aitemid, aoldparent, aoldindex, anewparent, anewindex) {}, queryinterface: xpcomutils.generateqi([components.interfaces.nsinavbookmarkobserver]) }; // an extension var myextension = { // this function is called when my add-on is loaded onload: function() { bmsvc.addobserver(myext_bookmarklistener, false); }, // this function is called when my add-on is unloaded onunload: function() { bmsvc.removeobserver(myext_bookmarklistener); }, dosomething: function() { alert("did something."); } }; see also nsinavbookmarksservice nsinavbookmarkobserver places using xpcom without chrome - bookmark observer ...
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 ...
Rosetta - Archive of obsolete content
it is also possible, in theory, to use ecmascript for a smaller task: parsing exotic programming languages (i.e., creating compilers). beyond ecmascript this is not the place for showing a full compiler written in ecmascript. we can show, however, a possible way to start from. the following code is nothing but the base for an extensible collection of compilers. but by default, no compilers are loaded. it relies on the fact that unrecognized mime types will be simply ignored: this allows us to manually parse them. for a fast overview on the code proposed here you can git clone https://github.com/madmurphy/rosetta.js, or, at your choice, directly download this .zip file. rosetta.js: library "use strict"; /*\ |*| |*| :: rosetta.js :: |*| |*| a possible, extensible collection of compilers...
Sidebar - Archive of obsolete content
bar"); // hide the sidebar, if one is showing sidebarui.hide(); avoid opening the sidebar on startup. users have been known to complain about this "feature", and if two or more extensions try to open their sidebars on startup, the user will see a flurry of sidebars opening and closing with which ever extension going last "winning". web panels sidebar content such as web pages can be safely loaded as sidebar in the "viewwebpanelssidebar". bookmarks with "load this bookmark in sidebar" checked in the properties open in the "viewwebpanelssidebar". a web page can use window.sidebar to create bookmark with that property. to open a page in the "viewwebpanelssidebar" from chrome code (browser/addon/extension) such as from menuitem, it can call: openwebpanel(atitle, auri); accessing the sideba...
Common Pitfalls - Archive of obsolete content
s 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 principal that the uri originates from as the first argument and an nsiuri object representing the uri as ...
Communication between HTML and your extension - Archive of obsolete content
// 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.customreceived, false); since the event is dispatched after the element in the html is updated by the statuschanged function, the element that extension is looking ...
Creating custom Firefox extensions with the Mozilla build system - Archive of obsolete content
are to be used directly by other modules. the easiest way to accomplish the latter is to use inline implementations for all methods so you don't have any additional linking dependencies. otherwise you will have to link statically to your module if you use these public headers in other modules. personally i would discourage this practice (among other things, static linking means the same code gets loaded more than once into memory, and the code won't be available from javascript or other non-c++ languages) and encourage the use of xpcom wherever possible. the makefile in the public/ directory should follow this model: depth = ../../.. topsrcdir = @top_srcdir@ srcdir = @srcdir@ vpath = @srcdir@ include $(depth)/config/autoconf.mk module = myextension xpidl_module =...
Enhanced Extension Installation - Archive of obsolete content
possible to order install locations using the priority property on an install location object. this determines whether or not an extension from one install location can "trump" the same extension installed at a different install location. user action requested notifications are now sent with the em-action-requested topic through the observer service: item-installed an item has just been downloaded and configured for installation for the first time. item-upgraded a new version of an installed item has been downloaded and configured for installation. item-uninstalled an item has been configured for uninstallation. item-enabled an item has been configured for enabling. item-disabled an item has been configured for disabling. things this upgrade does not do replace rdf/xml as a ...
Inline options - Archive of obsolete content
pref attribute, otherwise the oninputchanged will not trigger. some discussion on the subject at stackoverflow: how to use addeventlistener on inputchanged of inline options display notifications if you want to use the settings ui for anything more than storing preferences, then you will probably need to initialize them when they first appear. you can't do this until your options xul has been loaded into the add-on manager window, so you should listen for the addon-options-displayed notification to initialize your settings. for example: var observer = { observe: function(asubject, atopic, adata) { if (atopic == "addon-options-displayed" && adata == "my_addon@my_domain") { var doc = asubject; var control = doc.getelementbyid("myaddon-pref-control"); control.value = "t...
Multiple item extension packaging - Archive of obsolete content
from the release of firefox 53, multiple item extension packages are no longer supported and will not load. as a consequence, these packages are no longer accepted by amo. a multiple item package provides the ability to package multiple installable bundles which can then be downloaded and installed by a user, or provided pre-packaged with an application or by an external program. every multiple item package must provide an install.rdf file (not old-style install.js!) and has the same requirements as an extension except as noted below. there is currently no feature to prevent or warn the user when installing an older version of an extension. multiple item package file layout the multiple item package file layout is a simplified form of an installable bundle and requires a file exte...
Chapter 5: Let's build a Firefox extension - Archive of obsolete content
his isn’t a requirement for extension development, but i recommend it as a way to work more efficiently. preference description value nglayout.debug.disable_xul_cache (not present in firefox 3.5+) ordinarily, firefox will cache xul documents after they have been read in once, to speed subsequent displays. disabling this cache forces xul documents to be reloaded any every time they are displayed. true browser.dom.window.dump.enabled (not present in firefox 3.5+) enables use of the dump method for debugging. refer to the “javascript debugging methods” sidebar. true javascript.options.showinconsole (present in firefox 3.5+) outputs javascript errors to the error console. true javascript.option...
Appendix A: Add-on Performance - Archive of obsolete content
ines: do not load or run code before it’s needed. add-ons can have extra features that are only available depending on user preferences. other add-ons have most of their features depend on a user being logged in to a service. don’t load at startup something you won’t need at the time. javascript code modules. use them. jsm provide the cleanest way to separate js into modules that can be loaded on request, unlike chrome scripts which are generally loaded with the overlay at startup. keep as much of your code in jsm, make it as modular as you can, and only load modules as you require them. if your add-on is too simple for jsm, don’t worry 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 10...
Getting Started with Firefox Extensions - Archive of obsolete content
take a closer look at it. extension contents you may have noticed that the extension file you installed is named xulschoolhello1.xpi. xpi (pronounced "zippy") stands for cross-platform installer, because the same installer file can work on all platforms firefox supports. xpis are simply zip files, but firefox recognizes the xpi extension and triggers the installation process when an xpi file is loaded. to look into the xpi file you need to download it first, not install it. if the server triggers an install when clicking on a link or button, what you need to do is right click on the install link, and choose the save link as... option. decompress the xpi file in a convenient location. issue the following command to unzip the file on linux or mac os x: unzip xulschoolhello1.xpi -d xulschoolhe...
Observer Notifications - Archive of obsolete content
e text and the last input parameter is a string "hello". in a chrome browser overlay file, we register an observer to listen to the notification topic "xulschoolhello-test-topic" when the window loads. keep in mind that you have to remove observers that are not longer needed. not doing so will result in memory leaks. therefore, the registered observer is unregistered when the browser window is unloaded. /** * controls the browser overlay for the hello world extension. */ xulschoolchrome.browseroverlay = { /* observer service. */ _observerservice : null, /** * initializes this object. */ init : function() { this._observerservice = components.classes["@mozilla.org/observer-service;1"]. getservice(components.interfaces.nsiobserverservice); this._observerservice.a...
Setting Up a Development Environment - Archive of obsolete content
files involved, which gives you a good starting point when looking into the mozilla source. you can even change styles, attributes and execute javascript code in it, although that's not completely reliable. javascript debugger the name says it all. the venkman javascript debugger is a great way to trace execution of your javascript code. to debug extension and browser code, right-click on the loaded scripts panel and uncheck exclude browser files. the list of loaded scripts will grow long to include all of the scripts in firefox. having our file naming conventions prove very useful in this case. you can set breakpoints, step in and out of methods, and even get profiling information from javascript execution. you can inspect variables, keep track of watch expressions, and evaluate arbitrary j...
The Essentials of an Extension - Archive of obsolete content
here are usually more controls there. you have to be specially careful when picking access keys on an overlay. in our case, we can't use the letter "h" as an accesskey in the main menu item, because it would be the same as the access key in the help menu. same goes with "w" and the window menu on mac os. so we settled on the letter "l". dtd strings are resolved and set when the document is being loaded. if you request the label attribute value for the hello world menu using dom, you get the localized string, not the string key. you cannot dynamically change an attribute value with a new dtd key, you have to set the new value directly: let helloitem = document.getelementbyid("xulschoolhello-hello-menu-item"); // the alert will say "hello world!" alert(helloitem.getattribute("label")); // wro...
Performance best practices in extensions - Archive of obsolete content
tensions can do almost anything. there is a down side to this: poorly written extensions can have a severe impact on the browsing experience, including on the overall performance of firefox itself. this article offers some best practices and suggestions that can not only improve the performance and speed of your extension, but also of firefox itself. improving startup performance extensions are loaded and run whenever a new browser window opens. that means every time a window opens, your extension can have an impact on how long it takes the user to see the content they're trying to view. there are several things you can do to reduce the amount of time your extension delays the appearance of the user's desired content. load only what you need, when you need it don't load things during startup...
Session store API - Archive of obsolete content
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 is being restored by looking at the event's originaltarget field. there's not really a way to determine when the last tab has been restored unless you determine how many tabs need to b...
Firefox addons developer guide - Archive of obsolete content
cle. apostrophes are being done using curly apostrophes instead of straight ones as is done everywhere else in mdc. the stuff about installing the dom inspector (https://developer.mozilla.org/en/firefox_addons_developer_guide/let%27s_build_a_firefox_extension#install_the_dom_inspector) is not accurate for firefox 3 or later, since it's no longer included in the firefox installer and must be downloaded from amo. filenames should use <code> styling. this is available from the style drop-down menu in the editor. variable and function names use <code> styling. xpi should be in all caps instead of written as ("xpi"). method and function names should have parentheses after them. for example, here: https://developer.mozilla.org/en/firefox_addons_developer_guide/let's_build_a_firefox_extension#i...
Promises - Archive of obsolete content
"])) extension.userdisabled = true; }); json file storage this helper simplifies the use of json data storage files with asynchronous io. the jsonstore object must be instantiated with the base name of the storage file and, optionally, a json-compatible object to be used if the file does not yet exist. the constructor returns a promise which resolves when the file’s contents have been loaded. the contents of the file will be initially loaded into the json store’s data property. after any changes are made to this property, the save() method must be called to queue the changes to be written to disk. unless the flush() method is called, no writes will happen until a full second has elapsed between save() calls. the variable addon_id must be defined to the id of the add-on the code i...
Using the Stylesheet Service - Archive of obsolete content
ponents.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); var uri = ios.newuri("chrome://myext/content/myext.css", null, null); sss.loadandregistersheet(uri, sss.user_sheet); note: loadandregistersheet will load the stylesheet synchronously, so you should only call this method using local uris. determining whether a sheet has been loaded if you are writing an extension and adding your stylesheet in an onload handler, you'll want to see if your sheet has already been added. if you don't check, you will wind up adding your sheet once per window load. var sss = components.classes["@mozilla.org/content/style-sheet-service;1"] .getservice(components.interfaces.nsistylesheetservice); var ios = components.classes["...
An Interview With Douglas Bowman of Wired News - Archive of obsolete content
ing css to style the content inside tables. the sheer amount [sic] of redundant <font> tags inside every cell was probably enough to double file size. my initial attempts at the markup and css for the wired news design eliminated the majority of our tables, but left one master table to control the primary columns of each page. that approach meant that the content of every column would have to be loaded and calculated before it would be rendered in the browser window. that wasn't good enough. around that time, i started discovering great sites like glish.com and bluerobot.com. both presented and documented viable means of producing multi-column layouts without a single table. despite some initial setbacks with those approaches due to our own unique scenarios, it wasn't long before i discovered a...
Creating reusable content with CSS and XBL - Archive of obsolete content
you apply this technique in a simple demonstration. information: xbl bindings the structure provided by markup languages and css is not ideal for complex applications where parts need to be self-contained and reusable. you can place stylesheets in separate files, and you can place scripts in separate files. ...
cached - 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. ...
progress - Archive of obsolete content
ent 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. read only. loaded unsigned long (long) 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 c...
updateready - 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. ...
Index of archived content - Archive of obsolete content
ation extensions faq hostwindow installer scripting styling proxy ui pydom rdf api rdf datasource how-to reading textual data remote xul remote debugging rsyncing the cvs repository running windows debug builds downloaded from tinderbox sxsw 2007 presentations safe browsing safe browsing: design documentation safely loading uris same origin policy for xbl space manager detailed design space manager high level design standalone xpcom standard makefile header static analysis for windows code under linux stre...
JXON - Archive of obsolete content
oat(svalue); } if (isfinite(date.parse(svalue))) { return new date(svalue); } return svalue; } function objectify (vvalue) { if (vvalue === null) { return new (function() { this.tostring = function() { return "null"; } this.valueof = function() { return null; } })(); } return vvalue instanceof object ? vvalue : new vvalue.constructor(vvalue); } var atmpels = []; // loaded element nodes cache function getjxontree (oxmlparent) { var sprop, vcontent, vresult, nlength = 0, nlevelstart = atmpels.length, nchildren = oxmlparent.haschildnodes() ? oxmlparent.childnodes.length : 0, scollectedtxt = ""; for (var onode, nitem = 0; nitem < nchildren; nitem++) { onode = oxmlparent.childnodes.item(nitem); if (onode.nodetype === 4) { scollectedtxt += onode.nod...
MMgc - Archive of obsolete content
the number of private committed pages in the process, mmgc is the amount of memory gcheap has asked for from the os (not including jit). fixedmalloc vs. gc allocations are shown in the unmanaged vs. managed split. free is the amount of memory gcheap is holding onto that isn't in use by the mutator. other is the delta between private and mmgc, it includes things like system malloc, stacks, loaded library data areas etc. when this is enable this information is logged everytime we log something interesting. so far something interesting means an incremental mark cycle, a sweep or a drc reap. they are logged like this: [mem] sweep(21) reclaimed 910 whole pages (3640 kb) in 22.66 millis (2.4975 s) [mem] mark(1) 0 objects (180866 kb 205162 mb/s) in 0.88 millis (2.5195 s) [mem] drc reaped 1...
MCD, Mission Control Desktop, AKA AutoConfig - Archive of obsolete content
been compiled?) about:buildconfig build platform target i686-pc-linux-gnu build tools compiler version compiler flags gcc gcc version 3.4.3 20050227 (red hat 3.4.3-22.fc3) -wall -w -wno-unused -wpointer-arith -wcast-align -wno-long-long -pedantic -pthread -pipe c++ gcc version 3.4.3 20050227 (red hat 3.4.3-22.fc3) -fno-rtti -fno-exceptions -wall -wconversion -wpointer-arith -wcast-align -woverloaded-virtual -wsynth -wno-ctor-dtor-privacy -wno-non-virtual-dtor -wno-long-long -pedantic -fshort-wchar -pthread -pipe -i/usr/x11r6/include configure arguments --disable-mailnews --enable-extensions=cookie,xml-rpc,xmlextras,pref,transformiix,universalchardet,webservices,inspector,gnomevfs,negotiateauth --enable-crypto --disable-composer --enable-single-profile --disable-profilesharing --with-system-...
Automated testing tips and tricks - Archive of obsolete content
.js how to execute test code with chrome privileges using a chrome doc - see sbtests.xul in http://people.mozilla.com/~davel/scripts/ for an example firefox-bin -p sbtestprofile -chrome chrome://sbtests/content/ above code calls the quit function in quit.js to exit after test is finished how to detect content onload event from chrome use the domcontentloaded event chromewindow.addeventlistener('domcontentloaded',callbackfunction,false); ...
Compiling The npruntime Sample Plugin in Visual Studio - Archive of obsolete content
".dll" (i wasted hours on this - repeatedly) mimetype reflects the data type handled by the plugin. this is how webpages invoke your plugin. should either be like "application/x-vnd-yourorganization-yourfiletype" or be officially registered with iana (unlikely) or be a standard type (e.g. if you want to play mpeg files). file extension reflects the data type handled by the plugin, esp. when loaded from local disk on windows. build create a new project in visual studio for a win32 gui library (dll) (in .net 2003: win32 template, then switch to dll in application settings in the following dialog, export symbols too?)(in visual studio 2008, it is visualc++|win32|win32 project, then check dll in the wizard). if a wizard gives you a checkbox to create an empty project, then check it. othe...
Adding the structure - Archive of obsolete content
curity-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 class so they can be styled accordingly by the css stylesheet that defines these elements' ...
Finding the file to modify - Archive of obsolete content
ith mozilla that allows you to examine the dom of web pages and xul windows. to access it, go to the "tools" menu, select the "web development" submenu, then select the "dom inspector" item. the dom inspector will load in a new window. in the dom inspector window, go to the file menu, select the inspect a window submenu, then select the mozilla browser window item (named after the page currently loaded in the browser). the dom inspector will display the url of the xul file that defines the mozilla browser window, which is chrome://navigator/content/navigator.xul. a chrome url is a url used internally by mozilla to refer to files in the chrome subdirectory of the mozilla installation directory. chrome urls have paths that do not necessarily refer to a precise directory hierarchy. in this case t...
Creating a Microsummary - Archive of obsolete content
warning: microsummary support was removed in gecko 6.0 (firefox 6.0 / thunderbird 6.0 / seamonkey 2.3) a microsummary generator is a set of instructions for creating a microsummary from the content of a page. web pages can reference generators via <link rel="microsummary"> elements in their <head> elements. generators can also be independently downloaded and installed by users if they include a list of pages to which they apply. in this tutorial we're going to create a microsummary generator for the spread firefox home page that displays the current firefox download count along with the label fx downloads; for example: 174475447 fx downloads. we'll build the xslt transform sheet that converts that page into its microsummary, learn how to specify that the generator applies to that page...
Download Manager improvements in Firefox 3 - Archive of obsolete content
sidownloadmanager gives applications and extensions access to the download manager, allowing them to add and remove files to the download list, retrieve information about past and present downloads, and request notifications as to the progress of downloads. nsidownload describes a file in the download queue; these files may currently be queued for download, actively being downloaded, or finished being downloaded. nsidownloadprogresslistener applications and extensions implement this interface to be made aware of changes in the status of downloads. nsidownloadmanagerui implement this interface to replace or augment the download manager user interface. other download manager documentation download manager preferences this article li...
Drag and Drop JavaScript Wrapper - Archive of obsolete content
nddrop.js. you can include this file in your xul file with the script tag in the same way you would include your own scripts. the library also depends on another script library, which you should also include, usually at the top of your xul file. you can look at the contents of these files to see how drag and drop is done at a lower level. note that you can only use these libraries from within xul loaded via a chrome url. <script src="chrome://global/content/nsdraganddrop.js" /> <script src="chrome://global/content/nstransferable.js" /> this drag and drop library creates an object stored in the variable nsdraganddrop. the object contains a series of functions, one for each event handler (except for dragenter where it has nothing special to do). each of the functions takes two parameters, the fir...
Block and Line Layout Cheat Sheet - Archive of obsolete content
c_frame_and_view ns_frame_outside_children this flag is set if the combined area of a frame's children extend past the frame's bounding box. (what is a frame's "bounding box"?) if this flag is set, then <code>moverflowarea</code> will contain the total area of the frame, including the overflow. ns_frame_external_reference ns_frame_replaced_element ns_frame_generated_content ns_frame_has_loaded_images ns_frame_out_of_flow ns_frame_selected_content ns_frame_is_dirty ns_frame_is_unflowable an unflowable frame is an error condition; for example, due to system limitations. currently, the only way to get an unflowable frame is to have a frame tree that is "too deep". (see nsframe::isframetreetoodeep().) ns_frame_has_dirty_children ns_frame_has_view ns_frame_independent_selecti...
Layout System Overview - Archive of obsolete content
in incrementally, and invalidates the formatting of some of the frames that precede it, frame that have already been formatted. in this case the layout system has to detect that impact and reflow again the impacted frames. this is referred to as an incremental reflow. another responsibility of layout is to manage dynamic changes to the content model, changes that occur after the document has been loaded and (possibly) presented. these dynamic changes are caused by manipulations of the content model via the dom (generally through javascript). when a content element is modified, added or removed, layout is notified. if content elements have been inserted, new frames are created and formatted (and impacts to other frames are managed by performing further incremental reflows). if content is removed,...
Repackaging Firefox - Archive of obsolete content
partner repacks, please add it below, using the same style: localizable preferences browser.startup.homepage=<string> browser.startup.homepage_reset=<string> url for the default homepage, and what the homepage gets reset to when the user hits "restore to default" in the preferences. these should both be the same url. startup.homepage_welcome_url=<string> url to the first-run page. this is loaded in addition to the homepage, the very first time that firefox is run. browser.search.defaultenginename=<string> name of the default search engine. note that this does not change the order of the search engines in the drop-down, only selects the default. capitalization is significant. repackaging firefox once you have all the required pieces in place, all you need to do is launch the repackag...
Using microformats - Archive of obsolete content
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. predefined microformats firefox 3 provides definitions implementing several common microformats: adr represents an address (such as a street or mailing address). geo represents a geographical location using latitude and longit...
JavaScript crypto - Archive of obsolete content
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 case, the module is removed from the nss secmod.db. this function will issue a user prompt to confirm the operation before the add or delete actually occurs. parameters modulename name of the module. libraryfullpath the filename of the library prepended with its full path. cryptomechanismflags a bit vector indicating all cryptographic m...
Java in Firefox Extensions - Archive of obsolete content
taking into account the liveconnect conversion rules) for more complex cases, in which you need to call a specific constructor with arguments, you will need reflection. ...
Basics - Archive of obsolete content
onfocus()changing the focus of a tab. methods open(urlstring)opens a new tab in your browser with a defined url. urlurl to be openedstring jetpack.tabs.open("http://www.example.com/"); ...
slideBar - Archive of obsolete content
slidebaruri htmlhtml content for the featurehtml/xml urlurl to load content for the featureuri widthwidth of the content area and the selected slide sizeint persistdefault slide behavior when being selectedbool autoreloadautomatically reload content on selectbool onclickcallback when the icon is clickedfunction onselectcallback when the feature is selectedfunction onreadycallback when featured is loadedfunction an example: jetpack.slidebar.append({ url: "http://mozilla.com", width: 150, onclick: function(slide){ slide.icon.src = "chrome://branding/content/icon48.png"; }}); ...
statusBar - Archive of obsolete content
new item to the statusbar. many of the options are optional. syntax jetpack.statusbar.append(options); possible options are: url width (string/length) the width of the panel-item html (string) the html code which will be used inside the item onload (event) this event fires when the item was appended. its acutally not implemented in the current version. onready (event) occurs when the item was loaded onunload (event) triggers when the item was removed. example jetpack.statusbar.append({ html: 'hello <i>world</i>!', onready: function(widget){ $(widget).click(function(){ jetpack.tabs.open("http://www.jogkey.de"); }); } }); ...
Measuring add-on startup performance - Archive of obsolete content
ated using the same formula. the about:startup page shows 3 different time measurements: main, sessionrestored and firstpaint. main happens very early in the startup process and should not be affected by add-ons being installed. the firstpaint time should be roughly similar to what talos tests. this can vary between systems, though. sessionrestored is fired later in the process, when firefox has loaded all tabs from the saved session. ...
Metro browser chrome tests - Archive of obsolete content
s/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 body of the test contained in run(). the test file can contain other functions which will be ignored unless invoked by test(). gtests make use of promises and tasks for managing execution. test comp...
Microsummary XML grammar reference - Archive of obsolete content
name (required) a descriptive, human-readable name for the microsummary created by the generator. uri (optional) a valid uri uniquely identifying the generator. only relevant for generators dynamically created by firefox code and extensions. generators installed from the web via nssidebar::addmicrosummarygenerator are identified by the remote url from which they were downloaded, and firefox ignores the value of this attribute for them. child elements: <template> (required) defines how to transform pages into their microsummaries. <pages> (required) identifies the set of pages that the generator is able to summarize. <update> (optional) specifies how frequently firefox should update the microsummaries. the <template> element t...
Microsummary topics - Archive of obsolete content
s, use urns containing uuids generated by the nsuuidgenerator component. see generating a uuid in the nsiuuidgenerator documentation. you may also use another form appropriate to your extension. note: when web sites install generators via window.sidebar.addmicrosummarygenerator(), firefox sets their uri attribute to urn:source:sourceurl, where sourceurl is the url from which the generator was downloaded. in the future, firefox may access source urls to download updated versions of generators, so unless you are installing generators which are available from urls, you should not use this form for your programmatically-installed generators. differentiating between user-initiated and microsummary-related requests when firefox updates a microsummary generated by a microsummary generator add-on, it au...
Styling - Archive of obsolete content
simply add the webapp.css to the bundle and it will be injected into the web application, regardless of the platform or os. it is also possible to create platform-specific styles. in this scenario, the css file is specific to an os. this allows prism webapps to take on an os-specific look. ...
PyDOM - Archive of obsolete content
indow script-type="application/x-python" .../> html <meta http-equiv="content-script-type" content="application/x-python" /> should work (but possibly doesn't - see bug 100924). but addeventlistener within a <script type="application/x-python"> block does. almost python code can not be secured - so it will only run from trusted sources. this means you can only have python code in chrome. content loaded from anywhere other than a chrome:// url can not host python. it should be obvious why you don't want to run http://evil.com/something_evil.py in your browser! inside chrome, you can use python via either html or xul. related topics pyxpcom: create and use xpcom components with python python-spidermonkey pydom samples: sample applications that use pydom pythonext: a firefox/xulrunner extensio...
RDF Datasource How-To - Archive of obsolete content
l> </treeitem> </treehead> <!-- treechildren built _here_ --> </tree> </window> the important "magic attributes" have been called out in bold, above: datasources="rdf:my-datasource". this is a space-separated list that may include internal xpcom datasource "identifiers" (as described above) and uris for local or remote rdf/xml documents. each datasource that is listed will be loaded, and the assertions contained in the datasource will be made available to the tree control for display. ref="http://foo.bar.com/". this roots the graph in your content model. the tree tag will be treated as if it has the id attribute with a value http://foo.bar.com/. <template>...</template>. the xul template that is used to build content from the graph. starting with the resource that corres...
Rsyncing the CVS Repository - Archive of obsolete content
this is useful for faster diffs or for attempting to import it into another version control system. here's how to do it: rsync -az --delete --stats cvs-mirror.mozilla.org::mozilla ~/cvs-mirror this will mirror the cvs repository into ~/cvs-mirror. optionally, the --progress option will show the progress for each file, and a percentage of the total files that are transferred. at the time of this writing, this will take 2.8 gb of disk space. note that for using this copy, the nolocks line in cvsroot/config will need to be commented out, as it requires a modified cvs binary. ...
Same origin policy for XBL - Archive of obsolete content
the same origin policy used for xbl documents is different from the policy used for other content. this article provides a description of how the same origin policy for xbl works. when mozilla needs to decide whether or not xbl is allowed to be loaded, it looks at the nsiprincipal originating the load and the nsiuri to be loaded. determining the originating principal the principal originating the load is determined using the following steps: for external stylesheets (<link>, <?xml-stylesheet?>, user sheets, and ua sheets), it depends on where the sheet is loaded from, just like it would for an html document loaded from a similar source. for inline stylesheets (<style> and style attributes), the principal of the element node involved (meaning the <style> element or the element whose style attri...
Static Analysis for Windows Code under Linux - Archive of obsolete content
ches/series`; do cat .hg/patches/$file; done) |patch -p1 cd .. now, the gcc source with plugin supports is ready, we should now build a cross compiler from this source. and the instructions are exactly the same with the one here. follow that instructions strictly for making a cross compiler. build dehydra for cross-compiler build the dehydra plugin dehydra is a shared library which will be loaded by the above plugin-support gcc. build dehydra for a cross compiler has nothing difference with building one for a linux native compiler. so, please follow this link exactly. check the build make check if all tests past, you have gotten a workable dehydra. build treehydra build the treehydra plugin building treehydra for a cross compiler is something tricky. that is because the gcc with ...
Supporting per-window private browsing - Archive of obsolete content
ve created the channel directly yourself. you can use the nsiprivatebrowsingchannel interface for this purpose. the example below creates a channel to load a url, and forces it to be in private mode. var channel = services.io.newchannel("http://example.org", null, null); channel.queryinterface(components.interfaces.nsiprivatebrowsingchannel); channel.setprivate(true); // force the channel to be loaded in private mode similarly, xmlhttprequest objects created via createinstance(ci.nsixmlhttprequest) will often require explicit adjustment, since they have no context from which to derive a privacy status. var xhr = components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"].createinstance(components.interfaces.nsixmlhttpreqeust); var channel = xhr.channel.queryinterface(components.interfaces.ns...
Table Layout Regression Tests - Archive of obsolete content
ession-test menu the add new list...entry. select %moz_src%/layout/html/tests/block/rtest.lst. execute the baseline test shutdown the layoutdebugger execute mozilla -layoutdebug - p foo >selftest.txt execute the verify test make a note which tests have failed grep 'failed' selftest.txt (these are false positives, quite frequently they indicate reflow problems, pages showing differently when loaded from cache) make your changes to the source, recompile. execute mozilla -layoutdebug - p foo >outputfile.txt execute the verify test make a note which tests have failed grep 'failed' outputfile.txt check how many tests have failed and analyze your results: if the regression tests have failed at the same place as the previous diagnosed false positives => ignore try to figure out what the ot...
Tamarin Build System Documentation - Archive of obsolete content
dbot/slaves directory: cd build/buildbot/slaves copy the your platform scripts directory into the scripts directory and cd into the new scripts directory: cp -r mac-intel-10_5/scripts . ...
The Download Manager schema - Archive of obsolete content
rent state. see the constants list in the nsidownloadmanager documentation. referrer text the referrer for the download. entityid text the entity id from the nsiresumablechannel used to implement the download channel. this information is used to resume the download after it's been paused. currbytes integer the current number of bytes that have been downloaded. defaults to 0, may not be null. maxbytes integer the total number of bytes that need to be downloaded. defaults to -1, may not be null. mimetype text the mime type of the file. preferredapplication text the preferred application to use to open the file after the download is complete. preferredaction integer the action constant from nsim...
Tuning Pageload - Archive of obsolete content
ew things you should know. the data flows in gecko as follows: network -> necko -> parser -> content sink -> content model -> rendering model -> layout -> painting. nglayout.initialpaint.delay this is a preference that specifies a delay, in milliseconds, after the data from the server has started coming in. during this delay, the page that's coming in is not painted, unless it ends up fully loaded before the delay expires. the idea here is twofold.this reduces ugly visual jitter as the new page comes in by not starting painting till after we have a bunch of the data.this makes overall page load time shorter by not doing extra repaints very early on. content.interrupt.parsing this preference, when true, means that the content sink can tell the parser to stop for now and return to the eve...
Video presentations - Archive of obsolete content
o presentations that can help you learn how the mozilla codebase works and how to take advantage of its technology in your own applications and extensions. this article is a jumping-off point to help you find those presentations. architecture these presentations provide an architectural overview of the codebase. how pages are built using the dom this presentation describes how documents are loaded and the dom tree is constructed. (as quicktime; 198 mb) laying out and drawing documents (slides) this presentation describes how a document is laid out and painted to the display by the gecko engine. (as quicktime; 282 mb) community these presentations provide insight into the mozilla community and how the project works. the mozilla community (part 1, part 2) this presentation talks abo...
When To Use ifdefs - Archive of obsolete content
efs in use in the mozilla tree: platform/widget ifdefs, feature ifdefs, and application-specific ifdefs: platform/widget ifdefs the mozilla code will frequently need to differentiate between code for different platforms or widget sets. these ifdefs are generally always acceptable. the only time when they might be a problem is in cross-platform extension code and locales: since this code is downloaded on multiple platforms, platform-specific ifdefs are generally out of the question. for an example of platform-specfic ifdefs, see nscrt.h. feature ifdefs the mozilla code has many features that can be enabled or disabled by configure flags. for instance, it is possible to disable most of the xul rendering engine by specifying --disable-xul when configuring the build. when adding ifdefs that im...
Anonymous Content - Archive of obsolete content
ints. when nested, it inherits from the innermost anonymous parent. binding stylesheets a binding file can load stylesheets using the stylesheet element. by default these stylesheets apply to the bound element and to all anonymous content generated by all bindings attached to the bound element. these sheets have the same origin as the sheet with the rule responsible for the binding. stylesheets loaded by bindings that are attached using the dom are treated as author-level sheets. [editor's note: binding inheritance complicates this cascade, since an author-level dom binding could inherit from a user-level binding. if both load sheets, what level do those sheets belong to in the cascade?] sheets are always walked from the innermost scope to the outermost scope. with this ordering a binding th...
Elements - Archive of obsolete content
document. the stylesheet tag must be inside the resources tag. id - the id attribute is a document-unique identifier. src - the url of the style sheet to apply to the binding content. image <!element image empty> <!attlist image id id #implied src uri #required > declares an image resource used by the binding. the image is loaded as soon as the binding is used. you can use this to preload a number of images for later use. the image tag must be inside the resources tag. id - the id attribute is a document-unique identifier. src - the url of the image to load. ...
XML in Mozilla - Archive of obsolete content
s simply a wrapper for fixptr xpointer xpath1() scheme obsolete since gecko 1.9.1 internet-draft document.load(), document.async part of dom level 3 load & save module, a w3c working draft xhtml we have reasonable xhtml support, most things should work. we treat xhtml documents differently depending on the mime type (or file suffix if files are loaded from local discs). files that go through the html code path are not checked for well-formedness. you will also notice not all xhtml features are supported when you exercise the html code path. mime type file suffix code path text/xml application/xml application/xhtml+xml xml xht xhtml xml text/h...
Unix stub installer - Archive of obsolete content
he installer in the src2 directory as well). go to mozilla/xpinstall/packager/unix. on the shell prompt type "perl deliver.pl". now you will find an installer *and* the xpcom.xpi and other debug xpis delivered to mozilla/installer/raw. debug using "gdb mozilla-installer-bin" and set a breakpoint at xpi_init(). you can step into the xpinstall engine through the xpistub once the xpistub dll is loaded. how do i add an installer package to the unix installer? adding a package involves a few steps: add a section named for your <component> to the packages-unix manifest that describes which files from dist belong to which module. for example, see the xpcom section that lists all the shared libraries as seen in dist. these are eventually zipped with the directory structure preserved. read the...
Install Wizards (aka: Stub Installers) - Archive of obsolete content
n 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. ...
Install script template - Archive of obsolete content
l error values used by the cycore developers (www.cycore.com) who helped make this install script var exceptionoccurederror = -4711; var winregisnullerror = -4712; var invalidrootkeyerror = -4713; var registrykeynotwritableerror = -4714; //initinstall block //the installation is initialized here -- if we fail here, cancel the installation // initinstall is quite an overloaded method, but i have invoked it here with three strings // which are globally defined err = initinstall(software_name, plid, version); if (err != 0) { // call initinstall again in case illegal characters in plid err = initinstall(software_name, software_name, version); if (err != 0) cancelinstall(err); } //addfiles to current browser block var pluginsfolder = getfolder("plugins"); //v...
Methods - Archive of obsolete content
returns the most recent non-zero error code. getwinprofile constructs an object for working with a windows .ini file. getwinregistry constructs an object for working with the windows registry. initinstall initializes installation for the given software and version. loadresources returns an object whose properties are localized strings loaded from the specified property file. logcomment add a comment line to the install log. patch applies a set of differences between two versions. performinstall finalizes the installation of the software. refreshplugins refreshes the list of plug-ins registered for the browser. registerchrome registers chrome with the chrome registr...
Properties - Archive of obsolete content
pi. 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. properties archive full local path of the archive after it is downloaded to the platform specific temp folder. (e.g. c:\temp\argstest.xpi) arguments args can be passed in through the triggering apis by attaching a ? and then the rg string to the xpi url: (e.g. startsoftwareupdate("http://webserver/argstest.xpi?argument_string") will result in the value of install.arguments being argument_string #). note that spaces in the arg string are legal. everything...
Learn XPI Installer Scripting by Example - Archive of obsolete content
note that in the example above, the installation is cancelled if the error code from the file addition process returns success (0), and also cancelled outside the main block if the earlier verification process is not successful. note also the comments that indicate the success of various steps in the process--including the performinstall and c...
datasources - Archive of obsolete content
e, the reference '#data' refers to an element with the id 'data'. if you plan on adding a datasource to an element but don't want one to be added right away, set this attribute to 'rdf:null'. this will make the element so that its contents can be generated from a datasource. otherwise, you cannot add one later. when the xul document is contained on a remote web site, the datasources may only be loaded from the same domain as the document. ...
disablefastfind - Archive of obsolete content
« xul reference homedisablefastfindtype: booleanput disablefastfind="true" on the root element of a xul document, which is intended to be loaded in a tab, to disable the find bar for the tab with this document. this is used to prevent the find bar from being displayed when it's not supported by the content (such as in the add-ons manager tab). ...
onpaneload - Archive of obsolete content
...
pending - Archive of obsolete content
...
Building accessible custom components in XUL - Archive of obsolete content
if (!gfocuscell) { gfocuscell = e.target.getelementsbytagname('label')[0]; } gfocuscell.focus(); } else { gfocuscell = e.target; } } function spreadsheet_click(e) { e.target.focus(); } </code> finally, we'll add two lines to our .xul file to link in the javascript file (accjax.js) and call the install_handlers function when the spreadsheet is loaded. <code> <window id="accjax" title="accjax spreadsheet" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" xmlns:x2="http://www.w3.org/tr/xhtml2" xmlns:wairole="http://www.w3.org/2005/01/wai-rdf/guiroletaxonomy#" xmlns:waistate="http://www.w3.org/2005/01/wai-rdf/guistatetaxonomy#" onload="install_handlers()" > <script src="accjax.js"/> </code> by...
XUL Events - Archive of obsolete content
repeatedly). attribute: onkeypress keyup the keyup event is sent to an element that has the focus when a key is released. attribute: onkeyup load this event is sent to the window after it has been fully loaded. you should place this event handler on the window element. this event may also be used on the image element, or an element that accepts an image attribute, and will be fired when the image has finished loading. for images, this event does not bubble up the element tree, so it will not conflict with the window's load event. attribute: onload ...
Uploading and Downloading Files - Archive of obsolete content
extual data, list of file-related error codes. the io object and stream objects can be used to upload files to servers in various ways. 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 dat...
addTabsProgressListener - Archive of obsolete content
« xul reference home addtabsprogresslistener( listener ) return type: no return value add a progress listener to the browser which will monitor loaded documents in all tabs in the tabbed browser. the progress listener should be based on the nsiwebprogresslistener interface with an additional "browser" argument as the first argument of every method, which is the browser (not <tabbrowser> = gbrowser) where the event occurred. see listening to events on all tabs for details. ...
addProgressListener - Archive of obsolete content
the progress listener should implement the nsiwebprogresslistener interface. ...
loadGroup - Archive of obsolete content
...
loadOneTab - Archive of obsolete content
t opens a new tab that loads a page with the specified url. the rest of the parameters are optional. this method works the same as addtab except for the loadinbackground parameter which allows you to choose whether to open the new tab in foreground or background. there's also no owner parameter as the owner tab is specified automatically. parameters inbackground if true the tab will be loaded in the background, if false the tab will be the newly selected tab. and if null or not specified, this parameter will default to the browser.tabs.loadinbackground preference. firefox 3.6 note the second form of this method was added in firefox 3.6; it adds the relatedtocurrent parameter, and allows the parameters to be specified by name, in any order. ...
loadTabs - Archive of obsolete content
« xul reference home loadtabs( uris, loadinbackground, replace ) loadtabs( uris, params ) return type: no return value loads a set of uris, specified by the array uris, into tabs. if loadinbackground is true, the tabs are loaded in the background, and if replace is true, the currently displayed tabs are replaced with the specified uris instead of adding new tabs. the properties of params are following: boolean inbackground boolean replace boolean allowthirdpartyfixup tab targettab number newindex object postdatas number usercontextid ...
loadURIWithFlags - Archive of obsolete content
« xul reference home loaduriwithflags( uri, flags, referrer, charset, postdata ) return type: no return value load a url into the document, with the specified load flags, the given referrer, character set, and post data. in addition to the flags allowed for the reloadwithflags method, the following flags are also valid: load_flags_is_refresh: this flag is used when the url is loaded because of a meta tag refresh or redirect. load_flags_is_link: this flag is used when the url is loaded because a user clicked on a link. the http referer header is set accordingly. load_flags_bypass_history: do not add the url to the session history. load_flags_replace_history: replace the current url in the session history with a new one. this flag might be used for a redirect. (see ns...
reloadWithFlags - Archive of obsolete content
« xul reference home reloadwithflags( flags ) return type: no return value reloads the document in the browser with the given load flags. the flags listed below may be used, which are all constants of the webnavigation property (or the nsiwebnavigation interface). you may combine flags using a or symbol ( | ). load_flags_none: no special flags. the document is loaded normally. load_flags_bypass_cache: reload the page, ignoring if it is already in the cache. this is the flag used when the reload button is pressed while the shift key is held down. load_flags_bypass_proxy: reload the page, ignoring the proxy server. load_flags_charset_change: this flag is used if the document needs to be reloaded because the character set changed. ...
PopupEvents - Archive of obsolete content
ill not fire when a menu is closed so you should make sure not to call any necessary code there. a better way is to just reinitialize the menu or popup in the popupshowing event. one such situation when the hiding events are not sent is when the menu is removed from the document. this is because there is no longer an element to send the events to. another situation is when the document is being unloaded. the popuphidden event the popuphidden event is fired after a popup has been closed. when a chain of menus is opened, that is, when a menu and at least one level of submenus is opened, first the popuphiding event will be fired on the lowest level of submenu. then that menu will be closed and the popuphidden event will be fired. this process will then repeat for the next highest level of menu unti...
contentPrincipal - Archive of obsolete content
...
currentURI - Archive of obsolete content
to change the url, use the loaduri method. ...
datasources - Archive of obsolete content
...
securityUI - Archive of obsolete content
...
Attribute Substitution - Archive of obsolete content
e datasource loads, the query and rules are examined with the new data as it arrives. this causes rules to create matches as the data loads. however, variables determined from a binding are evaluated using a much simpler process. the bug is that this code path for bindings doesn't handle the textnode element properly. thus, if you use a variable set in a binding, you must ensure the datasource is loaded before the template is built, or just rebuild the template. another possibilty is to rearrange the rdf such that the values, in this example, the descriptions, are specified before the containers. this issue is fixed in firefox 3 (mozilla 1.9) and later. « previousnext » ...
Static Content - Archive of obsolete content
comes 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, although usually you would place it first. note that the static content is always placed before the generated content, so the 'all' item will always be the first item in the menu. static content example let's look at another example, involving radio button...
XML Templates - Archive of obsolete content
when an xml source is desired, specify a querytype attribute on the root node of the template to the value xml. this indicates to the template builder that an xml source is being used as that the queries use syntax that is specific to xml. the datasources attribute should be set to the url of an xml document, either a local file or a remote web site. ...
Creating a Window - Archive of obsolete content
s that the items are placed in a column. this is the default value, so you may leave the attribute off entirely if you wish to have vertical orientation. xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> this line declares the namespace for xul, which you should put on the window element to indicate that all of its children are xul. note that this url is never actually downloaded. mozilla will recognize this url internally. <!-- other elements go here --> replace this comment block with other elements (the buttons, menus and other user interface components) to appear in the window. we'll add some of these in the next set of sections. </window> and finally, we need to close the window tag at the end of the file. opening a window in order to open a xul window, ther...
Introduction - Archive of obsolete content
ble in html5. the first three types all require an installation to be performed on the user's machine. however, these types of applications do not have security restrictions placed on them, so they may access local files and read and write preferences, for example. for extensions, the xul files and associated scripts and images used by an application would be packaged into a single file and downloaded and installed by the user. mozilla applications such as firefox provide an extension manager which allows packages to be installed without having to write a lot of complex code. what do i need to know to use this tutorial? you should have an understanding of html and at least a basic understanding of xml and css. here are some guidelines to keep in mind: xul elements and attributes should al...
More Button Features - Archive of obsolete content
the button below will have both a label and the image 'happy.png'. the image will appear to the left of the label. you can change this position by using two other attributes. this will be explained in a moment. ...
More Event Handlers - Archive of obsolete content
(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 work as expected. to use a load event, place an onload attribute on the window tag. call code within the load handler which will initialize the interface as necessary. there is also an unload event which is called once the window has closed, or in a browser context, when the page is switched to another url. you can use this event to save any change...
Tree View Details - Archive of obsolete content
t piece by piece. <window onload="init();" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <tree id="elementlist" flex="1"> <treecols> <treecol id="element" label="element" primary="true" flex="1"/> </treecols> <treechildren/> </tree> </window> we use a simple tree here with no data in the treechildren. the 'init' function is called when the window is loaded to initialize the tree. it simply sets the custom view by retrieving the tree and setting its 'view' property. we will define 'treeview' next. function init() { document.getelementbyid("elementlist").view = treeview; } the custom tree view will need to implement a number of methods, of which the important ones will be examined individually. first we'll define two structures to hold the data ...
Using Visual Studio as your XUL IDE - Archive of obsolete content
a for install manifest files (install.rdf) - installrdfschema.codeplex.com - from the same author as a xul schema. the codeplex-page provides some instructions for installing the schema, but there is an easier way. if you already have a xml or xul file opened, visual studio will add the menu item xml to the main menu. just use xml > schemas... to add the xul.xsd from the package that you have downloaded. the other xsd files will be added automatically. visual studio will use the schema based on the namespace, so make sure your window element uses the correct xul namespace http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul. 3. xbl if you are writing your own elements in xbl, you can download a xbl schema from mozilla.doslash.org/xblschema. grab the xsd version and add it in the same w...
Writing Skinnable XUL and CSS - Archive of obsolete content
on't import any other skin files, but that are only intended to be used in the context of another component's skin are also considered derived skin files, since they are implicitly importing information from the other component's skin. these sorts of files are typically used with reusable overlayable widgets (e.g., the sidebar). your css file should never import another skin file if your file is loaded by a xul overlay. css files that are used by xul overlays should never import the global skin (or any other skin for that matter). they are already derived skins and therefore should not inherit from global. they should instead rely on the context in which they will appear for color, font, and border information. for example, the sidebar should not import the global skin, since it could appear in...
XUL Changes for Firefox 1.5 - Archive of obsolete content
make it easy to set preferences without having to use code. for more information, see preferences system. bfcache mozilla now caches the page's dom, so that navigating back and forward does not reload the page, making navigation much more efficient. the pageshow and pagehide events are used when switching from a page in the cache, while the load and unload events are used only when the page is loaded or unloaded. for more information see using firefox 1.5 caching. tabindex the tabindex property is now applied to most elements. <radiogroup> setting the value property on the <radiogroup> element selects the <radio> element in the group with the corresponding value. dialog: defaultbutton property the <dialog> binding now supports the defaultbutton property. setting this property changes t...
XUL Questions and Answers - Archive of obsolete content
thers, like <listbox>, cannot be so tied, but one can always write a script that updates preferences explicitly, via nsiprefbranch interface. can a xul template be used for rss? you should be able to use a xul template to display feeds, although you may have to write the feed data to an rdf datasource first. ...
XUL element attributes - Archive of obsolete content
e, the reference '#data' refers to an element with the id 'data'. if you plan on adding a datasource to an element but don't want one to be added right away, set this attribute to 'rdf:null'. this will make the element so that its contents can be generated from a datasource. otherwise, you cannot add one later. when the xul document is contained on a remote web site, the datasources may only be loaded from the same domain as the document. dir type: one of the values below the direction in which the child elements of the element are placed. normal for scales, the scale's values are ordered from left to right (for horizontal scales) or from top to bottom (for vertical scales) for other elements, the elements are placed left to right or top to bottom in the order they appear in th...
Accessibility/XUL Accessibility Reference - Archive of obsolete content
<label control="butwrap2" value="a" /> <label control="butwrap2" value="button" /> </button> <button image="images/img.xbm" tooltiptext="<!--button text-->"/> note that in the third example, only the first label is read browser jaws 7.10 issues to use a browser element with html, the type="content" attribute should be specified. however, this attribute causes any xul loaded in the browser to have issues with jaws 7.10. we believe they are using the window class to determine that it is content rather than dialog, but does not support content mode for xul. therefore, with jaws 7.10, to use xul inside of a browser, the type attribute cannot not be used. caption see groupbox checkbox <checkbox label='<!--label text-->' /> ...
XUL accessibility tool - Archive of obsolete content
la.org. the version currently on xulplanet is compatible with the following xul applications: firefox 1.5+ thunderbird 3.0a+ recent sunbird builds recent songbird builds. it probably also works on seamonkey, but i haven't verified this. use to launch the tool after installation, look for an entry in the tools menu of the host application, or hit ctrl+alt+shift+f12. once the tool window has loaded, select either a local file, web url, or currently open window from the file menu to generate a xul report for that document. be aware that the report might take a little while to be ready depending on the complexity of the application being analyzed and the speed of your machine. future work the following things have been suggested or are planned for a future version of the tool: new tests: ...
image - Archive of obsolete content
Archive › Mozilla › XUL › image
element. validate type: one of the values below this attribute indicates whether to load the image from the cache or not. this would be useful if the images are stored remotely or you plan on swapping the image frequently. the following values are accepted, or leave out the attribute entirely for default handling: always the image is always checked to see whether it should be reloaded. never the image will be loaded from the cache if possible. properties accessibletype type: integer a value indicating the type of accessibility object for the element. src type: url gets and sets the value of the src attribute. inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, control...
menuitem - Archive of obsolete content
xul tutorial validate type: one of the values below this attribute indicates whether to load the image from the cache or not. this would be useful if the images are stored remotely or you plan on swapping the image frequently. the following values are accepted, or leave out the attribute entirely for default handling: always the image is always checked to see whether it should be reloaded. never the image will be loaded from the cache if possible. value type: string the string attribute allows you to associate a data value with an element. it is not used for any specific purpose, but you can access it with a script for your own use. be aware, however, that some elements, such as textbox will display the value visually, so in order to merely associate data with an e...
page - Archive of obsolete content
Archive › Mozilla › XUL › page
« xul reference home [ examples | attributes | properties | methods | related ] similar to a window, except it should be used for xul files that are to be loaded into an iframe. examples (example needed) attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width ...
toolbar - Archive of obsolete content
oxid property on the toolbar. the chromeclass-toolbar class may be used to create a toolbar where its visibility depends on the toolbar flag when opening the window with the window interface's open() method loads the specified resource into the browsing context (window, <iframe> or tab) with the specified name. if the name doesn't exist, then a new window is opened and the specified resource is loaded into its browsing context.">window.open() method. more information is available in the xul tutorial. note: starting in gecko 1.9.1, toolbar items are moved from the toolbarpalette and added to the toolbar when a toolbar is first displayed. in earlier versions, a copy of each item was created and placed on the toolbar. this means that the palette now only contains items not already in the toolb...
toolbarbutton - Archive of obsolete content
validate type: one of the values below this attribute indicates whether to load the image from the cache or not. this would be useful if the images are stored remotely or you plan on swapping the image frequently. the following values are accepted, or leave out the attribute entirely for default handling: always the image is always checked to see whether it should be reloaded. never the image will be loaded from the cache if possible. properties accesskey type: character gets and sets the value of the accesskey attribute. accessibletype type: integer a value indicating the type of accessibility object for the element. autocheck type: boolean gets and sets the value of the autocheck attribute. chec...
window - Archive of obsolete content
. this is used to hide chrome when showing in-browser ui such as the about:addons page, and causes the toolbars to be hidden, with only the tab strip (and, if currently displayed, the add-on bar) left showing. note: this has no effect if the tabs on top preference is turned off. disablefastfindtype: booleanput disablefastfind="true" on the root element of a xul document, which is intended to be loaded in a tab, to disable the find bar for the tab with this document. this is used to prevent the find bar from being displayed when it's not supported by the content (such as in the add-ons manager tab). drawintitlebar type: boolean if this attribute is true, the top of the window's content area will begin at the top edge of the title bar, instead of below the title bar. this allows the window t...
Creating XULRunner Apps with the Mozilla Build System - Archive of obsolete content
custom-built xulrunner and read the previous section then you're way ahead of the game. you simply need to place your application's root directory directly under the mozilla root on your disk. and what's more, you can skip the following section, partially compensating you for all that extra work you put in just now. see, it all balances out in the end! building with a prebuilt sdk once you've downloaded the xulrunner sdk, you'll need a .mozconfig of your own. here's an example for mccoy: # options for client.mk. mk_add_options moz_co_projects=browser mk_add_options moz_objdir=@topsrcdir@/../mccoybase # options for 'configure' (same as command-line options). ac_add_options --with-libxul-sdk=/path/to/xulrunner-sdk ac_add_options --enable-application=mccoy you still need to get the mozilla source...
Debugging a XULRunner Application - Archive of obsolete content
f you get an error that "function toopenwindowbytype is not defined" you may add the following function to your scripts (doesn't seem to be in the venkman overlay): function toopenwindowbytype(intype, uri) { var winopts = "chrome,extrachrome,menubar,resizable,scrollbars,status,toolbar"; window.open(uri, "_blank", winopts); } i can't see my pages, functions ... if your pages are not in the loaded script window, uncheck the menu item "debug\exclude browser files" and find them in open windows tab when opening a js file in venkman, the code is unformatted and i get the following error in the jsconsole... security error: content at x-jsd:source?location=chrome%3a%2f%2fvenkman%2fcontent%2fvenkman-overlay.js&instance=12 may not load or link to chrome://venkman/skin/venkman-source.css. note...
Make your xulrunner app match the system locale - Archive of obsolete content
this article is going to assume a lot of knowledge of xpcom and will be written for someone using python, but the ideas should be adaptable. also, this may not be the proper way to do this and it may not work for you in all cases. please update if there are more correct ways to do this. the first step is to get the code we're about to write to run before any of the locale specific resources are loaded. democracy does this by creating a command line handler called democracyclh, and then creating a new object of our pybridge component. the code described lives in the pybridge component's onstartup method which gets called automatically. the second step is to figure out the system locale. to be finished later. then set the locale preference. the following is python code to set this preference. f...
XULRunner - Archive of obsolete content
ntime package that can be used to bootstrap xul+xpcom applications that are as rich as firefox and thunderbird. it provides mechanisms for installing, upgrading, and uninstalling these applications. xulrunner also provides libxul, a solution which allows the embedding of mozilla technologies in other projects and products. releases until version 41, xulrunner could be downloaded from ftp.mozilla.org. firefox (from version 3) ships with a private xulrunner package, which can run any compatible xulrunner application using the -app switch: firefox -app application.ini is equivalent to xulrunner -app application.ini older builds are also available. overview development plan what xulrunner provides xulrunner faq nightly builds: un...
XUL Explorer - Archive of obsolete content
a xul validator and the error console are both available to help debug problems. the help menu provides access to xul information on mdc. ...
mozilla.dev.platform FAQ - Archive of obsolete content
or later (not 1.8.0.1, which had a bug that prevented this from working properly). q: when using xul elements <browser/> and <tabbrowser/> the javascript popup windows don't work out of the box, what needs to be implement? a: have the browser.chromeurl preference - this should be a xul document containing a <browser type="content-primary"> element in which the popup window's content should get loaded. visual studio express 2005 q: when i try to run xulrunner-stub.exe i get the error "this application failed to start because msvcr80.dll was not found." a: see bug 350616 ...
Mozilla.dev.apps.firefox-2006-09-29 - Archive of obsolete content
eltnzer announced that 'users running the bon echo 20060921 nightly build will be offered the chance to upgrade to a "new version"' firefox start up performance boris zbarsky recently performed some profiling of firefox's start up - these are some of the details discussions problem handling dmg files on mac discussion about why sometimes dmg files are not mounted correctly after they are downloaded. binding tab bar to new theme discussion about how to bind a new theme to a tab bar without losing its original binding. the distributor university students working on cache distribution project - looking for help for how to tap the http requests. there have been no responses so far. can't view keith olbermann videos a user inability to launch videos, worked fine for others, ended up being a f...
2006-09-29 - Archive of obsolete content
eltnzer announced that 'users running the bon echo 20060921 nightly build will be offered the chance to upgrade to a "new version"' firefox start up performance boris zbarsky recently performed some profiling of firefox's start up - these are some of the details discussions problem handling dmg files on mac discussion about why sometimes dmg files are not mounted correctly after they are downloaded. binding tab bar to new theme discussion about how to bind a new theme to a tab bar without losing its original binding. the distributor university students working on cache distribution project - looking for help for how to tap the http requests. there have been no responses so far. can't view keith olbermann videos a user inability to launch videos, worked fine for others, ended up being a f...
2006-10-20 - Archive of obsolete content
er - say reviewers a discussion revolving around the quality of rss readers in ie7, firefox and other assorted browsers. also a debate about which browser is "beating" which to a lesser extent further in the discussion. how to create firefox extension (chrome) to add images next to urls ? question regarding how to make a firefox extension that would insert an image next to all links in the loaded web pages similar to the mcafee siteadvisor extension. adding support for new uri scheme question regarding creating a new uri scheme for firefox on windows. helpful information was found here on mozillazine. meetings none this week. authors sara minchella (sara) dave manley (senemanley) back to summary list ...
2006-11-10 - Archive of obsolete content
ommand he receive an error saying "no such file or directory". he stated that he set is home variable to c:\mozilla, and is not sure what he is doing wrong. november 9th: jonathan watt responded to his posting stating that he must have the wrong line endings in his mozconfig or some other script fill that he is probably using to run. ...
2006-11-17 - Archive of obsolete content
out of the box and asks what needs to be implement. alex vincent ran into some difficulty with xulrunner extension manager not recognizing xulwidgets for verbosio? however he found out that it was a result of his flat-chrome version of xul widgets and works fine with the jarred-chrome version. boaz discuses the evolution of web browsers towards a more "application mode" whereas a web browser is loaded for the sole purpose of running a given website. boaz invites your comments xulrunner 1.8.0.4 is running a kiosk-type application on linux with 512mb, and there is the appearance of a significant memory leak. win2xul asks for any quick pointers, opinions, experience, suggestions or ideas on where xulrunner might leak memory bug 319654 was fixed on trunk recently. nickolay ponomarev lets us know...
NPN_DestroyStream - Archive of obsolete content
can give the user appropriate feedback. values: npres_done (most common): stream completed normally; all data was sent by the plug-in to the browser. npres_user_break: plug-in is terminating the stream due to a user request. npres_network_err: stream failed due to network problems. returns if successful, the function returns nperr_no_error. if unsuccessful, the plug-in is not loaded and the function returns an error code. for possible values, see error codes. description the plug-in calls the npn_destroystream() function to close and delete a stream. this stream can be either a stream that the browser created and passed to the plug-in in npp_newstream(), or a stream created by the plug-in through a call to npn_newstream(). see also npp_destroystream() npn_newstream() np...
NPN_Evaluate - Archive of obsolete content
evaluate the script in. npobj the scope object. script the script to evaluate. result on return, contains the value returned by the script. can't be null. returns true if the script was evaluated successfully, otherwise false. description the script is evaluated in the context of the window that the calling plugin instance (the <tt>npp</tt> argument) is loaded in. note: the caller must call npn_releasevariantvalue() to release the returned value when it's no longer needed. ...
NPN_GetURLNotify - Archive of obsolete content
http, ftp, news, or mailto. target name of the target window or frame, or one of several special target names. for values, see npn_geturl(). notifydata plug-in-private value for associating the request with the subsequent npp_urlnotify() call, which passes this value (see description below). returns if successful, the function returns nperr_no_error. if unsuccessful, the plug-in is not loaded and the function returns an error code. for possible values, see error codes. description npn_geturlnotify() works just like npn_geturl(), with one exception: npn_geturlnotify() notifies the plug-in instance upon successful or unsuccessful completion of the request by calling the plug-in's npp_urlnotify() function and passing it the notifydata value. npn_geturlnotify() typically handles the u...
NPN_GetValue - Archive of obsolete content
(mac only) npnvsupportscoregraphicsbool : (mac only) value function returns the name of the plug-in in the value parameter. gecko 1.9.2 note starting with gecko 1.9.2 (firefox 3.6), the variables npnvservicemanager, npnvdomelement, and npnvdomwindow are no longer supported. returns if successful, the function returns nperr_no_error. if unsuccessful, the plug-in is not loaded and the function returns an error code. for possible values, see error codes. description npn_getvalue returns the browser information set with npn_setvalue. the queried information is returned in the value parameter. unix the platform-specific values for this parameter are npnvxdisplay (the current display), npnvxtappcontext (the browser's xtappcontext), and npnvnetscapewindow (the browser topl...
NPN NewStream - Archive of obsolete content
stream); parameters the function has the following parameters: instance pointer to current plug-in instance. type mime type of the stream. target name of the target window or frame, or one of several special target names. for values, see npn_geturl. stream stream to be created by the browser. returns if successful, the function returns nperr_no_error. if unsuccessful, the plug-in is not loaded and the function returns an error code. for possible values, see error codes. description npn_newstream creates a new stream of data produced by the plug-in and consumed by the browser. the mime parameter is the mime type of the plug-in to create. a plug-in can create another instance of itself by specifying its own mime type and a new target name in a call to npn_newstream. the stream is return...
NPN_PostURLNotify - Archive of obsolete content
true: post the local file whose path is specified in buf, then delete the file. false: post the raw data in buf. notifydata plug-in-private value for associating the request with the subsequent npp_urlnotify call, which returns this value (see description below). returns if successful, the function returns nperr_no_error. if unsuccessful, the plug-in is not loaded and the function returns an error code. for possible values, see error codes. description npn_posturlnotify functions identically to npn_posturl, with these exceptions: npn_posturlnotify supports specifying headers when posting a memory buffer. npn_posturlnotify calls npp_urlnotify upon successful or unsuccessful completion of the request. for more information, see npn_posturl. npn_posturl...
NPN_ReloadPlugins - Archive of obsolete content
« gecko plugin api reference « browser side plug-in api summary reloads all of the installed plugins. syntax #include <npapi.h> void npn_reloadplugins(npbool reloadpages);code parameters the function has the following parameter: reloadpages whether to reload pages. if true, all pages are reloaded once the plugins are reloaded; otherwise, they aren't. description npn_reloadplugins() reads the plugins directory for the current platform and reinstalls all of the plug-ins it finds there. normally, if you add or remove any plug-ins, the browser does not see them until you restart gecko. npn_reloadplugins() lets you install a new plug-in and load it, or to remove a plug-in, without having to restart the browser. you could use this function as part of the plug-in's installation pr...
NPN_Version - Archive of obsolete content
wless functionality. for more information and an example, see finding out if a feature exists. for a listing of version constants defined in the plug-in api, see version feature constants. note: platform-specific code in the plug-in api files npwin.cpp, npmac.cpp, or npunix.c checks version numbers automatically. a plug-in whose major version is less than the major version of the browser is not loaded. see also npn_useragent() np_initialize() ...
NPP_Destroy - Archive of obsolete content
stroy(npp instance, npsaveddata **save); parameters the function has the following parameters: instance pointer to the plug-in instance to delete. **save state or other information to save for reuse by a new instance of this plug-in at the same url. passed to npp_new. returns if successful, the function returns nperr_no_error. if unsuccessful, the plug-in is not loaded and the function returns an error code. for possible values, see error codes. description npp_destroy releases the instance data and resources associated with a plug-in. the browser calls this function when a plug-in instance is deleted, typically because the user has left the page containing the instance, closed the window, or quit the browser. you should delete any private instance-specific ...
NPP_SetWindow - Archive of obsolete content
rs: instance pointer to the current plug-in instance. must be embedded or full-screen. window pointer to the window into which the instance draws. the window structure contains a window handle and values for top left corner, width, height, and clipping rectangle (see note on unix below). returns if successful, the function returns nperr_no_error. if unsuccessful, the plug-in is not loaded and the function returns an error code. for possible values, see error codes. description the browser calls npp_setwindow after creating the instance to allow drawing to begin. subsequent calls to npp_setwindow indicate changes in size or position; these calls pass the same npwindow object each time, but with different values. if the window handle is set to null, the window is destroyed. in th...
NP_Initialize - Archive of obsolete content
api reference « plug-in side plug-in api summary provides global initialization for a plug-in. syntax windows #include <npapi.h> nperror winapi np_initialize(npnetscapefuncs *anpnfuncs) unix #include <npapi.h> nperror np_initialize(npnetscapefuncs *anpnfuncs, nppluginfuncs *anppfuncs) returns if successful, the function returns nperr_no_error. if unsuccessful, the plug-in is not loaded and the function returns an error code. for possible values, see error codes. description the browser calls this function only once: when a plug-in is loaded, before the first instance is created. this is the first function that the browser calls. np_initialize tells the plug-in that the browser has loaded it and provides global initialization. allocate any memory or resources shared by all in...
NP_Shutdown - Archive of obsolete content
ance 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 only when the library is finally unloaded. see also np_initialize, npp_destroy ...
Shipping a plugin as a Toolkit bundle - Archive of obsolete content
at. the target application block says which versions of an application the plugin is compatible with. it includes the application id and the minimum and maximum version of the application that the plugin works with. there can be multiple targetapplication blocks listed. the unpack property is necessary to tell applications using newer versions of gecko to unpack the plugin because dlls can't be loaded from xpi files. providing updates when plugins are packaged in this way they can make use of the built in add-on update system. this allows a remote update file to be read periodically and an updated version of the plugin offered to the user or to mark the plugin as compatible with a wider range of applications. this is performed by including an updateurl in the install manifest. this should poi...
Supporting private browsing in plugins - Archive of obsolete content
rmation is not recorded in any way. it also introduced a mechanism by which plugins can determine whether or not private browsing mode is in effect. plugins should be updated to monitor the state of private browsing mode and only save private information when private browsing is disabled. potentially private information may include (but is not necessarily limited to) history information for downloaded data. for example, if private browsing mode is in effect, video player plugins should not record the urls of watched videos in their histories. detecting private browsing mode plug-ins can detect whether or not private browsing mode is in effect by using the npn_getvalue() function to check the current value of the npnvprivatemodebool variable. ...
The First Install Problem - Archive of obsolete content
ated key -- some are string values (reg_sz), and some are actually subkeys. string values take the form stringvalue=valuedata, and subkeys contain their own string values and value data. "path" -- string value -- this would be the absolute path to the plugin module. this is the path to the actual dll. ...
Proposal - Archive of obsolete content
for iptv and ipradio/podcasting. spec exists newsgator feed extension created to make rss feeds work better with newsgator software. lets you specify an image, up to 277x78 pixels. and lets you specifies a specific rendering transform (xslt) to be used when rendering the feed in newsgator for outlook. the transform must already exist on the machine running newsgator; stylesheets will not be downloaded or installed automatically. spec exists rss disposition hinting a proposal to make it so iptv and ipradio/podcasting works better with rss. uses an http "content-type" parameter to hint at an rss feeds disposition type -- to hint at what is being syndicated. in development rsshints a module that adds elements to a feed that help an aggregator process them. draft exists source guid when an r...
Introduction to Public-Key Cryptography - Archive of obsolete content
javascript scripts, or other signed files. for more information, see "object signing". example: a software company signs software distributed over the internet to provide users with some assurance that the software is a legitimate product of that company. using certificates and digital signatures in this manner can also make it possible for users to identify and control the kind of access downloaded software has to their computers. ca certificates. used to identify cas. client and server software use ca certificates to determine what other certificates can be trusted. for more information, see "how ca certificates are used to establish trust". example: the ca certificates stored in firefox determine what other certificates that copy of firefox can authenticate. an administrator can i...
Using workers in extensions - Archive of obsolete content
m xmlhttprequest, instead of immediately updating the displayed information in the status bar, a message is sent to the main thread using the worker's postmessage() method. this is because only the main thread is allowed to access the user interface. the main thread the changes here are also relatively minor, but crucial. the startup() method this method is called when the extension is first loaded, and needs to be updated to start up and configure the worker. let's take a look: startup: function() { // register to receive notifications of preference changes this.prefs = components.classes["@mozilla.org/preferences-service;1"] .getservice(components.interfaces.nsiprefservice) .getbranch("stockwatcher2."); this.prefs.queryinterface(components.interfaces.nsip...
GetObject - Archive of obsolete content
iable you defined. in the preceding example, you access properties and methods of the new object using the object variable myobject. for example: myobject.line(9, 90); myobject.inserttext(9, 100, "hello, world."); myobject.saveas("c:\\drawings\\sample.drw"); note: use the getobject function when there is a current instance of the object, or if you want to create the object with a file already loaded. if there is no current instance, and you don't want the object started with a file loaded, use the activexobject object. if an object has registered itself as a single-instance object, only one instance of the object is created, no matter how many times activexobject is executed. with a single-instance object, getobject always returns the same instance when called with the zero-length string (...
ECMAScript 2015 support in Mozilla - Archive of obsolete content
xt". in august 2014, the ecmascript 2015 draft specification was feature frozen and went through a stabilization and bug fixing period. finally, ecma-262 edition 6 got officially approved and published as a standard on june 17, 2015 by the ecma general assembly. it will also appear as the international industry standard iso/iec 16262:2016. a pdf and html version of the standard can be freely downloaded on ecma-international.org. a channel for feedback on ecmascript standards is es-discuss. standard library additions to the array object array iteration with for...of (firefox 13) array.from() (firefox 32) array.of() (firefox 25) array.prototype.fill() (firefox 31) array.prototype.find(), array.prototype.findindex() (firefox 25) array.prototype.entries(), array.prototype.keys() (firef...
LiveConnect - Archive of obsolete content
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 are blocked when the java control panel security slider is set to very high...
Window.importDialog() - Archive of obsolete content
the chrome url of the xul dialog. aarguments a javascript object containing data to pass to the dialog. example var dialog = importdialog(null, "chrome://myextension/content/dialog.xul", myobject); notes the xul passed to importdialog() is very similar to xul passed to window.opendialog(), with some limitations and caveats: only <dialog> top level elements are permitted. scripts are loaded via an attribute on the <dialog> element, not via the <script> tag. the xul is merged into the existing window, almost like a xul overlay. because of this, element id and javascript conflicts are possible, just like overlays. so be careful. specification this is not part of any specification. ...
XForms Custom Controls - Archive of obsolete content
it is possible to re-enable this by following the steps on using remote xul. this is required for all examples here to run! purpose you are in the right place if you would like to create your own custom renderings of the xforms controls like input, output, trigger, etc. we will also show you how to create custom controls that work with the xforms model and are automatically updated just like xforms controls. the purpose of this article is to give you enough background information so that you'll be able to get a good start. ...
Troubleshooting XForms Forms - Archive of obsolete content
o replace="instance" make sure that the document being returned is xml. there will be an error on the javascript console if it is not. on most webservers you cannot use <submission method="post" action="file.xml"> to a static xml file. you need to use method="get", or <instance src="file.xml"> if the instance is always needed. if you are trying to submit to a different domain than the form is loaded from, make sure that you have allowed cross-domain submission for that specific "form domain". read here for more information. conflicts with other plug-ins if you are using the noscript plugin you may notice that your put and/or post requests are being converted to get requests. in order to fix this, go to the noscript options dialog (right-click on the 's' icon on the status bar and select '...
Mozilla XForms Specials - Archive of obsolete content
the input control documentation. misc cross domain submission not exactly either a limitation, or an extension, but it is worth mentioning here. for security reasons, it is not per default possible for an xforms to submit data to another domain. this is due to security reasons. information about how to whitelist domain can be found in the release notes the cross domain check also includes forms loaded from file://. forms loaded from that url should be local files, and thus trusted, but it is not always the case. so there is not automatic "whitelisting" of local files. if you are wondering why we have this restriction, here is a simple example of why: <xforms:model> <xforms:instance src="http://intranetserver/addrbook.xml"/> <xforms:submission id="sub" action="http://megaspammer.com/gather"...
Correctly Using Titles With External Stylesheets - Archive of obsolete content
persistent, and is likely to be ignored by the web browser. any link element referring to a stylesheet with a title attribute must be either preferred or alternate, depending on the value of the rel attribute. in a document that refers to alternate stylesheets, the preferred stylesheet will be used so long as none of the alternate stylesheets are selected by the user. thus, when the document is loaded, the browser will use all of the persistent stylesheets and one preferred stylesheet (but remember, there should only be one preferred stylesheet). once the user selects one of the alternate stylesheets, the preferred stylesheet will no longer be used, although the user can always re-select the preferred stylesheet. the primary use for preferred stylesheets is to designate one stylesheet as pref...
The Business Benefits of Web Standards - Archive of obsolete content
ing engine), gecko-based browsers, safari, opera linux: gecko-based browsers, khtml-based browsers, opera overall, 5 different rendering engines are used to surf the web using dozens of browsers on 3 platforms. according to many sources, gecko-based browsers are now much more common than netscape 4.x and msie 4 browsers, and it is increasing significantly with time. firefox alone has been downloaded more than 50 millions times in 6 months. in such an increasingly heterogeneous environment, testing each web page in every configuration is impossible. coding to standards is then the only practical solution. in a ground breaking development microsoft have announced a new meta tag that can be used in sites to trigger ie 8 into web standards mode. at the same time in non standards mode existing ...
XQuery - Archive of obsolete content
to browser users), at least one extension has been developed to give a preliminary support for xquery for browser users (and serving as a simple model for how xquery can be implemented within extensions). xquseme is a working proof-of-concept (so far tested on windows and linux with java installed; mac does not work) extension which allows one to perform xqueries on external urls, the currently loaded webpage (even if originally from poorly formed html), and/or xml (including well-formed xhtml) documents stored locally. the extension now includes and interfaces with the open-source version of saxonica's saxon b (though this extension currently only performs the xqueries). other popular native xml databases might also be supported (e.g., exist) in the future, especially now that the extension ...
Anatomy of a video game - Game development
ndle asynchronous events. while we are on the topic of budgeting time, many web browsers have a tool called high resolution time. the date object is no longer the recognised method for timing events because it is very imprecise and can be modified by the system clock. high resolution time, on the other hand, counts the number of milliseconds since navigationstart (when the previous document is unloaded). this value is returned as a decimal number accurate to a thousandth of a millisecond. it is known as a domhighrestimestamp but, for all intents and purposes, consider it a floating point number. note: systems (hardware or software) that are not capable of microsecond accuracy are allowed to provide millisecond accuracy as a minimum. they should provide 0.001ms accuracy if they are capable of ...
Introduction to game development for the Web - Game development
des one way to do 2d graphics. html audio the <audio> element lets you easily play simple sound effects and music. if your needs are more involved, check out the web audio api for real audio processing power! indexeddb a powerful data storage api for maintaining user data on their own computer or device. a great way to save game state and other information locally so it doesn't have to be downloaded every time it's needed. also useful to help make your game playable even when the user isn't connected to the web (such as when they're stuck on an airplane for hours on end). javascript javascript, the programming language used on the web, is blazing fast in modern browsers and getting faster all the time. use its power to write the code for your game, or look at using technologies like emscri...
Building up a basic demo with PlayCanvas editor - Game development
boxanimation.js. if you double click on it, you'll be moved to a code editor. as you can see, the file contains some boilerplate code already: pc.script.create('boxanimation', function (app) { // creates a new boxanimation instance var boxanimation = function (entity) { this.entity = entity; }; boxanimation.prototype = { // called once after all resources are loaded and before the first update initialize: function () { }, // called every frame, dt is time in seconds since last update update: function (dt) { } }; return boxanimation; }); the most interesting part is the update() function, which is where we can put any code that we want repeated on every frame. add the following line inside this function, to r...
Implementing game control mechanisms - Game development
et's start with a quick overview of the game's folder structure, javascript files and in-game states, so we know what's happening where. the game's folders look like this: as you can see there are folders for images, javascript files, fonts and sound effects. the src folder contains the javascript files split as a separate states — 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, an...
Game over - Game development
cordingly. add the following lines just below the previous new one: ball.checkworldbounds = true; ball.events.onoutofbounds.add(function(){ alert('game over!'); location.reload(); }, this); adding those lines will make the ball check the world (in our case canvas) bounds and execute the function bound to the onoutofbounds event. when you click on the resulting alert, the page will be reloaded so you can play again. compare your code you can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: next steps now the basic gameplay is in place let's make it more interesting by introducing bricks to smash — it's time to build the brick field. « previousnext » ...
Initialize the framework - Game development
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 » ...
Load the assets and print them on screen - Game development
e the create() function as shown: function create() { ball = game.add.sprite(50, 50, 'ball'); } this will add the ball to the game and render it on the screen. the first two parameters are the x and y coordinates of the canvas where you want it added, and the third one is the name of the asset we defined earlier. that's it — if you load your index.html file you will see the image already loaded and rendered on the canvas! compare your code you can check the finished code for this lesson for yourself in the live demo below, and play with it to better understand how it works: next steps printing out the ball was easy; next, we'll try moving the ball on screen. « previousnext » ...
Certificate authority - MDN Web Docs Glossary: Definitions of Web-related terms
a certificate authority (ca) is an organization that signs digital certificates and their associated public keys. this certifies that an organization that requested a digital certificate (e.g., mozilla corporation) is authorized to request a certificate for the subject named in the certificate (e.g., mozilla.org). web browsers come preloaded with a list of certificate authorities trusted to issue digital certificates. learn more certificate authority on wikipedia mozilla included ca certificate list ...
Compile time - MDN Web Docs Glossary: Definitions of Web-related terms
the compile time is the time from when the program is first loaded until the program is parsed. learn more general knowledge compile time on wikipedia ...
Constructor - MDN Web Docs Glossary: Definitions of Web-related terms
that is instantiated. the constructor initializes this object and can provide access to its private information. the concept of a constructor can be applied to most object-oriented programming languages. essentially, a constructor in javascript is usually declared at the instance of a class. syntax // this is a generic default constructor class default function default() { } // this is an overloaded constructor class overloaded // with parameter arguments function overloaded(arg1, arg2, ...,argn){ } to call the constructor of the class in javascript, use a new operator to assign a new object reference to a variable. function default() { } // a new reference of a default object assigned to a // local variable defaultreference var defaultreference = new default(); learn more general k...
DOM (Document Object Model) - MDN Web Docs Glossary: Definitions of Web-related terms
an element, text string, or comment). the dom is one of the most-used apis on the web because it allows code running in a browser to access and interact with every node in the document. nodes can be created, moved and changed. event listeners can be added to nodes and triggered on occurrence of a given event. ...
Domain sharding - MDN Web Docs Glossary: Definitions of Web-related terms
y, resulting in a faster page load time and improved user experience. the problem with domain sharding, in terms of performance, is the cost of extra dns lookups for each domain and the overhead of establishing each tcp connection. the initial response from an http request is generally an html file listing other resources such as javascript, css, images and other media files that need to be downloaded. as browsers limit the number of active connections per domain, serving all the required resources from a single domain could be slow as assets need to be downloaded sequentially. with domain sharding, the required downloads are served from more than one domain, enabling the browser to simultaneously download needed resources. multiple domains, however, is an anti-pattern, as dns lookups slow ini...
Fetch directive - MDN Web Docs Glossary: Definitions of Web-related terms
for instance, script-src allows developers to allow trusted sources of script to execute on a page, while font-src controls the sources of web fonts. all fetch directives fall back to default-src. ...
First input delay - MDN Web Docs Glossary: Definitions of Web-related terms
e length of time, in milliseconds, between the first user interaction on a web page and the browser’s response to that interaction. scrolling and zooming are not included in this metric. the time between when content is painted to the page and when all the functionality becomes responsive to human interaction 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 ...
First interactive - MDN Web Docs Glossary: Definitions of Web-related terms
first interactive, also known as first cpu idle, is a non-standard web performance metric that measures when the user's window is quiet enough to handle user input, or what is termed as minimally interactive. minimally interactive is defined as when some, but not necessarily all, ui elements on the page have loaded and are interactive, and, on average, respond to user input in a reasonable amount of time. more information first interactive is a variation of time to interactive, which is split into first interactive and consistently interactive. these metrics have been proposed by the web incubator community group and are already being used in various tools. this metric has been called first cpu idle since lighthouse 3.0 ...
Function - MDN Web Docs Glossary: Definitions of Web-related terms
x; return square(a) + square(b); }; a recursive function is a function that calls itself. see recursion. function loop(x) { if (x >= 10) return; loop(x + 1); }; //using ecmascript 2015 arrow notation const loop = x => { if (x >= 10) return; loop(x + 1); }; an immediately invoked function expressions (iife) is a function that is called directly after the function is loaded into the browser’s compiler. the way to identify an iife is by locating the extra left and right parenthesis at the end of the function’s definition. // declared functions can't be called immediately this way // error (https://en.wikipedia.org/wiki/immediately-invoked_function_expression) /* ​function foo() { console.log('hello foo'); }(); */ // function expressions, named or anonymou...
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. see also lazy loading ...
Media - MDN Web Docs Glossary: Definitions of Web-related terms
media (audio-visual presentation) the term media (more accurately, multimedia) refers to audio, video, or combined audio-visual material such as music, recorded speech, movies, tv shows, or any other form of content that is presented over a period of time. media (css) in the context of css (cascading style sheets), the term media refers to the destination to which the document is to be drawn by the rendering engine. ...
Page prediction - MDN Web Docs Glossary: Definitions of Web-related terms
on feature completing search text and address bar urls based on browsing history and related searches. for example, as the user types in the address bar, the browser might send the current text in the address bar to the search engine before the user submits the request. although browser page prediction and prediction services enable faster page loads, they consume additional bandwidth. also, pre-loaded websites and embedded content can set and read their cookies as if they were visited even if they weren't. ...
Parse - MDN Web Docs Glossary: Definitions of Web-related terms
articularly those without an async or defer attribute—blocks rendering, and pauses parsing of html. when the browser encounters css styles, it parses the text into the css object model (or cssom), a data structure it then uses for styling layouts and painting. the browser then creates a render tree from both these structures to be able to paint the content to the screen. javascript is also downloaded, parsed, and then execute. javascript parsing is done during compile time or whenever the parser is invoked, such as during a call to a method. learn more general knowledge parse on wikipedia ...
Perceived performance - MDN Web Docs Glossary: Definitions of Web-related terms
n 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. perceived performance is not measured 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 t...
Resource Timing - MDN Web Docs Glossary: Definitions of Web-related terms
...
Same-origin policy - MDN Web Docs Glossary: Definitions of Web-related terms
the same-origin policy is a critical security mechanism that restricts how a document or script loaded from one origin can interact with a resource from another origin. it helps isolate potentially malicious documents, reducing possible attack vectors. ...
Style origin - MDN Web Docs Glossary: Definitions of Web-related terms
the style origin containing any css that the user of the web browser has added. these may be from adding styles using a developer tool or from a browser extension that automatically applies custom styles to content, such as stylus or stylish. author origin the author origin is the style origin which contains all of the styles which are part of the document, whether embedded within the html or loaded from an external stylesheet file. the style origins are used to determine where to stop rolling back (or backtracking through) the cascade of styles that have been applied to an element when removing styles, such as when using the unset or revert keywords. learn more technical information css cascading and inheritance: cascading origins ...
Web performance - MDN Web Docs Glossary: Definitions of Web-related terms
web performance is the objective time from when a request for content is made until the requested content is displayed in the user's browser, objective render times, and the subjective user experience of load time and runtime. objectively, it is measurable time, in milliseconds, it takes for the web page or web application to be downloaded, painted in the user's web browser, and become responsive and interactive. it is the frames per second and times the main thread is not available for user interactions. subjectively, it is the user's perception of whether the time it takes between the time the user requests the content and the time until the user feels the content requested is available and usable feels slow or fast. learn more learn about web performance perceived performance ...
First Meaningful Paint - MDN Web Docs Glossary: Definitions of Web-related terms
it is when the answer to "is it useful?" becomes "yes", upon first meaningful paint completion. ...
Speculative parsing - MDN Web Docs Glossary: Definitions of Web-related terms
traditionally in browsers the html parser ran on the main thread and was blocked after a </script> tag until the script has been retrieved from the network and executed. some html parser, such as firefox since firefox 4, support speculative parsing off of the main thread. it parses ahead while scripts are being downloaded and executed. the html parser starts speculative loads for scripts, style sheets and images it finds ahead in the stream 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 th...
HTML: A good basis for accessibility - Learn web development
tanding upright like a human, with small arms, and a large head with lots of sharp teeth.</p> the first image, when viewed by a screen reader, doesn't really offer the user much help — voiceover for example reads out "/dinosaur.png, image". it reads out the filename to try to provide some help. in this example the user will at least know it is a dinosaur of some kind, but often files may be uploaded with machine-generated file names (e.g. from a digital camera) and these file names would likely provide no context to the image's content. note: this is why you should never include text content inside an image — screen readers simply can't access it. there are other disadvantages too — you can't select it and copy/paste it. just don't do it! when a screen reader encounters the second im...
HTML: A good basis for accessibility - Learn web development
tanding upright like a human, with small arms, and a large head with lots of sharp teeth.</p> the first image, when viewed by a screen reader, doesn't really offer the user much help — voiceover for example reads out "/dinosaur.png, image". it reads out the filename to try to provide some help. in this example the user will at least know it is a dinosaur of some kind, but often files may be uploaded with machine-generated file names (e.g. from a digital camera) and these file names would likely provide no context to the image's content. note: this is why you should never include text content inside an image — screen readers simply can't access it. there are other disadvantages too — you can't select it and copy/paste it. just don't do it! when a screen reader encounters the second im...
Mobile accessibility - Learn web development
the most common problems that need to be addressed for mobile are: suitability of layouts for mobile devices. a multi-column layout won't work as well on a narrow screen, for example, and the text size may need to be increased so it is legible. such issues can be solved by creating a responsive layout using technologies such as media queries, viewport, and flexbox. conserving image sizes downloaded. in general, small screen devices won't need images that are as large as their desktop counterparts, and they are more likely to be on slow network connections. therefore, it is wise to serve smaller images to narrow screen devices as appropriate. you can handle this using responsive image techniques. thinking about high resolutions. many mobile devices have high-resolution screens, and therefor...
WAI-ARIA basics - Learn web development
improved semantics of the search form have shown what is made possible when aria goes beyond the semantics available in html5. you'll see a lot more about these semantics and the power of aria properties/attributes below, especially in the accessibility of non-semantic controls section. for now though, let's look at how aria can help with dynamic content updates. dynamic content updates content loaded into the dom can be easily accessed 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 updat...
Organizing your CSS - Learn web development
s to actually link into your website. so for example, with partials, you could have several style files inside a directory, say foundation/_code.scss, foundation/_lists.scss, foundation/_footer.scss, foundation/_links.scss, etc., then use the sass @use role to load them into other stylesheets: // foundation/_index.sass @use 'code' @use 'lists' @use 'footer' @use 'links' if the partials are all loaded into an index file, as implied above, you can then load that entire directory into another stylesheet in one go: // style.sass @use 'foundation' note: a simple way to try out sass is to use codepen — you can enable sass for your css in the settings for a pen, and codepen will then run the sass parser for you, in order that you can see the resulting webpage with regular css applied. sometimes...
Beginner's guide to media queries - Learn web development
ia expression, which is a rule, or test that must be passed for the contained css to be applied. a set of css rules that will be applied if the test passes and the media type is correct. media types the possible types of media you can specify are: all print screen speech the following media query will only set the body to 12pt if the page is printed. it will not apply when the page is loaded in a browser. @media print { body { font-size: 12pt; } } note: the media type here is different from the so-called mime type. note: there were a number of other media types defined in the level 3 media queries specification; these have been deprecated and should be avoided. note: media types are optional; if you do not indicate a media type in your media query then the me...
Styling links - Learn web development
and centering the text to make it stand out more.) <p><a href="#">a simple link</a></p> p { font-size: 2rem; text-align: center; } note: all the links in the examples in this page are fake links — a # (hash, or pound sign) is put in place of the real url. this is because if the real links were included, clicking on them would break the examples (you'd end up with an error, or a page loaded in the embedded example that you couldn't get back from.) # just links to the current page. you'll notice a few things as you explore the default styles: links are underlined. unvisited links are blue. visited links are purple. hovering a link makes the mouse pointer change to a little hand icon. focused links have an outline around them — you should be able to focus on the links on th...
Styling lists - Learn web development
(example.png); list-style-position: inside; } could be replaced by this: ul { list-style: square url(example.png) inside; } the values can be listed in any order, and you can use one, two or all three (the default values used for the properties that are not included are disc, none, and outside). if both a type and an image are specified, the type is used as a fallback if the image can't be loaded for some reason. controlling list counting sometimes you might want to count differently on an ordered list — e.g. starting from a number other than 1, or counting backwards, or counting in steps of more than 1. html and css have some tools to help you here. start the start attribute allows you to start the list counting from a number other than 1. the following example: <ol start="4"> <...
How do you set up a local testing server? - Learn web development
if you are using linux or macos, it should be available on your system already. if you are a windows user, you can get an installer from the python homepage and follow the instructions to install it: go to python.org under the download section, click the link for python "3.xxx". at the bottom of the page, choose the windows x86 executable installer and download it. when it has downloaded, run it. on the first installer page, make sure you check the "add python 3.xxx to path" checkbox. click install, then click close when the installation has finished. open your command prompt (windows)/ terminal (macos/ linux). to check python is installed, enter the following command: python -v # or you might have the py command available, # in which case try py -v this ...
HTML forms in legacy browsers - Learn web development
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 function is called in order to initialize the app. complete : function () { app.init(); } }); the modernizr team conveniently maintains a list of great polyfills. just pick what you need. note: modernizr has other awe...
Other form controls - Learn web development
ters and progress bars are visual representations of numeric values. progress a progress bar represents a value that changes over time up to a maximum value specified by the max attribute. such a bar is created using a <progress> element. <progress max="100" value="75">75/100</progress> this is for implementing anything requiring progress reporting, such as the percentage of total files downloaded, or the number of questions filled in on a questionnaire. the content inside the <progress> element is a fallback for browsers that don't support the element and for screen readers to vocalize it. meter a meter bar represents a fixed value in a range delimited by max and min values. this value is visually rendered as a bar, and to know how this bar looks, we compare the value to some other set...
Styling web forms - Learn web development
the css now we can dig into the css for the example. add all the code blocks shown below inside the <style> element, one after another. overall layout first, we prepare by defining our @font-face rules, and all the basic styles set on the <body> and <form> elements. ...
HTML basics - Learn web development
ur document should use to utf-8 which includes most characters from the vast majority of written languages. essentially, it can now handle any textual content you might put on it. there is no reason not to set this and it can help avoid some problems later on. <title></title> — the <title> element. this sets the title of your page, which is the title that appears in the browser tab the page is loaded in. it is also used to describe the page when you bookmark/favourite it. <body></body> — the <body> element. this contains all the content that you want to show to web users when they visit your page, whether that's text, images, videos, games, playable audio tracks or whatever else. images let's turn our attention to the <img> element again: <img src="images/firefox-icon.png" alt="my test...
How the Web works - Learn web development
ients are the typical web user's internet-connected devices (for example, your computer connected to your wi-fi, or your phone connected to your mobile network) and web-accessing software available on those devices (usually a web browser like firefox or chrome). servers are computers that store webpages, sites, or apps. when a client device wants to access a webpage, a copy of the webpage is downloaded from the server onto the client machine to be displayed in the user's web browser. the other parts of the toolbox the client and server we've described above don't tell the whole story. there are many other parts involved, and we'll describe them below. for now, let's imagine that the web is a road. on one end of the road is the client, which is like your house. on the other end of the road i...
Use JavaScript within a webpage - Learn web development
pt from your webpage, just use <script> with an src attribute pointing to the script file, using its url: <script src="path/to/my/script.js"></script> writing javascript within html you may also add javascript code between <script> tags rather than providing an src attribute. <script> window.addeventlistener('load', function () { console.log('this function is executed once the page is fully loaded'); }); </script> that's convenient when you just need a small bit of javascript, but if you keep javascript in separate files you'll find it easier to focus on your work write self-sufficient html write structured javascript applications use scripting accessibly accessibility is a major issue in any software development. javascript can make your website more accessible if you use it wise...
Getting started with HTML - Learn web development
our document to utf-8, which includes most characters from the vast majority of human written languages. with this setting, the page can now handle any textual content it might contain. there is no reason not to set this, and it can help avoid some problems later. <title></title>: the <title> element. this sets the title of the page, which is the title that appears in the browser tab the page is loaded in. the page title is also used to describe the page when it is bookmarked. <body></body>: the <body> element. this contains all the content that displays on the page, including text, images, videos, games, playable audio tracks, or whatever else. active learning: adding some features to an html document if you want to experiment with writing some html on your local computer, you can: copy...
Introduction to HTML - Learn web development
tant terms, and show where they fit in the language. we also show how a typical html page is structured and how an html element is structured, and explain other important basic language features. along the way, we'll play with some html to get you interested! what’s in the head? metadata in html the head of an html document is the part that is not displayed in the web browser when the page is loaded. it contains information such as the page <title>, links to css (if you want to style your html content with css), links to custom favicons, and metadata (data about the html, such as who wrote it, and important keywords that describe the document). html text fundamentals one of html's main jobs is to give text meaning (also known as semantics), so that the browser knows how to display it corre...
Images in HTML - Learn web development
ple, we could do this: <img src="images/dinosaur.jpg" alt="the head and torso of a dinosaur skeleton; it has a large head 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 fitti...
From object to iframe — other embedding technologies - Learn web development
="1200" typemustmatch> <p>you don't have a pdf plugin, but you can <a href="mypdf.pdf">download the pdf file. </a> </p> </object> pdfs were a necessary stepping stone between paper and digital, but they pose many accessibility challenges and can be hard to read on small screens. they do still tend to be popular in some circles, but it is much better to link to them so they can be downloaded or read on a separate page, rather than embedding them in a webpage. the case against plugins once upon a time, plugins were indispensable on the web. remember the days when you had to install adobe flash player just to watch a movie online? and then you constantly got annoying alerts about updating flash player and your java runtime environment. web technologies have since grown much more robu...
Introducing asynchronous JavaScript - Learn web development
r 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(), displaytext(), etc. note that not all callbacks are async — some run synchronously. an example is when we use array.prototype.foreach() to loop through the items in an array (see it live, and the source): const gods = ['apollo', 'artemis', 'ares', 'zeus']; gods.foreach(function (eachname, index){ console.log(index + '. ' + eachname); }); in this example we loop thr...
Introduction to events - Learn web development
is, some code running) when the event occurs. for example, in an airport, when the runway is clear for take off, a signal is communicated to the pilot. as a result, the plane can safely takeoff. in the case of the web, events are fired inside the browser window, and tend to be attached to a specific item that resides in it — this might be a single element, set of elements, the html document loaded in the current tab, or the entire browser window. there are many different types of events that can occur. for example: the user selects a certain element or hovers the cursor over a certain element. the user chooses a key on the keyboard. the user resizes or closes the browser window. a web page finishes loading. a form is submitted. a video is played, paused, or finishes. an error occu...
What went wrong? Troubleshooting JavaScript - Learn web development
o enter a guess and press the submit guess button, you'll see ... another error! this time the error being reported is "typeerror: loworhi is null", on line 78. note: null is a special value that means "nothing", or "no value". so loworhi has been declared and initialised, but not with any meaningful value — it has no type or value. note: this error didn't come up as soon as the page was loaded because this error occurred inside a function (inside the checkguess() { ... } block). as you'll learn in more detail in our later functions article, code inside functions runs in a separate scope than code outside functions. in this case, the code was not run and the error was not thrown until the checkguess() function was run by line 86. have a look at line 78, and you'll see the following c...
JavaScript object basics - Learn web development
your code, that string is automatically created as an instance of string, and therefore has several common methods and properties available on it. when you accessed the document object model using lines like this: const mydiv = document.createelement('div'); const myvideo = document.queryselector('video'); you were using methods available on an instance of the document class. for each webpage loaded, an instance of document is created, called document, which represents the entire page's structure, content, and other features such as its url. again, this means that it has several common methods and properties available on it. the same is true of pretty much any other built-in object or api you've been using — array, math, and so on. note that built in objects and apis don't always create ...
Working with JSON - Learn web development
for example: superheroes.hometown superheroes['active'] to access data further down the hierarchy, you simply have to chain the required property names and array indexes toget...
Object-oriented JavaScript for beginners - Learn web development
and it is clear where they came from. however, some people prefer to create object instances without first creating constructors, especially if they are creating only a few instances of an object. javascript has a built-in method called create() that allows you to do that. with it, you can create a new object based on any existing object. with your finished exercise from the previous sections loaded in the browser, try this in your javascript console: let person2 = object.create(person1); now try these: person2.name; person2.greeting(); you'll see that person2 has been created based on person1—it has the same properties and method available to it. one limitation of create() is that ie8 does not support it. so constructors may be more effective if you want to support older brows...
Test your skills: JSON - Learn web development
n error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version). json 1 the one and only task in this article concerns accessing json data and using it in your page. json data about some mother cats and their kittens is available in sample.json. the json is loaded into the page as a text string and made available in the catstring parameter of the displaycatinfo() function, called when the provided promise chain (which starts by fetching the json data) is fulfilled. your task is to fill in the missing parts of the displaycatinfo() function to store: the names of the three mother cats, separated by commas, in the motherinfo variable. the total number of ...
Web performance resources - Learn web development
uick wins css web performance is all about user experience and perceived performance. as we learned in the critical rendering path document, linking css with a tradional link tag with rel="stylesheet" is synchronous and blocks rendering. optimize the rendering of your page by removing blocking css. to load css asynchronously one can simpy set the media type to print and then change to all once loaded. the following snippet includes an onload attribute, requiring javascript, so it is important to include a noscript tag with a traditional fallback. <link rel="stylesheet" href="/path/to/my.css" media="print" onload="this.media='all'"> <noscript><link rel="stylesheet" href="/path/to/my.css"></noscript> the downside with this approach is the flash of unstyled text (fout.) the simplist way to ad...
The business case for web performance - Learn web development
ke sure the team stays on track in keeping the site and help prevent regressions. a performance budget is a set of limits that are set to specify limits, such as maximum number of http requests allowed, the maximum total size of all the assets combined, the minimum allowable fps on a specific device, etc, that must be maintained. the budget can be applied to a single file, a file type, all files loaded on a page, a specific metric, or a threshold over a period of time.the budget reflects reachable goals; whehter they are time, quantity, or rule based. definining and promoting a budget helps performance proponent advocates for good user experience against competing interests, such as marketing, sales, or even other developers that may want to add videos, 3rd party scripts, or even frameworks. p...
Properly configuring server MIME types - Learn web development
ontinue to process content as expected even though the web server is misconfigured, e.g. displays an image which is reported to be plain text. serving content using the correct mime type can also be important for security reasons; it's possible for malicious content to affect the user's computer by pretending to be a safe type of document when it is in fact not. note: historically, firefox has loaded css files even if they had the wrong mime type, as long as the html document that requested them was being processed in quirks mode. for security reasons, gecko 2.0 will no longer do this for stylesheets loaded from a different origin than the requesting document. if your stylesheet comes from a different origin than the document, you must serve it with the correct mime type (text/css). gecko 1.
Getting started with Svelte - Learn web development
heet' href='/build/bundle.css'> <script defer src='/build/bundle.js'></script> </head> <body> </body> </html> the minified version of bundle.js weighs a little more than 3kb, which includes the "svelte runtime" (just 300 lines of javascript code) and the app.svelte compiled component. as you can see, bundle.js is the only javascript file referenced by index.html. there are no other libraries loaded into the web page. this is a much smaller footprint than compiled bundles from other frameworks. take into account that, in the case of code bundles, it's not just the size of the files you have to download that matter. this is executable code that needs to be parsed, executed, and kept in memory. so this really makes a difference, especially in low-powered devices or cpu-intensive applications.
Handling common accessibility problems - Learn web development
commands to use in certain places. have a play with vo now; you can then go on to play with some of our examples in the screenreader testing section. nvda nvda is windows-only, and you'll need to install it. download it from nvaccess.org. you can choose whether to make a donation or download it for free; you'll also need to give them your e-mail address before you can download it. once downloaded, install it — you double click the installer, accept the license and follow the prompts. to start nvda, double click on the program file/shortcut, or use the keyboard shortcut ctrl + alt + n. you'll see the nvda welcome dialog when you start it. here you can choose from a couple of options, then press the ok button to get going. nvda will now be active on your computer. to use nvda, you wil...
Introduction to automated testing - Learn web development
me 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 button in your test session. with the in-built image editor, highlight your screenshot before you push ...
Handling common JavaScript problems - Learn web development
ment.createelement('script'); js.src = src; js.onload = function() { done(); }; js.onerror = function() { done(new error('failed to load script ' + src)); }; document.head.appendchild(js); } this function creates a new <script> element, then sets its src attribute to the path we specified as the first argument ('polyfills.js' when we called it in the code above). when it has loaded, we run the function we specified as the second argument (main()). if an error occurs in the loading of the script, we still call the function, but with a custom error that we can retrieve to help debug a problem if it occurs. note that polyfills.js is basically the two polyfills we are using put together into one file. we did this manually, but there are cleverer solutions that will automatical...
Client-side tooling overview - Learn web development
r, which we’ll make use of later on in the module. bundlers/packagers these are tools that get your code ready for production, for example by “tree-shaking” to make sure only the parts of your code libraries that you are actually using are put into your final production code, or "minifying" to remove all the whitespace in your production code, making it as small as possible before it is uploaded to a server. parcel is a particularly clever tool that fits into this category — it can do the above tasks, but also helps to package assets like html, css, and image files into convenient bundles that you can then go on to deploy, and also adds dependencies for you automatically whenever you try to use them. it can even handle some code transformation duties for you. webpack is another very ...
Accessibility/LiveRegionDevGuide
tribute 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 system generated. (at-spi only) a global variable can be set in a document:load:complete event listener and reset in a object:state-changed:busy listener. this variable can then be used to quickly determine if an event was triggered by the document being loaded. an event containing an object that does not have state visible is probably from a hidden tab. an event containing an object that has state selectable is not a live region. an event containing an object that has the attribute "container-live" is a live region. however, many web sites do not have proper aria markup so this cannot be used by itself. an event containing an object that has an att...
Embedding API for Accessibility
"alert.audio.*" preference, 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 prese...
Gecko info for Windows accessibility vendors
eturn 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_change is fired for the new root role_document object for the window, with its state_b...
Links and Resources
nd on opensp for sgml validation - just like w3c html validator) is a free, powerful, versatile, extended html validator. it can work offline. it can also report accessibility errors and warnings according to selectable accessibility guidelines (section 508, wcag priorities 1, 2 or 3). its accessibility report is viewable in the view source window. this html advanced validator may also be downloaded from firefox add-ons: html validator. open source assistive technology projects nonvisual desktop access open source screen reader for windows, written in python. lsr open source screen reader for linux, written in python orca open source screen reader for linux, written in python accessibility for desktop environments gnome accessibility - gnome accessibility project kde accessi...
Mozilla’s UAAG evaluation report
ollowing line can be added to a user's prefs.js file to control blinking: user_pref("browser.blink_allowed", false); bug 89144 has been filed to expose this pref in the ui. mozilla doesn't support <marquee> by default. 3.4 toggle scripts. (p1) g preferences, advanced, scripts & windows - enable javascript for when toggled off, we don't notify the user when a page is loaded with scripts 3.5 toggle content refresh. (p1) ni mozilla has no features for toggling refreshes 3.6 toggle redirects. (p2) ni mozilla has no features for toggling redirects 3.7 toggle images. (p2) p our interface for image toggling needs redesign unfortunately, there are quite a few open bugs on image toggling guideline 4. ensure user co...
Command line options
privileges. note: since firefox 2.0.0.7, use of the -install-global-extension and -install-global-theme command line arguments have been restricted to only allow installing add-ons that are on local disks or mapped drives. installing from a network share directly will no longer succeed. -safe-mode launches the application with all extensions disabled, for that launch only (extensions are not loaded, but are not permanently disabled in the extension manager data source). remote control -remote remote_command this feature was removed in firefox 36.0, restored in 36.0.1 and removed again in 39.0. see bug 1080319. execute the specified remote_command in an already running application process. firefox -remote "openurl(www.mozilla.org, new-tab)" this option is only available on x-wind...
Creating a Language Pack
cale. $ make wget-en-us en_us_binary_url=http://ftp.mozilla.org/pub/mozilla.org/firefox/nightly/latest-mozilla-aurora if you're building on mac 64 bit, you'll need to change the command slightly: $ make wget-en-us en_us_binary_url=http://ftp.mozilla.org/pub/mozilla.org/firefox/nightly/latest-mozilla-aurora moz_pkg_platform=mac at some point, you should see the following success message: downloaded http://ftp.mozilla.org/pub/mozilla.o....en-us.mac.dmg to /users/your_id/mozilla/vc/firefox/browser/locales/../../dist/firefox-3.6b5pre.en-us.mac.dmg the en-us binary has been downloaded. let's unpack it $ make unpack again, for 64-bit mac, append moz_pkg_platform=mac to this command. at the end of the process, you should see the following success message. ... done unpacking let's check whi...
Creating reftest-based unit tests
omplish this by either: rewrite them as mochitests. the helper functions snapshotwindow and comparesnapshots are available in testing/mochitest/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...
Creating Sandboxed HTTP Connections
s cookies. the observer service (nsiobserverservice) is used to send general notifications, including the two cookie ones. the addobserver method is used to add an observer for a certain topic and takes in three agruments: an object than implements nsiobserver the topic to listen for. for cookies, the two topics are: http-on-modify-request - happens after the cookie data has been loaded into the request, but before the request is sent. http-on-examine-response - happens after the response is received, but before the cookies are processed whether to hold a weak reference to the observer argument. use false. in order to avoid memory leaks, the observer needs to be removed at one point. the removeobserver method takes in the listener object and the topic and remov...
Debugging on Mac OS X
in 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 extended attribute from the downloaded nightly: $ xattr -r -d com.apple.quarantine /path/to/nightly.app local builds local builds of mozilla-central do not enable hardened runtime and hence do not have debugging restrictions. as a result, some functionality will be permit...
HTTP logging
hat look like: log.txt-main.1806, log.txt-child.1954, log.txt-child.1970, etc. this is because firefox now uses multiple processes, and each process gets its own log file. for many bugs, the "log.txt-main" file is the only thing you need to upload as a file attachment to your bugzilla bug (this is assuming you're logging to help a mozilla developer). other bugs may require all the logs to be uploaded--ask the developer if you're not sure. pat yourself on the back--a job well done! thanks for helping us debug firefox. logging http activity by manually setting environment variables sometimes the about:networking approach won't work, for instance if your bug occurs during startup, or you're running on mobile, etc. in that case you can set environment variables *before* you launch firefox. ...
Simple Thunderbird build
=12905 are installed because the mapi header files (except mapi.h) are not bundled with visual studio 2017 (windows sdk 10). you should copy 17 of the 18 header files to a windows sdk include directory so that the build process will find the files, that is c:\program files (x86)\windows kits\10\include\10.0.nnnnn.0\shared, where nnnnn is the highest number present on the system. note that the downloaded outlook 2010 mapi header files contain 18 fies, of which only 17 are needed. do not copy mapi.h, it is already in c:\program files (x86)\windows kits\10\include\10.0.17134.0\um\mapi.h. as of april 2019, 10.0.17134.0 is needed to compile thunderbird. assuming standard installation locations, copy these 17 files to c:\program files (x86)\windows kits\10\include\10.0.17134.0\shared. 18/10/2010 16...
ESLint
below. no-undef the no-undef rule is currently being enabled throughout the code base. here are some common issues: my script is imported into the global browser.xul scope. add a line like: /* eslint-env mozilla/browser-window */ or enable the rule in a .eslintrc.js if it will apply to the whole directory. ...
Eclipse CDT
ile that is compiled. this would eliminate the requirement for non-parallelized, non-silenced builds. you could also build from eclipse and get the benefits that that brings. how can i run a more recent cdt version? this can be useful if you need to get certain bug fixes, or to help with testing to make sure that new eclipse bugs that affect its use with mozilla don't get shipped. if you've downloaded an eclipse developer build then you can use eclipse's software update mechanism to update your developer snapshot to the latest nightly for that developer branch. to do that, carry out the following steps. from eclipse's "help" menu select "install new software...", then in the "install" window that opens, click "available software sites". in the window that opens, click "add", and in the prompt...
Displaying Places information using views
views below. using the tree view so you've got a built-in tree view. how do you ask it about the data it displays? first, see nsiplacesview. like all places views, the built-in tree view implements this interface, which provides broad methods such as getting the view's nsinavhistoryresult instance and examining the view's selection. second, know this: when it comes to trees, "view" is an overloaded word. this document describes places views. places views are just xul elements; the built-in places tree view is just a tree element whose type attribute is equal to "places", as described above. but recall that all trees—places view or not—display their data using another kind of view, nsitreeview. the built-in places tree view therefore has a view of its own, the built-in places tree view's...
Index
ge associated with traditional cookie blocking. this article explains how the new policy works and how you can test it. 171 tracking protection privacy, private browsing, blocking, tracking starting in version 42, firefox desktop and firefox for android include built-in tracking protection. in private browsing windows (tabs, in firefox for android), firefox will block content loaded from domains that track users across sites. 172 security best practices for firefox front-end engineers best practices, developing firefox, developing mozilla, firefox, front-end, mozilla, performance this article will help firefox developers understand the security controls in place and avoid common pitfalls when developing front-end code for firefox. ...
Multiple Firefox profiles
show up every time you launch. setting up multiple profiles for different firefox channels this section will be especially helpful if you are a developer, wanting to work with multiple channels, and each having their separate launcher. windows in windows, the developer and nightly builds get their own directory in the "programs" folder, so you don't have to worry about where to store the downloaded files. however, all three will attempt to use the same profile by default. you won't want to keep this behavior, because the different channels have different levels of features. to set each launcher, follow the windows instructions at windows launcher. linux in linux, things aren't as automatically set up. you will likely get a prompt to download a tar.bz2 file to extract from. extract the fil...
Limitations of frame scripts
l. if you want a chrome window: send a message from the content process using the message manager. the target property of the object passed into the message handler in the chrome process is the xul <browser> receiving the message, and you can get the chrome window from that (note: i'm not really sure how...). nsiaboutmodule by default, custom about: pages registered using nsiaboutmodule are loaded in the chrome process. this means that you can't access their content from the content process (via xhr, for example). you can change this default in the code you use to register the about: uri. see about: and chrome: uris. javascript code modules (jsms) in multiprocess firefox, a jsm loaded into the content process does not share any state with the same jsm loaded into the chrome process. see...
Partitioned: All third-party storage access requests
message firefox: cookiepartitionedforeign=partitioned cookie or storage access was provided to “<url>” because it is loaded in the third-party context and storage partitioning is enabled. what went wrong? a request to access cookies or storage was partitioned because it came from a third-party (a different origin) and dynamic first-party isolation is enabled. ...
Site Identity Button
in this case, expect to see a 'mixed content' message in the web console. use of a weak cipher - in this case, you're using tls but a strong cipher was not available. look for messages about weak ciphers (e.g. rc4). insecure renegotation - older versions of tls had a flaw in the basic design; if your server uses an affected version, the security ui will be downgraded but...
HTMLIFrameElement.download()
he htmliframeelement interface downloads a specified url, storing it at /sdcard/download. syntax var instanceofdomrequest = instanceofhtmliframeelement.download(url, options); returns a domrequest for handling the download request. its request.onsuccess handler handles the success case, and its request.onerror handler handles the failure case. parameters url the url of the file to be downloaded. options optional an options object allowing optional settings to be specified for the download. the available options are: filename: the filename to save the downloaded file as. if this is not specified, the filename used will be the original filename, as specified in the url. referrer: specifies a referrer for the downloaded file. if this is not specified there will be no referrer. ...
HTMLIFrameElement.executeScript()
warning: removed in firefox 65. the executescript() method of the htmliframeelement interface allows a specified script to be executed against a page loaded in the browser <iframe>. note: use of the browser api requires a privileged app, and browser and/or embed-apps permissions, depending on what you want to do. see using the browser api for more details. syntax var mydomrequest = instanceofhtmliframeelement.executescript(script, options); return value a domrequest object that returns an onsuccess handler if the script is successfully executed against the loaded content, or an onerror handler if not. parameters script the script to be executed. options optional optionally, you can provide an origin or url for the script to be executed against. it's recommended that you includ...
HTMLIFrameElement.getManifest()
warning: removed in firefox 65. the getmanifest() method of the htmliframeelement interface retrieves the manifest of an app loaded in the browser <iframe> and returns it as json. syntax instanceofhtmliframeelement.getmanifest().then(function(json) { ... }); parameters none. return value a promise that resolves to a json object representation of the loaded app's manifest. examples var browser = document.queryselector('iframe'); browser.addeventlistener('mozbrowserloadend',function() { var request = browser.getmanifest().then(function(json) { console.log(json); }); }); specification not part of any specification. ...
HTMLIFrameElement.getStructuredData()
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 getstructureddata() method of the htmliframeelement interface retrieves any structured microdata (and hcard and hcalendar microformat data) contained in the html loaded in the browser <iframe> and returns it as json. syntax var instanceofdomrequest = instanceofhtmliframeelement.getstructureddata(); returns a domrequest to handle the getstructureddata() request's success and error cases. if the request is successful, the request.result is a json object representation of all microdata contained on the page loaded in the browser. parameters none. examples v...
mozbrowsercaretstatechanged
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 mozbrowsercaretstatechanged event is fired when the user selects content in a page loaded in a browser <iframe>. this is used by the embedder to show a context menu for clipboard actions. 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 ...
mozbrowsermanifestchange
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 mozbrowsermanifestchange event is fired when the manifest location of the app loaded in the browser <iframe> changes. by this, we are referring to the href of the manifest, as defined in <link rel="manifest" href=" … ">. 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 rea...
mozbrowseropentab
t. bubbles read only boolean whether the event normally bubbles or not. cancelable read only boolean whether the event is cancellable or not. details read only object a custom object. details the details property returns an anonymous javascript object with the following properties: url a domstring representing the url of the new document loaded. example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowseropentab", function( event ) { console.log("a new document has opened containing the content at " + event.details.url + "."); }); related events mozbrowserasyncscroll mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowser...
mozbrowseropenwindow
event. bubbles read only boolean whether the event normally bubbles or not. cancelable read only boolean whether the event is cancellable or not. details read only object a custom object. details the details property returns an anonymous javascript object with the following properties: url a domstring representing the url of the document loaded within the frameelement property. name a domstring representing the name of the new browser window. features a domstring containing features represented by a list of names and values separated by commas. for a complete list of possible features, see window.open(). frameelement an object representing the new browser <iframe> that will embed the new content. example var browser = document.
CSS -moz-bool-pref() @supports function
the -moz-bool-pref() @supports condition is available to gecko chrome and ua stylesheets to check if a boolean preference is enabled. syntax -moz-bool-pref( <string> ) parameters <string> the preference name returns evaluates to true if the preference is enabled, false otherwise. example warning: this will only work when loaded from a gecko chrome stylesheet. html <div id="pref-test"> this will have a green background if the <code>test</code> preference is enabled. </div> css @supports -moz-bool-pref("test") { #pref-test { background: green; } } @supports not -moz-bool-pref("test") { #pref-test { background: red; } } result ...
Overview of Mozilla embedding APIs
reference to a component which implements the nsiweakreference interface. global services nsservicemanager the service manager is the central repository for accessing instances of the various xpcom services. each service is represented by a singleton object which is instantiated the first time it is requested and remains alive until the service manager is shut down, or the service is explicitly unloaded. through the service manager, individual services can be loaded, unloaded and accessed. implemented interfaces: nsiservicemanager related interfaces: nsishutdownlistener nsmemory the nsmemory service provides the global memory manager implementation for xpcom. in addition to memory allocation and release, this service provides low memory notifications, called a memory pressure observers, ...
Embedding the editor
the editor frame. xbl creates an nseditorboxobject for each <editor> tag, and allows javascript to access properties of this box object (such as the nsieditorshell). the <editor> tag is simply a <iframe> on which an editor is created; in all other respects, it behaves like a xul <iframe>. the problem with this ownership model is that there can be only one editor per <editor> tag, yet the document loaded in the <iframe> may itself contain multiple <iframe>s (consider a frameset document, or a document itself containing an <html:iframe>). currently, composer does not deal gracefully with such documents. one editor per window limitation the current composer window xul/c++ architecture has grown up with the assumption that there can be just one <editor> tag per window. at window construction time, w...
Gecko SDK
note: you can subscribe to a calendar of the firefox release schedule. also, you can view the schedule on the web. unpack the sdk tarball to some suitable location. issues with the os x sdk if you need to use the xpidl utility to compile idl files on os x, it's likely that you will receive a strange error when running the tool that looks something along the lines of this: dyld: library not loaded: /opt/local/lib/libintl.3.dylib referenced from: /users/varmaa/xulrunner-sdk/bin/./xpidl reason: image not found trace/bpt trap unfortunately, this is caused by a problem with the sdk build process which cannot currently be resolved (see bugzilla bug #430274). to get around it, you'll need to first install macports as outlined in the mac os x build prerequisites and install libidl with it. ...
Addon
this property will hold the new addon object. releasenotesuri read only nsiuri a uri for release notes for this version. screenshots read only addonscreenshot[] an array of addonscreenshot objects containing urls of preview images for the add-on. size read only integer the size of the add-on's files in bytes. for an add-on that has not yet been downloaded, this may be an estimated value. sourceuri read only nsiuri the uri that this add-on was installed from. syncguid read only string string guid to identify the add-on in sync. the guid is generated randomly and is made consistent across devices during sync. translators read only addonauthor[] an array of strings holding the translators of the add-on...
AddonInstall
r the state of the installation. error integer if an error has been encountered during the download or install this will hold the error code. sourceuri nsiuri the uri that the add-on is being installed from. file nsifile the file that the add-on is being installed from. this 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...
UpdateInfo
updateinfo objects hold information about available versions of add-ons and are generated as a result of an update check performed by addonupdatechecker. attributes attribute type description version string the version of the update. updateurl string the updateurl that the update can be downloaded from. updatehash string a hash for the update's file. updateinfourl string a url containing simple release notes for the update. targetapplications object[] information about what applications the update is compatible with. each item in the array contains "id", "minversion", and "maxversion" properties. ...
Add-on Manager
ither for a specific install using the addlistener() method or for all installs using the addinstalllistener() method. finding updates add-ons can be checked for updates using the findupdates() method. it must be passed an updatelistener to receive information about compatibility information and new update information. any available update is returned as an addoninstall which is ready to be downloaded and installed. detecting add-on changes requires gecko 7.0(firefox 7.0 / thunderbird 7.0 / seamonkey 2.4) you can also get lists of add-ons that, at startup, were changed in various ways. the getstartupchanges() method lets you find out which add-ons were installed, removed, updated, enabled, or disabled at application startup. for example, to take a look at the add-ons that were dis...
CustomizableUI.jsm
ea or the area in which it was placed previously. if the widget has no default area and/or it has never been placed anywhere, aarea may be null. only fired for api-based widgets. onwidgetdestroyed(awidgetid) fired when widgets are destroyed. awidgetid is the widget that is being destroyed. only fired for api-based widgets. onwidgetinstanceremoved(awidgetid, adocument) fired when a window is unloaded and a widget's instance is destroyed because of this. awidgetid is the widget whose instance is being destroyed, adocument the document in which this is happening. only fired for api-based widgets. onwidgetdrag(awidgetid, aarea) fired both when and after customize mode drag handling system tries to determine the width and height of widget awidgetid when dragged to a different area. aarea will b...
DownloadList
ined when the view has been removed. at this point, the removed view will not receive any more notifications. removefinished() removes downloads from the list that have finished, have failed, or have been canceled without keeping partial data. a filter function may be specified to remove only a subset of those downloads. this method finalizes each removed download, ensuring that any partially downloaded data associated with it is also removed. promise removefinished( function afilterfn ); parameters afilterfn the filter function is called with each download as its only argument, and should return true to remove the download and false to keep it. this parameter may be null or omitted to have no additional filter. ...
source-editor.jsm
d, before calling any other source editor methods. void init( element aelement, object aconfig function acallback ); parameters aelement the dom element in which to place the editor. aconfig an object containing a set of properties used to configure the editor. see the editor configuration object for details. acallback a function that will be called when the editor has been fully loaded and initialized. hasfocus() determines whether or not the editor is currently focused. boolean hasfocus(); parameters none. return value true if the editor is currently focused, otherwise false. redo() redoes the most recently undone change in the editor. boolean redo(); parameters none. return value true if a change was redone, otherwise false. removebreakpoint removes the bre...
JavaScript code modules
ator. timer.jsm a pure js implementation of window.settimeout. webapps.jsm provides an interface to manage open web apps. webrequest.jsm provides an api to add event listeners for the various stages of making an http request. the event listener receives detailed information about the request, and can modify or cancel the request. xpcomutils.jsm contains utilities for javascript components loaded by the js component loader. ...
Localizing without a specialized tool
f sub-directories, you will need to run the mkdir command inside your locale directory and then copy the .dtd or .properties files into that directory. translating to start editing, you will need a text editing application. you can choose to use: notepad++ or notepad2 on windows, vim, gedit or kate on gnu/linux, textwrangler on mac os x. (read more about tools at l10n:tools.) after you have downloaded your editor of choice, type the following command in the same path from above (l10n-mozilla-1.9.2/x-testing/browser/chrome/browser) $ edit l10n-mozilla-1.9.2/x-testing/browser/chrome/browser/aboutcerterror.dtd read the top of the file to get any context on how to translate contained in the notes written by the developers or l10n-drivers. localization notes will look like this: <!-- localization ...
Localization formats
ent for localization is presented in the following manner: msgid "coming soon" msgstr "bientôt disponible" where the value in the "" of the msgid is the english content, and the value in the "" of the msgstr is the translation. msgstr can be longer translations than just the exact above. for example, below is the entire introduction used for a certificate that was presented to those who downloaded firefox during the download day campaign. the french content runs three lines: msgid "certificate_intro" msgstr "" "merci de nous avoir aidé à établir ce record du monde ! " "allez-y et montrez-le en téléchargeant et en imprimant votre " "certificat personnalisé firefox 3 download day." advantages of gettext gettext has very powerful tools to update this site (if you use the actu...
Mozilla Web Developer FAQ
erred if the tags are not explicitly present. cdata sections are supported. xml empty element notation (<foo/>) is supported. white space characters in attribute values are normalized to spaces at parse time, so the original white space never makes it to the dom. this affects data round tripping using hidden form inputs. in versions prior to gecko 1.9/firefox 3, the document is not loaded and rendered incrementally. the layout mode is the (full) standards mode regardless of doctype. css works according to the xml+css rules. html-specific css exceptions do not apply. for example, the body element gets no special treatment. css selectors are case-sensitive. the dom is in the xml mode. namespace-aware variants of methods need to be used when working with elemen...
Investigating leaks using DMD heap scan mode
unwatchdog but the call to ns_setcurrentthreadname. this will keep the watch dog from killing the browser when shut down takes multiple minutes. secondly, you may need to comment out the call to moz_crash("nss_shutdown failed"); in xpcom/build/xpcominit.cpp, as this also seems to trigger when shutdown is extremely slow. you need the cycle collector analysis script find_roots.py, which can be downloaded as part of this repo on github. generating logs the next step is to generate a number of log files. you need to get a shutdown cc log and a dmd log, for a single run. definitions i'll write $objdir for the object directory for your firefox dmd build, $srcdir for the top level of the firefox source directory, and $heapgraph for the location of the heapgraph repo, and $logdir for the location y...
DMD
c you will need root access on the android device. instructions on how to root your device is outside the scope of this document. build build with these options: ac_add_options --enable-dmd prep in order to prepare your device for running fennec with dmd enabled, you will need to do a few things. first, you will need to push the libdmd.so library to the device so that it can by dynamically loaded by fennec. you can do this by running: adb push $objdir/dist/bin/libdmd.so /sdcard/ second, you will need to make an executable wrapper for fennec which sets an environment variable before launching it. (if you are familiar with the recommended "--es env0" method for setting environment variables when launching fennec, note that you cannot use this method here because those are processed too la...
Profiling with Concurrency Visualizer - Performance
concurrency visualizer is an excellent alternative to xperf. in newer versions of visual studio, it is an addon that needs to be downloaded. here are some scripts that you can be used for manipulating the profiles that have been exported to csv: https://github.com/jrmuizel/concurrency-visualizer-scripts ...
Profiling with the Firefox Profiler
builds if you built firefox for windows locally and you would like to use the local symbols with the profiler, you will need to run an additional tool; see profiling with the firefox profiler and local symbols on windows. profiling try builds profiling try builds is supported, but to have symbols in the profiles, they need to be available on the symbol server. symbols for try builds are not uploaded to the symbol server automatically, you need to trigger a "sym" job on treeherder: using treeherder's add new jobs ui, schedule a "sym" job for each platform whose "b" job you want symbols for. (and "symn" if you have an "n" job you want symbols for, i.e. a build job with the "nightly configuration.) profiling firefox mobile firefox 61 for android supports gecko profiler again; see remote profi...
Reporting a Performance Problem
abeled '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 problem and/or send it to the appropriate person. try to give some context about what you were doing when the performance problem arose such as the url you were viewing and what actions were you doing (ex. scrolling on gmail.com). viewing addon performance in geckoview sometimes an ...
about:memory
.". 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 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 eve...
Phishing: a short definition
if implemented to protect millions of users automatically. as most phishing attacks start with unsolicited email messages, a clear starting point is improving spam filters, thus reducing the number of fraudulent messages reaching users. web browser vendors too, are interested in protecting their users from phishing. after all, the browser plays an essential role in the scheme: a fake website is loaded in a browser and here is the maker’s last chance to preventing fraud. since version 2.0, firefox has used google’s safebrowsing service, to detect known web forgeries, and display an alert instead of the fraudulent website. two-factor authentication none of the above anti-phishing measures address the basic problem: username/password combinations are often enough to impersonate users. ente...
A brief guide to Mozilla preferences
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 using the mozilla platform services/common/services-common.js - preferences for some shared services code, this should arguably be included in some other file defaults/pref/services-sync.js - default preferenc...
nglayout.debug.disable_xul_cache
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). possible values and their effects: true: do not cache parsed xul documents and do not save the cache to the xul fastload file on exit; re-read the source files each time the window or dialog needs to be displayed. false: cache xul documents in memory and save the cache to disk on exit to improve performance. (default) see also: http://kb.mozillazine.org...
Preferences system
</preferences> .. ui elements that refer to the preferences above, e.g.: <checkbox id="check1" preference="pref1" label="&check1.label;" accesskey="&check1.accesskey;"/> </prefpane> <prefpane id="pane2" label="&pane2.title;" src="chrome://uri/to/pane.xul"/> </prefwindow> pane content can be specified inline or an external chrome uri supplied for pane content to be loaded in via a dynamic overlay. you should be careful to read the higs for the platforms you are targeting and use the xul preprocessor if necessary to set different window titles as appropriate. you should also be careful to specify the width of the window (in em) as appropriate using the preprocessor for each targeted platform, as well as the height (in em) for platforms where the window size does no...
Debugging out-of-memory problems
this article explains how to debug such problems. ...
Emscripten techniques
this page contains specific emscripten-related techniques. debugging out-of-memory problems a common bug to diagnose with emscripten is where a big game fails due to an out of memory error (oom) somewhere during load time. by the time about:memory is loaded in a new tab and you have clicked the "measure" button to diagnose what's happened, the memory usage causing the spike has gone away, making temporary memory spikes difficult to diagnose. this article explains how to debug such problems. ...
Dynamic Library Linking
this section describes nspr's programming interface to load, unload and resolve symbols in dynamic libraries. it also provides a method by which to condition symbols of statically linked code so that to other clients it appears as though they are dynamically loaded. library linking types these data types are defined for dynamic library linking: prlibrary prstaticlinktable library linking functions the library linking functions are: pr_setlibrarypath pr_getlibrarypath pr_getlibraryname pr_freelibraryname pr_loadlibrary pr_unloadlibrary pr_findsymbol pr_findsymbolandlibrary finding symbols defined in the main executable program pr_loadlibrary cannot open a handle that references the main executable program. (this is admittedly an omission that should be fixed.) however, it i...
PL_HashTableAdd
...
PL_HashTableRemove
to the hash table from which to remove the entry. key a pointer to the key for the entry to be removed. description if there is no entry in the table with the specified key, pl_hashtableremove returns pr_false. if the entry exists, pl_hashtableremove removes the entry from the table, invokes freeentry with the ht_free_entry flag to frees the entry, and returns pr_true. if the table is underloaded, pl_hashtableremove also shrinks the number of buckets by half. remark this function should return prstatus. ...
PR_Connect
uccessfully established or an error occurs. the function uses the lesser of the provided timeout and the os's connect timeout. in particular, if you specify pr_interval_no_timeout as the timeout, the os's connection time limit will be used. if the socket is a udp socket, there is no connection setup to speak of, since udp is connectionless. if pr_connect is invoked on a udp socket, it has an overloaded meaning: pr_connect merely saves the specified address as the default peer address for the socket, so that subsequently one can send and receive datagrams from the socket using pr_send and pr_recv instead of the usual pr_sendto and pr_recvfrom. ...
PR_GetLibraryName
path name of the library, as returned by pr_getlibrarypath. lib the leaf name of the library of interest. returns if successful, returns a new character string containing a constructed path name. in case of error, returns null. description this function constructs a full path name from the specified directory name and library name. the constructed path name refers to the actual dynamically loaded library. it is suitable for use in the pr_loadlibrary call. this function does not test for existence of the specified file, it just constructs the full filename. the way the name is constructed is system dependent. if sufficient storage cannot be allocated to contain the constructed path name, the function returns null. storage for the result is allocated by the runtime and becomes the respons...
PR_LoadLibrary
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. ...
PR_UnloadLibrary
syntax #include <prlink.h> prstatus pr_unloadlibrary(prlibrary *lib); parameters the function has this parameter: lib a reference previously returned from pr_loadlibrary. returns the function returns one of the following values: if successful, pr_success. if unsuccessful, pr_failure. use pr_geterror to find the reason for the failure. description this function undoes the effect of a pr_loadlibrary. after calling this function, future references to the library using its identity as returned by pr_loadlibrary will be invalid. ...
Running NSPR tests
and save the test results as the benchmark. then you can detect regressions of the new version by comparing its test results with the benchmark. known issues other issues with the nspr test suite are: some of the test programs test the accuracy of the timeout of nspr functions. since none of our operating systems is a real-time os, such test programs may fail when the test machine is heavily loaded. some tests, such as pipepong and sockpong, should not be run directly. they will be invoked by their companion test programs (e.g., pipeping and sockping). this is not an issue if you run runtests.sh because runtests.sh knows not to run such test programs directly. ...
NSS FAQ
Mozilla › Projects › NSS › FAQ
ntegration process. however, there is little or no documentation currently available for the rest of the nss api. if your application requires sophisticated certificate management, smart card support, or hardware acceleration, your integration effort will be more extensive. where can i download the nss tools? binary builds of nss for several platforms including the command-line tools can be downloaded from http://ftp.mozilla.org/pub/mozilla.o...y/nss/releases/. nspr, which you will need as well, can be downloaded from http://ftp.mozilla.org/pub/mozilla.org/nspr/releases/. how can i learn more about tls? see https://developer.mozilla.org/docs/glossary/tls. licensing questions how is nss licensed? nss is available under the mozilla public license, version 2. is nss available outside the un...
Introduction to Network Security Services
table. platform for 32-bit cpus for 64-bit cpus solaris/sparc libfreebl_pure32_3.so libfreebl_hybrid_3.so hpux/parisc libfreebl_pure32_3.sl libfreebl_hybrid_3.sl aix (planned for a future release) libfreebl_pure32_3_shr.a libfreebl_hybrid_3_shr.a an application should not link against these libraries, because they are dynamically loaded by nss at run time. linking the application against one or the other of these libraries may produce an application program that can only run on one type of cpu (e.g. only on 64-bit cpus, not on 32-bit cpus) or that doesn't use the more efficient 64-bit code on 64-bit cpus, which defeats the purpose of having these shared libraries. on platforms for which these shared libraries exist, nss 3.2 wil...
JSS Provider Notes
l jce (java cryptography extension) algorithms. these algorithms have at various times been export-controlled by the us government. sun therefore requires that jar files implementing jce algorithms be digitally signed by an approved organization. netscape has this approval and signs the official builds of jss32.jar. at runtime, the jre automatically verifies this signature whenever a jss class is loaded that implements a jce algorithm. the verification is transparent to the application (unless it fails and throws an exception). if you are curious, you can verify the signature on the jar file using the jarsigner tool, which is distributed with the jdk. if you build jss yourself from source instead of using binaries downloaded from mozilla.org, your jar file will not have a valid signature. thi...
Mozilla-JSS JCA Provider notes
thms. these algorithms have at various times been export-controlled by the us government. jre therefore requires that jar files implementing jce algorithms be digitally signed by an approved organization. the maintainers of jss, sun, red hat, and mozilla, have this approval and signs the official builds of jss4.jar. at runtime, the jre automatically verifies this signature whenever a jss class is loaded that implements a jce algorithm. the verification is transparent to the application (unless it fails and throws an exception). if you are curious, you can verify the signature on the jar file using the jarsigner tool, which is distributed with the jdk. if you build jss yourself from source instead of using binaries downloaded from mozilla.org, your jar file will not have a valid signature. this m...
JSS
Mozilla › Projects › NSS › JSS
ncepts 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 download binaries, source, and javadoc view the source online testing jss tests frequently asked questi...
NSS 3.14.2 release notes
0986) sqlite has been updated to 3.7.15. note: please apply the patch in https://bugzilla.mozilla.org/show_bug.cgi?id=837799 if you build nss with the system sqlite library and your system sqlite library is older than 3.7.15. bug 816853 - when using libpkix for certificate validation, applications may now supply additional application-defined trust anchors to be used in addition to those from loaded security tokens, rather than as an alternative to. (https://bugzilla.mozilla.org/show_bug.cgi?id=816853) bug 772144 - basic support for running nss test suites on android devices.this is currently limited to running tests from a linux host machine using an ssh connection. only the sshdroid app has been tested. bug 373108 - fixed a bug where, under certain circumstances, when applications supp...
NSS 3.14 release notes
ased under a mpl 1.1/gpl 2.0/lgpl 2.1 tri-license. for more information about mpl 2.0, please see http://www.mozilla.org/mpl/2.0/faq.html. for an additional explantation on gpl/lgpl compatibility, see security/nss/copying in the source code. export and des cipher suites are disabled by default. non-ecc aes and triple des cipher suites are enabled by default. nss 3.14 source tarballs can be downloaded from https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_14_rtm/src/. the cvs tag is nss_3_14_rtm. new in nss 3.14 the sections that follow discuss specific changes in nss 3.14 in more detail. support for tls 1.1 (rfc 4346) has been added (https://bugzilla.mozilla.org/show_bug.cgi?id=565047). to better support tls 1.1 and future versions of tls, a new version range a...
NSS 3.18 release notes
rogram has new command-line options -c, -d, -b and -r. use -c one, two or three times to print information about the certificates received from a server, and information about the locally found and trusted issuer certificates, to diagnose server side configuration issues. it is possible to run tstclnt without providing a database (-d). a pkcs#11 library that contains root ca certificates can be loaded by tstclnt, which may either be the nssckbi library provided by nss (-b) or another compatible library (-r). new functions in certdb.h sec_checkcrltimes - check the validity of a crl at the given time. sec_getcrltimes - extract the validity times from a crl. in p12.h sec_pkcs12decoderrenamecertnicknames - call an application provided callback for each certificate found ...
NSS 3.21 release notes
new functions in nss.h nss_optionset - sets nss global options nss_optionget - gets the current value of nss global options in secmod.h secmod_createmoduleex - create a new secmodmodule structure from module name string, module parameters string, nss specific parameters string, and nss configuration parameter string. the module represented by the module structure is not loaded. the difference with secmod_createmodule is the new function handles nss configuration parameter strings. in ssl.h ssl_getpreliminarychannelinfo - obtains information about a tls channel prior to the handshake being completed, for use with the callbacks that are invoked during the handshake ssl_signatureprefset - configures the enabled signature and hash algorithms for tls ssl_s...
NSS Sample Code Sample1
eypublickey **pubkey); int wrapkey(pk11symkey *key, seckeypublickey *pubkey, secitem **data); // export raw key (unwrapped) do not use int rawexportkey(pk11symkey *key, secitem **data); char *mservername; // these items represent data that might be stored // in files or in a configuration file secitem *mwrappedenckey; secitem *mwrappedmackey; // these are the runtime keys as loaded from the files pk11symkey *menckey; pk11symkey *mmackey; }; server::server(const char *servername) : mservername(0), mwrappedenckey(0), mwrappedmackey(0), menckey(0), mmackey(0) { // copy the server name mservername = pl_strdup(servername); } server::~server() { if (mservername) pl_strfree(mservername); if (mwrappedenckey) secitem_freeitem(mwrappedenckey, pr_true); if (mwrappedm...
NSS Third-Party Code
e compiled into the nss libraries, and code that is only used for testing. note that not all code that can be compiled into the nss libraries necessarily is. ...
PKCS11 Implement
en and was generated by nss. all the fields defined by pkcs #11 for certificates are set. the nss also sets the cka_id and cka_label attributes for the token. currently, the cka_id attribute is set to the modulus for rsa or to the public value on dsa. the nss may hash this value in the future. in either case, nss does set the cka_id attribute and expects it to remain the same. if a certificate is loaded, the value of the certificate's cka_id attribute must match the value of the cka_id attribute for the corresponding private key, and the value of the certificate's cka_label attribute must also match the value of the cka_label attribute for the private key. for private keys that don't include certificates, nss doesn't set the cka_label attribute, or sets it to null, until it receives the certific...
Python binding for NSS
ge and cert type entities which feature prominently during cert validation. certificate() constructor signature changed from certificate(data=none, der_is_signed=true) to certificate(data, certdb=cert_get_default_certdb(), perm=false, nickname=none) this change was necessary because all certs should be added to the nss temporary database when they are loaded, but earlier code failed to to that. it's is not likely that an previous code was failing to pass initialization data or the der_is_signed flag so this change should be backwards compatible. fix bug #922247, pkcs12decoder.database_import() method. importing into a nss database would sometimes fail or segfault. error codes and descriptions were updated from upst...
NSS environment variables
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) use libpkix, rather ...
NSS tools : certutil
g (pty) ltd. id < 1> rsa 40defeeb522ade11090eacebaaf1196a172127df example domain administrator cert < 2> rsa 1d0b06f44f6c03842f7d4f4a1dc78b3bcd1b85a5 john smith user cert there are ways to narrow the keys listed in the search results: * to return a specific key, use the -n name argument with the name of the key. * if there are multiple security devices loaded, then the -h tokenname argument 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 ca...
sslerr.html
memory allocation failure. sec_error_untrusted_issuer -8172 peer's certificate issuer has been marked as not trusted by the user. sec_error_untrusted_cert -8171 peer's certificate has been marked as not trusted by the user. sec_error_duplicate_cert -8170 certificate already exists in your database. sec_error_duplicate_cert_name -8169 downloaded certificate's name duplicates one already in your database. sec_error_adding_cert -8168 error adding certificate to database. sec_error_filing_key -8167 error refiling the key for this certificate. sec_error_no_key -8166 the private key for this certificate cannot be found in key database. sec_error_cert_valid -8165 this certificate is v...
certutil
sulting (pty) ltd. id < 1> rsa 40defeeb522ade11090eacebaaf1196a172127df example domain administrator cert < 2> rsa 1d0b06f44f6c03842f7d4f4a1dc78b3bcd1b85a5 john smith user cert there are ways to narrow the keys listed in the search results: o to return a specific key, use the -n name argument with the name of the key. o if there are multiple security devices loaded, then the -h 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 a...
Network Security Services
. 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 - archived version ca certificates pre-loaded into nss mozilla ca certificate policy list of pre-loaded ca certificates consumers of this list must consider the trust bit setting for each included root certificate. more information, extracting roots and their trust bits nss is built on top of netscape portable runtime (nspr) netscape portable runtime nspr project...
Necko Architecture
necko provides the following libraries: necko - core networking functionality. ...
Necko Interfaces Overview
tp) maps uri string to nsiuri instance via newuri method creates nsichannel instance from nsiuri instance via newchannel method nsistreamlistener : nsirequestobserver implemented by the consumer of a nsichannel instance passed to nsichannel::asyncopen method nsirequestobserver::onstartrequest - notifies start of async download nsistreamlistener::ondataavailable - notifies presence of downloaded data nsirequestobserver::onstoprequest - notifies completion of async download, possibly w/ error nsiloadgroup : nsirequest attribute of a nsirequest channel impl adds itself to its load group during invocation of asyncopen channel impl removes itself from its load group when download completes load groups in gecko own all channels used to load a particular page (until the channels comple...
Rhino Debugger
tion will display a file-selection dialog box prompting you for the location of a script to load. the selected file will be compiled and displayed in a new window. running scripts you may select the file->run menu item on the menu bar to execute javascript scripts contained in files. this action will display a file-selection dialog box prompting you for the location of a script to execute. the loaded script will be run in a new thread and control will be given to the debugger on its first instruction. controlling execution the debugger provides the following facilities for you to control the execution of scripts you are debugging: step into to single step entering any function calls, you may do any of the following: select the debug->step into menu item on the menu bar press the ...
Rhino history
e 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 are no longer in use they can be collected like any other java object. rhino was released to mozilla.org in april 1998. originally rhino classfile generation had been held back from release. however the licensees of rhino have now agreed to release all of rhino to open source, including class file generation. since its release to open source, rhino...
Rhino JavaScript compiler
note that the top-level functions available to the shell (such as print) are not available to compiled scripts when they are run outside the shell. ...
Rhino overview
cases by calling isinterpreterclass() in the context class. if it is the interpreter class, call the getinterpretersecuritydomain() method of context to obtain the security domain of the currently executing interpreted script or function. otherwise, it must be a generated class, and an embedding can call getsecuritydomain() in the class implementing securitysupport. when the class was defined and loaded, the appropriate security domain was associated with it, and can be retrieved by calling this method. once the security domain has been determined, an embedding can perform whatever checks are appropriate to determine whether access should be allowed. ...
The JavaScript Runtime
identifiers. conceptually, all accessors are converted to strings in order to perform the lookup of the property in the object. however, this is not the implementation used in practice because a number to string conversion is too expensive to be performed on every array access. instead, every property accessor method in scriptable (has, get, set, remove, getattributes, and setattributes) has overloaded forms that take either a string or an int argument. it is the responsibility of the caller to invoke the appropriate overloaded form. for example, evaluating the expression obj["3"] will invoke the get(int, scriptable) method even though the property name was presented in the script as a string. similarly, values of numbers that do not fix in integers (like 1.1 and 0x100000000) must be converted ...
Rhino scopes and contexts
ng sealedsharedscope.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...
Shumway
perience met by your users who are running that version of shumway. hopefully, this displays your content with acceptable quality. the next step is to use the inspector included as one of shumway's examples. it can be run locally through a web server or you can use the version hosted on mozilla's github. several methods exist to allow inspector access to your swf file. once your flash content is loaded, you can see how shumway manages it in detail. several buttons are available at the bottom of the screen to enable or disable various shumway options. note: if your applet runs at an abnormal speed, try toggling "turbo" at the bottom of the inspector window. you may wish to do this before opening your swf file. limitations of shumway might be encountered through testing. there are two places ...
Creating JavaScript tests
ty of wildly varying hardware plaforms, from phones all the way up to servers. even tests that check for polynomial time complexity will start to fail in a few years when they have sped up enough to run faster than the granularity of the os scheduler or when run on platforms with higher latencies than your development workstation. these tests will also show up as infrequent oranges on our heavily loaded test machines, lowering the value of our test suite for everyone. just don't do it, it's never worth it. do not add performance tests to the test suite. it is not generally even possible to tell if the speed of any particular feature is going to be important in the real world without running a real-world benchmark. it is very hard to write a good real-world benchmark. for this reason, the best ...
Hacking Tips
if gdb does not load the unwinder by default, you can force it to, by using the source command with the js-gdb.py file. setting a breakpoint in the generated code (from gdb, x86 / x86-64, arm) to set a breakpoint the generated code of a specific jsscript compiled with ionmonkey. set a breakpoint on ...
Index
ments guide, needscontent, needsexample, spidermonkey no summary! 539 spidermonkey releases spidermonkey the easiest way to fetch the version corresponding to the current firefox release is to visit the treeherder page for the release repository and click on the first sm(pkg) link you see. that will open a small window in the bottom left with a line like "artifact uploaded: mozjs-57.0.1.tar.bz2". 540 spidermonkey 1.8 spidermonkey spidermonkey 1.8 has one known significant regression from 1.7. 541 spidermonkey 1.8.5 spidermonkey spidermonkey 1.8.5 is supported on all the platforms where firefox 4 runs. 542 spidermonkey 1.8.7 spidermonkey draft in progress - this is a draft, and right now it's mostly just...
Functions
d using jsop_{get,set,call}{arg,local} instructions. some of these can even be fused with other operations into combo instructions like jsop_getargprop, jsop_forlocal, and jsop_inclocal. because arguments and locals can't be deleted, this optimization is available to all functions, and eval does not interfere with it. but a with block can: function f(s) { eval(s); print(s); // s can be loaded with getarg with (obj) { print(s); // no getarg here; s might refer to obj.s } } upvar instructions. jsop_{get,call}upvar (in algol-like functions only, i think?) todo dslot instructions. jsop_{get,call}dslot (in flat closures only) todo gvar instructions. outside all functions, if a name definitely refers to a global for which we have seen a var, const, or fun...
Introduction to the JavaScript shell
6 2 00017: add 00018: call 1 00021: pop 00022: stop source notes: 0: 0 [ 0] newline 1: 3 [ 3] decl offset 0 2: 7 [ 4] newline 3: 18 [ 11] xdelta 4: 18 [ 0] pcbase offset 11 dissrc([function]) disassembles the javascript bytecode for the entire program, or for the specified function, showing the source lines. this function only works with programs loaded from files, either using the -f flag on launching the shell, or by using the load() function. if your program includes a function, dostuff(), like this: function dostuff(input) { print("enter a number: "); var n1 = readline(); print("enter another one: "); var n2 = readline(); print("you entered " + n1 + " and " + n2 + "\n"); } calling dissrc(dostuff) function would give this output: ...
JSClass.flags
specify this option. one of jsclass_foreground_finalize and jsclass_background_finalize must be specified. jsclass_background_finalize it is safe to finalize objects of this class on a background thread. if this class has a finalizer that can be safely run concurrently with the main thread then this option can be specified. it results in finalization work being offloaded to another thread which improves performance. one of jsclass_foreground_finalize and jsclass_background_finalize must be specified. jsclass_implements_barriers obsolete since jsapi 43 correctly implements gc read and write barriers. jsclass_new_enumerate obsolete since jsapi 37 this class's enumerate hook is actually a jsnewenumerateop, not a jsenumerateo...
JSObjectOps.lookupProperty
ing it. warning! jsobjectops is not a supported api. details of the api may change from one release to the next. this documentation should be considered spidermonkey internals documentation, not api documentation. see bug 408416 for details. the jsobjectops.lookupproperty callback is called for every property access (except when a higher-level callback, such as jsobjectops.getproperty, is overloaded in a way that does not call lookupproperty). syntax typedef jsbool (*jslookuppropop)(jscontext *cx, jsobject *obj, jsid id, jsobject **objp, jsproperty **propp); name type description cx jscontext * pointer to the js context in which the property lookup is happening. obj jsobject * the object whose properties are being searched. id ...
SpiderMonkey 52
spidermonkey 52 is the javascript engine that shipped in firefox 52. ...
SpiderMonkey releases
ble source package. we are very limited in our ability to support older versions, including those labeled as "releases" on this page. the easiest way to fetch the version corresponding to the current firefox release is to visit the treeherder page for the release repository and click on the first sm(pkg) link you see. that will open a small window in the bottom left with a line like "artifact uploaded: mozjs-57.0.1.tar.bz2". past releases spidermonkey 52 spidermonkey 45 spidermonkey 38 spidermonkey 31 spidermonkey 24 spidermonkey 17 spidermonkey 1.8.8 spidermonkey 1.8.7 spidermonkey 1.8.5 spidermonkey 1.8 ...
WebReplayRoadmap
rewind, which should make writing a complete windows port easier. cloud integration (partially implemented) storing recordings in the cloud and interacting with them via the debugger could streamline several features described above: difficulties when recording and replaying on different machines with incompatible firefox builds or operating systems will be smoothed out. recordings can be uploaded, and cloud services can locate the correct build and os needed to replay them. management of a corpus of recordings (some which may have been made with different builds or operating systems) will be easier to manage, with shared storage in the cloud. expensive dynamic analyses are easier to run in the cloud, allowing a high level of parallelism without impacting users. the cloud should not be...
Setting up an update server
s filename, its sha512 hash, and its file size in bytes. ...
Gecko events
bar is supported: yes event_minimize_start a window object is about to be minimized or maximized is supported: no event_minimize_end a window object has been minimized or maximized is supported: no event_document_load_start is supported: yes event_document_load_complete the loading of the document has completed. is supported: yes event_document_reload the document contents are being reloaded. is supported: yes event_document_load_stopped the loading of the document was interrupted. 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 document have changed. is supported: no event_property_changed is supported: no event_selection_changed is...
Manipulating bookmarks using Places
id, aproperty, aisannotationproperty, avalue) { myextension.dosomething(); }, onitemvisited: function(abookmarkid, avisitid, time) {}, onitemmoved: function(aitemid, aoldparent, aoldindex, anewparent, anewindex) {}, queryinterface: xpcomutils.generateqi([components.interfaces.nsinavbookmarkobserver]) }; // an extension var myextension = { // this function is called when my add-on is loaded onload: function() { bmsvc.addobserver(myext_bookmarklistener, false); }, // this function is called when my add-on is unloaded onunload: function() { bmsvc.removeobserver(myext_bookmarklistener); }, dosomething: function() { alert("did something."); } }; see also nsinavbookmarksservice nsinavbookmarkobserver places using xpcom without chrome - bookmark observer ...
Using the Places annotation service
overview of the places database design, see the places database. most methods in the service are duplicated with one method labeled as a 'page annotation' taking an nsiuri and the others labeled as an 'item annotation' and taking the id of an item in the places database. which one to use is usually dictated by the application. uri's are easier to use for services that want to annotate a web page loaded in the browser, while id's are easier to use for services already working with the places database. id's also offer the ability to add annotations to containers and queries of the database. creating the annotation service the annotation contract id is @mozilla.org/browser/annotation-service;1 var annotationservice = components.classes["@mozilla.org/browser/annotation-service;1"] ...
Using the Places favicon service
e favicon will be picked up quickly. most of the time, the favicon will be served from the browser's cache and will have minimal performance impact. this expiration time is not the time that the favicon will be deleted. expiration is handled by browser/components/places/src/nsnavhistoryexpire.cpp as described in places design. the expiration time is only used to determine whether data should be reloaded from the network (or cache) or whether the version in the database is fresh enough. getting favicon images you can use favicons in the browser ui using special annotation uris. nsifaviconservice.getfaviconimageforpage() returns an annotation uri for the favicon for a given page, and nsifaviconservice.getfaviconlinkforicon() returns an annotation uri for the given favicon. the annotation servic...
SMILE
implemented in firefox ("fuel") and in thunderbird ("steel"). objects extiapplication objects exticonsole extieventitem extieventlistener extievents extiextension extiextensions extipreference extipreferencebranch extisessionstorage smileiapplication objects smileibookmarkroots smileiwindow smileibrowsertab smileiapplication xpcom although the extiapplication object is preloaded into xul scripts, it is not preloaded into javascript xpcom code. the object needs to be accessed like any other xpcom service: var application = components.classes["@mozilla.org/smile/application;1"].getservice(components.interfaces.smileiapplication); ...
STEEL
ion. the library has also been implemented in firefox ("fuel") and in seamonkey ("smile"). objects extiapplication objects extiapplication exticonsole extieventitem extieventlistener extievents extiextension extiextensions extipreference extipreferencebranch extisessionstorage steeliapplication objects steeliapplication xpcom although the steel steeliapplication object is preloaded into xul scripts, it is not preloaded into javascript xpcom code. the object needs to be accessed like any other xpcom service: var application = components.classes["@mozilla.org/steel/application;1"].getservice(components.interfaces.steeliapplication); other resources steel development plan. bug 408370 bug 1278067 ...
extIApplication
ul. restart() attempts to restart the application. it is possible for the restart to be canceled. boolean restart() return value boolean value indicating whether the restart was successful. getextensions(acallback) calls acallback with the list of installed extensions. void getextensions(extiextensionscallback acallback) return value none. xpcom although the application object is preloaded into xul scripts, it is not preloaded into javascript xpcom code. the object needs to be accessed like any other xpcom service: var application = components.classes["@mozilla.org/fuel/application;1"].getservice(components.interfaces.fueliapplication); see also fuel (firefox), steel (thunderbird) and smile (seamonkey) ...
Creating a Python XPCOM component
can achieve a copy of binary of pyxpcom from pythonext; simply unpack xpi and take everything you need. if you wish to use pyxpcom from a normal python executable, you will need to tell python where it can find the pyxpcom library. this is probably best done by setting a pythonpath variable pointing at the 'bin/python' directory in the application. this is not necessary when your components are loaded by mozilla as the python loader modifies sys.path. then you can import xpcom in any python module (mostly, in your component). defining the interface make a file named "nsipysimple.idl" to define the interface: #include "nsisupports.idl" [scriptable, uuid(2b324e9d-a322-44a7-bd6e-0d8c83d94883)] interface nsipysimple : nsisupports { attribute string yourname; void write( ); void change...
XPCOM glue
Mozilla › Tech › XPCOM › Glue
en linkage: dependent glue (dependent on xpcom.dll) xpcom modules, i.e. extension or xulrunner application components, should use the dependent glue. code which wishes to use only frozen symbols but can tolerate a load-time dependency on xpcom.dll should link against xpcomglue_s.lib and xpcom.lib. it should not link against xpcom_core.lib. this is the case for xpcom components, because they are loaded into mozilla which already 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 co...
Component Internals
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 languages and other "non-native" languages usually have no way to build native libraries. in order to have "non-native" xpcom components work, xpcom must have a special component loader which knows how to deal with these type of components. xpconnect, for example, provides a component loader that makes the various types, including the interfaces and their parameters, available...
Using XPCOM Utilities to Make Things Easier
all the macros follow the same general pattern. all of these macros work on an array of structures represented by the components parameter. each structure describes a cid that is to be registered with xpcom. the first parameter for each of these macros is an arbitrary string that names the module. in a debugging environment, this string will be printed to the screen when the component library is loaded or unloaded. you should pick a name that makes sense and helps you keep track of things. the four required parts[other-parts] of the structure contain the following information: a human readable class name the class id (cid) the contract id (an optional but recommended argument) a constructor for the given object static const nsmodulecomponentinfo components[] = { { "pretty class name",...
Receiving startup notifications
the case, so be sure to remove that when migrating existing code. additionally, the earliest startup time notification you can receive is now profile-after-change. your add-on will not receive xpcom-startup or app-startup notifications. the startup process during application startup, the application'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. rece...
Components.utils.import
components.utils.import was introduced 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 ...
Components.utils.importGlobalProperties
s the objects, such as services.jsm const {blob, file, services} = cu.import("resource://gre/modules/services.jsm", {}); reference: stackoverflow :: use blob on firefox add-on hiddendomwindow the hidden domwindow has all of these objects automatically imported. the downside of using hiddendomwindow is that on startup of firefox, the hiddendomwindow objects cannot be accessed until it is fully loaded. therefore readystate must be checked, if it is not complete, then a load listener must be attached. once readystate is complete then the objects can be used. for example this is how to ues the file object. var domfile = services.appshell.hiddendomwindow.file('/path/to/file'); xpcom components some objects have an xpcom alternative, which typically allows more flexibility then the dom version...
Components.utils
vascript object. getweakreference() gets a weak reference for the object passed in. import() loads a js module into the current script, without sharing a scope. importglobalproperties() specify a list of constructors to import into the scope. isxraywrapper() test whether a given object is an xray or not. unload() unloads a js module loaded with import(). isdeadwrapper() determines whether this object is backed by a deadobjectproxy. lookupmethod() looks up a native (i.e. declared in the interface) method or property of an xpcom object. serves the same purpose as xpcnativewrapper. makeobjectpropsnormal() ensures that all functions come from the specified object's scope, and aren't cross-compartmen...
Components.utils.unload
ntax components.utils.unload( url ); parameters url 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/ ...
NS_InitXPCOM3
ile needed for the abindirectory parameter to ns_initxpcom3. many of the xpcom glue functions and classes are also available prior to xpcom initialization, including for example nsembedcstring and nscomptr. initializing xpcom with static modules allows the application to easily define modules that are linked into the application's executable. this can be a performance improvement over dynamically loaded xpcom modules. history this function was finalized for mozilla 1.8. see bug 296561 for details. see also ns_initxpcom2, ns_shutdownxpcom ...
imgICache
chrome if true, evict only chrome images. if false, evict everything except chrome images. findentryproperties() find properties used to get properties such as 'type' and 'content-disposition' 'type' is a nsisupportscstring containing the images' mime type such as 'image/png' 'content-disposition' will be a nsisupportscstring containing the header if you call this before any data has been loaded from a uri, it will succeed, but come back empty. nsiproperties findentryproperties( in nsiuri uri ); parameters uri the uri to look up. return value null if the url was not found in the cache. removeentry() evict images from the cache. void removeentry( in nsiuri uri ); parameters uri the uri to remove. exceptions thrown ns_ok if a uri was rem...
mozIAsyncFavicons
hose favicon is being set. afaviconuri uri of the favicon to associate with the page. aforcereload if false, we try to reload the favicon only if we do not have it or it has expired from the cache. setting to true causes us to reload the favicon even if we have a usable copy. afaviconloadtype set to nsifaviconservice.favicon_load_private if the favicon is loaded from a private browsing window. set to nsifaviconservice.favicon_load_non_private otherwise acallback optional once we're done setting and/or fetching the favicon, we invoke this callback. replacefavicondata() sets the data for a given favicon uri either by replacing existing data in the database or taking the place of otherwise fetched icon data when calling setandfetchfaviconforp...
mozIStorageConnection
e=") is full or the entire file is read. the cache must be active on the database for this to work. this means that you must have a transaction open on the connection, or have a transaction open on another connection that shares the same pager cache. this cached data will go away when the transaction is closed. this preload operation can dramatically speed up read operations because the data is loaded as one large block. normally, pages are read in on demand, which can cause many disk seeks. void preload(); parameters none. removefunction() deletes a custom sql function that was created with either mozistorageconnection.createfunction() or mozistorageconnection.createaggregatefunction(). void removefunction( in autf8string afunctionname ); parameters afunctionname the name of...
nsIAccessibleEvent
nd 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 have changed. event_property_changed 0x0030 0x002c event_selection_changed 0x0031 0x002d event_te...
nsIAlertsService
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"]. getservice(components.interfaces.nsia...
nsIAppStartup
urns a javascript object with events from startup and the timestamps indicating when they occurred. parameters none. return value a javascript object with the following fields. keys are the event names and their values are the times. events that didn't occur are not in the object. event identifier (key) description main time at which main application core was loaded. note: only available with libxul builds. firstpaint time the first paint occurred. note: only available with libxul builds. sessionrestored time session restore finished. example this example logs startup time information to the console. var aconsoleservice = components.classes["@mozilla.org/consoleservice;1"] .getse...
nsIApplicationCacheChannel
transferred through a redirect. exceptions thrown ns_error_already_opened if set after calling asyncopen() on the channel. inheritapplicationcache boolean true if the channel will ask its notification callbacks for an application cache if one is not explicitly provided. the default value is true. exceptions thrown ns_error_already_opened if set after calling asyncopen() on the channel. loadedfromapplicationcache prbool true if the resource was loaded from the application cache, otherwise false. this value may be false even if the resource is assigned to an application cache if, for example, it was loaded as a fallback. read only. methods markofflinecacheentryasforeign() a shortcut method to mark the cache item of this channel as 'foreign'. see the 'cache selection algorithm' and ca...
nsIApplicationCacheNamespace
ant 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 top-level loads of resources in this namespace should be placed into the application cache. this can be combined with namespace_fallback to provide a fallback entry in the data attribute. methods init() initializes the namespace. void init( in unsigned long i...
nsIChannel
attempts to set it to null must throw. note: this is distinctly different from the http referer (referring uri), which is typically the page that contained the original uri (accessible from nsihttpchannel.) owner nsisupports the owner, corresponding to the entity that is responsible for this channel. used by the security manager to grant or deny privileges to mobile code loaded from this channel. note: this is a strong reference to the owner, so if the owner is also holding a strong reference to the channel, care must be taken to explicitly drop its reference to the channel. securityinfo nsisupports transport-level security information (if any, else null) corresponding to the channel, normally presented through the interfaces nsitransportsecurityinfo ...
nsIChannelPolicy
nnel redirects. channels can be created with this interface placed in the property bag and upon redirect, the interface can be transferred from the old channel to the new channel. attributes attribute type description contentsecuritypolicy nsisupports a nsicontentsecuritypolicy object to determine if the load should be allowed. loadtype unsigned long indicates what type of content is being loaded, for example nsicontentpolicy::type_image. ...
nsIChromeFrameMessageManager
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. aallowdelayedload if true, the script will be loaded when the remote frame becomes available; otherwise, the script will only be loaded if the frame is already available. removedelayedframescript() removes a script from the list of scripts supporting delayed load. void removedelayedframescript( in astring aurl ); parameters aurl the url of the script to remove from the list of scripts supporting delayed load. see also content...
nsIComponentManager
in gecko 8 to let bootstrapped add-ons provide content at chrome:// uris. until gecko 10 you had to call this method manually from within the add-on's startup() method (with a matching removebootstrappedmanifestlocation() call in the add-on's shutdown() method). if you're targeting gecko 10 or higher there should be no need to call this method, since the bootstrapped add-on's chrome.manifest is loaded automatically now. void addbootstrappedmanifestlocation( in interface nsilocalfile alocation ); parameters alocation the directory or xpi from which to load the chrome.manifest. createinstance() creates an instance of the class specified by classid. unlike getservice, this returns a new instance each time it is called. (see also nsifactory.createinstance.) void createinstance( in n...
nsIContentFrameMessageManager
it enables these scripts to receive messages from the chrome process and send messages back to the chrome process. frame scripts can send either synchronous or asynchronous messages to the chrome process: for details on these messaging apis see the documentation for the nsicontentframemessagemanager's parent classes nsisyncmessagesender and nsimessagesender. ...
nsIContentSecurityPolicy
riggers violation report sending given a uri and reason. the uri may be null, in which case "self" is sent. void sendreports( in astring blockeduri, in astring violateddirective ); parameters blockeduri the uri that violated the policy. violateddirective the directive that was violated. shouldload() delegate method called by the service when sub-elements of the protected document are being loaded. given a bit of information about the request, decides whether or not the policy is satisfied. calls to this may trigger violation reports when queried, so this value should not be cached. short shouldload( in unsigned long acontenttype, in nsiuri acontentlocation, in nsiuri arequestorigin, in nsisupports acontext, in acstring amimetypeguess, in nsisupports aextra ); parameters acon...
nsICookiePermission
nsider freezing this interface. methods canaccess() tests whether or not the given uri/channel may access the cookie database, either to set or get cookies. nscookieaccess canaccess( in nsiuri auri, in nsiuri afirsturi, obsolete since gecko 1.9 in nsichannel achannel ); parameters auri the uri trying to access cookies. afirsturi the uri initiated by the user that resulted in auri being loaded. achannel the channel corresponding to auri. return value one of the nscookieaccess values: access_default, access_allow, or access_deny. cansetcookie() tests whether or not the given uri/channel may set a specific cookie. this method is always preceded by a call to canaccess(). it may modify the issession and expiry attributes of the cookie via the aissession and aexpiry parameters, in order to...
nsIDOMFile
this is also used by the datatransfer object to describe files dragged into a web application using drag and drop. ...
nsIDOMFontFace
te type description format domstring the font format. read only. localname domstring null if not a src:local(...) rule. read only. metadata domstring xml metadata from woff file(if any). read only. rule nsidomcssfontfacerule null if no associated @font-face rule. read only. srcindex long index in the rule's src list, -1 if no @font-face rule. read only. uri domstring null if not a downloaded font, that is local. read only. see also nsidomfontfacelist ...
nsIDOMHTMLSourceElement
e source element allows authors to specify multiple media resources for media elements. it does not specify anything on its own. attributes attribute type description src domstring the src attribute gives the address of the media resource. the value must be a valid url. this attribute must be present. note that dynamically manipulating this value after the page has loaded has no effect on the containing element; instead, change the src attribute of that element (audio or video) instead. type domstring the type attribute gives the type of the media resource, to help the user agent determine if it can play this media resource before fetching it. if specified, its value must be a valid mime type. the codecs parameter may be specified and might be neces...
nsIDOMWindowInternal
esizeto(in long width, in long height) void resizeby(in long widthdif, in long heightdif) void scroll(in long xscroll, in long yscroll) nsidomwindow window interface's open() method loads the specified resource into the browsing context (window, <iframe> or tab) with the specified name. ...
nsIDownloadProgressListener
rd 3.0 / seamonkey 2.0) void onlocationchange( in nsiwebprogress awebprogress, in nsirequest arequest, in nsiuri alocation, in nsidownload adownload ); parameters awebprogress the nsiwebprogress instance used by the download manager to monitor downloads. arequest the nsichannel that changed state. this parameter will not be null. alocation the uri of the file being downloaded. adownload the nsidownload object representing the file being downloaded. onprogresschange() called when the download progress level changes for a download. void onprogresschange( in nsiwebprogress awebprogress, in nsirequest arequest, in long long acurselfprogress, in long long amaxselfprogress, in long long acurtotalprogress, in long long amaxtotalprogress, in nsidownload ad...
nsIEditorDocShell
attributes attribute type description editable boolean this docshell is editable. read only. editor nsieditor gets or sets the editor for the content document. haseditingsession boolean this docshell has an editing session. read only. methods makeeditable() make this docshell editable, setting a flag that causes an editor to get created, either immediately, or after a url has been loaded. void makeeditable( in boolean inwaitforuriload ); parameters inwaitforuriload true to wait for a uri before creating the editor. ...
nsIFocusManager
) window, or null if no window that is part of the application is active. setting the activewindow raises it, and focuses the current child window's current element, if any. setting this to null or to a non-top-level window throws an ns_error_invalid_arg exception. focusedelement nsidomelement the element that is currently focused. this will always be an element within the document loaded in focusedwindow or null if no element in that document is focused. read only. focusedwindow nsidomwindow the child window within the activewindow that is focused. this will always be activewindow, a child window of activewindow or null if no child window is focused. setting the focusedwindow changes the focused window and raises the toplevel window it is in. if the current focus w...
nsIFrameLoader
. ay the y coordinate of the mouse. abutton which button was clicked, if any. aclickcount the number of clicks comprising the mouse button event, if any. amodifiers the modifier keys in effect at the time of the event. aignorerootscrollframe optional whether or not to ignore the root scroll frame. native code only!updatepositionandsize updates the position and size of the subdocument loaded by this frameloader. void updatepositionandsize( in nsiframe aiframe ); parameters aiframe the nsiframe for the content node that owns this frameloader. see also content process event handling nsiframeloaderowner nsiframemessagelistener nsichromeframemessagemanager nsidomwindowutils ...
nsIGlobalHistory2
mple mailbox:, for the main nsiuri and the referrer. void adduri( in nsiuri auri, in boolean aredirect, in boolean atoplevel, in nsiuri areferrer ); parameters auri the nsiuri of the page being added. aredirect whether the uri was redirected to another location; this is true for the original uri which is redirected. atoplevel whether the uri is loaded in a top-level window. areferrer the uri of the referring page. isvisited() checks to see whether the given uri is in history. boolean isvisited( in nsiuri auri ); parameters auri the nsiuri of the page. return value true if a uri has been visited. setpagetitle() set the page title for the given uri. uris that are not already in global history will not be added.
nsIGlobalHistory3
) upon getting the ns_error_not_implemented result. void adddocumentredirect( in nsichannel aoldchannel, in nsichannel anewchannel, in print32 aflags, in boolean atoplevel ); 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 ...
nsILivemarkService
the folder id isn't known. reloadalllivemarks() this method reloads all livemark subscriptions, whether or not they have expired. void 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 nsiu...
nsIMacDockSupport
te window" menuitem's are missing. therefore, if you would like to add or remove items to the menu it is recommended to manipulate the default menu item which is on the hidden window of firefox. note: the hidden window of firefox (services.appshel.hiddendomwindow) loads on browser startup, so if you would like to access it on startup of the browser make sure to check and wait for the window to be loaded. this can be done by adding a event listenr for load of the hidden window. this is the recommended way to add to the native menu, just maniuplate the default menu dom element. var macmenuitem = services.appshell.hiddendomwindow.document.createelementns('http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul', 'menuitem'); macmenuitem.setattribute('label', 'show most recent window'); macmen...
nsIMessenger
sghdrfromuri(in acstring auri); getmsguriatnavigatepos() gets the message a particular position in the navigation history. for example, back-forward history needs a list of visited messages, and where it is in the list. unfortunately, you must call this before navigating to a position, because calling this has the side effect of making us adjust our current history position, and not adding the loaded message to the history queue. acstring getmsguriatnavigatepos(in long apos); parameters apos the position to get the url from relative to the current history cursor. +1 is forward, -1 is back. return value the url at that point in the history. getfolderuriatnavigatepos() gets the folder url at a particular position in the navigation history. acstring getfolderuriatnavigatepos(in...
nsIMicrosummary
void update(); attributes attribute type description content astring the content of the microsummary. since generators and pages can be remote resources, and we need them to generate the content, this may not always be available. read only. generator nsimicrosummarygenerator the generator that generates this microsummary. may need to be loaded. needsremoval boolean used when a site author has indicated that a microsummary (or an associated generator) will no longer be available. read only. pageuri nsiuri the uri of the page being summarized. read only. updateinterval long the minimum interval after which this microsummary would like to be refreshed or null if it doesn't care. read only. ...
Building an Account Manager Extension
panel, the same naming as used for the xul. this means in our example, the javascript file should be located in chrome://example@mozilla.org/content/am-devmo-account.js. <?xml version="1.0" encoding="utf-8"?> <?xml-stylesheet href="chrome://messenger/skin/accountmanage.css" type="text/css"?> <page xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" onload="parent.onpanelloaded('am-devmo-account.xul');"> <script type="application/javascript" src="chrome://messenger/content/accountmanager.js"/> <script type="application/javascript" src="chrome://example@mozilla.org/content/am-devmo-account.js"/> <dialogheader title="devmo example panel"/> <description> this panel is only shown in imap accounts... </description> <vbox flex = "1"/> </page>...
nsIMsgAccountManagerExtension
l. this attribute is readonly! methods showpanel() before displaying a panel in the account manager this method is triggered. boolean showpanel( in nsimsgincomingserver server ); parameters server the account for which the panel should be displayed. return value a true indicates, that the account manager can display the panel for the given account, while false prevents the panel to be loaded. see also nsimsgaccountmanager building an account manager extension ...
nsIMsgFolder
ion supportsoffline boolean readonly offlinestoreoutputstream nsioutputstream readonly offlinestoreinputstream nsiinputstream readonly retentionsettings nsimsgretentionsettings downloadsettings nsimsgdownloadsettings sortorder long used for order in the folder pane, folder pickers, etc. lastmessageloaded nsmsgkey unique id to the folder, it is not a globally unique identifier. will return nsmsgkey_none if there was no last message loaded. note: does not persist across sessions. uri acstring readonly: old nsifolder properties and methods. name astring old nsifolder properties and methods. prettyname astring old nsifolder properties ...
nsIMsgWindow
l to display in the message pane. note that the html is wrapped in <html> and <body> tags for you. clearmsghdr whether or not the existing message pane and header should be cleared before the html is displayed. stopurls() this is equivalent to calling stop(nsiwebnavigation::stop_network) on the nsiwebnavigation object. void stopurls(); closewindow() when the msg window is being unloaded from the content window, this notification can be used to force a flush on anything the message window hangs on. for some reason xpconnect is still hanging onto the message window even though all of our objects have let go of it. this forces a release. it clears out the content listener, the windowcommands, the statusfeedback and the docshell objects. void closewindow(); remarks see also ...
nsIPluginHost
atalen ); parameters ainpostdata the post data. ainpostdatalen the length ainpostdata. aoutpostdata the buffer. aoutpostdatalen the length of aoutpostdata. reloadplugins() causes the plugins directory to be searched again for new plugin libraries. void reloadplugins( in boolean reloadpages ); parameters reloadpages indicates whether currently visible pages should also be reloaded. native code only!setisscriptableinstance obsolete since gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1)this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. to notify the plugin manager that the plugin created a script object. void setisscriptableinstance( in nsiplugininstance...
nsISHEntry
ry from others during subframe navigation. layouthistorystate nsilayouthistorystate layouthistorystate for scroll position and form values. loadtype unsigned long the loadtype for this entry. this is typically loadhistory except when reload is pressed, it has the appropriate reload flag. owner nsisupports get the owner, if any, that was associated with the channel that the document that was loaded to create this history entry came from. pageidentifier unsigned long an integer that should be the same for two entries attached to the same docshell only if the two entries are entries for the same page in the sense that one could go from the state represented by one to the state represented by the other simply by scrolling (so the entries are separated by an anchor traversal or a subframe na...
nsITelemetry
(components.interfaces.nsitelemetry); method overview jsval gethistogrambyid(in acstring id); jsval snapshothistograms(in uint32_t adataset, in boolean asubsession, in boolean aclear); jsval getkeyedhistogrambyid(in acstring id); void capturestack(in acstring name); jsval snapshotcapturedstacks([optional] in boolean clear); nsisupports getloadedmodules(); jsval snapshotkeyedhistograms(in uint32_t adataset, in boolean asubsession, in boolean aclear); void sethistogramrecordingenabled(in acstring id, in boolean enabled); void asyncfetchtelemetrydata(in nsifetchtelemetrydatacallback acallback); double mssinceprocessstart(); void scalaradd(in acstring aname, in jsval avalue); void scala...
nsIUpdate
ich 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 represented by the object: "maj...
nsIUpdateCheckListener
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 nsixmlhttprequest request, in unsigned long position, in unsigned long totalsize ); parameters request the nsixmlhttprequest object handling the update check. position the number of bytes downloaded so far. totalsize the total number of bytes that need to be downloaded. see also nsiupdatepatch nsiupdate nsiupdatechecker nsiapplicationupdateservice nsiupdatemanager nsiupdateprompt nsiupdatetimermanager ...
nsIWebBrowser
ata and throttling the refresh driver. in firefox, this corresponds to the visible tab. defaults to true. for optimal performance, set it to false when appropriate. parenturicontentlistener nsiuricontentlistener uri content listener parent. the embedder may set this property to their own implementation if they intend to override or prevent how certain kinds of content are loaded. note: if this attribute is set to an object that implements nsisupportsweakreference, the implementation should get the nsiweakreference and hold that. otherwise, the implementation should not refcount this interface; it should assume that a non null value is always valid. in that case, the embedder should explicitly set this value back to null if the parent content listener is destroyed bef...
nsIWebBrowserChrome
g status); void showasmodal(); void sizebrowserto(in long acx, in long acy); attributes attribute type description chromeflags unsigned long the chrome flags for this browser chrome. the implementation should reflect the value of this attribute by hiding or showing its chrome appropriately. webbrowser nsiwebbrowser the currently loaded webbrowser. the browser chrome may be told to set the webbrowser object to a new object by setting this attribute. in this case the implementer is responsible for taking the new webbrowser object and doing any necessary initialization or setup as if it had created the webbrowser itself. this includes positioning setting up listeners etc. constants constant value description ...
nsIWebProgress
d 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, corresponding to nsiwebprogresslistener.onstatechange(). constant value d...
nsIWindowMediator
ndow) { // wait for the window to finish loading let domwindow = awindow.queryinterface(ci.nsiinterfacerequestor).getinterface(ci.nsidomwindowinternal || ci.nsidomwindow); domwindow.addeventlistener("load", function () { domwindow.removeeventlistener("load", arguments.callee, false); //this removes this load function from the window //window has now loaded now do stuff to it //as example this will add a function to listen to tab select and will fire alert in that window if (domwindow.gbrowser && domwindow.gbrowser.tabcontainer) { domwindow.gbrowser.tabcontainer.addeventlistener('tabselect', function () { domwindow.alert('tab was selected') }, false); } }...
nsIXULTemplateBuilder
; void removelistener(in nsixulbuilderlistener alistener); attributes attribute type description root nsidomelement readonly: the root node in the dom to which this builder is attached. datasource nsisupports the opaque datasource object that is used for the template. this object is created by the getdatasource method of the query processor. may be null if the datasource has not been loaded yet. set this attribute to use a different datasource and rebuild the template. for an rdf datasource, this will be the same as the database. for xml this will be the nsidomnode for the datasource document or node for an inline reference (such as #name). other query processors may use other types for the datasource. database nsirdfcompositedatasource readonly: the composite datasource that the...
Using nsIDirectoryService
can be found in: nsdirectoryservicedefs.h nsappdirectoryservicedefs.h nsxulappapi.h content formerly at http://www.mozilla.org/projects/xpco...locations.html background the way in which mozilla components locate special files and directories has changed. in the past, this was done using nsifilelocator. this component was a problem for embedding applications. since it was a component and was loaded implicitly by many other components, it was difficult to customize. customizing the locations is important if, for example, your application already has a profile directory or other resource directories. you may wish that you could have mozilla use these locations rather than requiring the same disk layout as seamonkey. in order to change these locations using nsifilelocator and still be able to ...
Using the Gecko SDK
et of component interfaces (c++ vtables) and <tt>extern "c"</tt> symbols exported from the xpcom library and the nspr libraries. the abi of the component interfaces depends on the c++ abi of the host compiler (i.e., the vtable format and calling conventions of the virtual methods may vary from compiler to compiler). the gecko abi is therefore compiler sensitive. (<tt>about:buildconfig</tt> can be loaded in mozilla to reveal details about the compiler that was used.) for the remainder of this guide, we'll assume you are developing components under linux. (ports of this guide are welcome.) a "frozen" interface or function is guaranteed to be supported by future versions of same major version of the platform. the sdk contains headers for all of the frozen interfaces and functions, and it also conta...
Using the clipboard
eate an xpcom object to wrap what we want to copy. we'll assume that we want to copy some text. we will use the interface nsisupportsstring which can be used to represent strings (specifically, unicode strings). the following boilerplate utility functions will be used in all later code examples. // import the services module for future use, if we're not in // a browser window where it's already loaded. components.utils.import('resource://gre/modules/services.jsm'); // create a constructor for the built-in supports-string class. const nssupportsstring = components.constructor("@mozilla.org/supports-string;1", "nsisupportsstring"); function supportsstring(str) { // create an instance of the supports-string class var res = nssupportsstring(); // store the javascript string that we w...
XPCOM category image-sniffing-services
note: this category was removed. see bug 813787 - remove support for image-sniffing-services. ...
XSLT 2.0
although xslt 2.0 is not natively supported in firefox, it is possible via saxon-b (java) or, more recently, saxon-ce (javascript) to perform xslt 2.0. for users saxon-ce no extensions are required, saxon-ce runs whenever a html page is loaded that links to the saxon-ce javascript library. saxon-b the xsl results extension uses the new incarnation of liveconnect (handled by java 1.6v12+ instead of mozilla-specific code) to connect with the java-based saxon-b library, and adds support for having xslt performed automatically when visiting a page with the appropriate xslt processing instruction (and which isn't processed by firefox's own xslt 1.0 processor). for developers saxon-ce a javascript api is provided for initiating an xslt 2.0 transform from a web page. error and diagnos...
Xray vision
the caller only the native version of the objects. gecko runs javascript from a variety of different sources and at a variety of different privilege levels. the javascript code that along with the c++ core, implements the browser itself is called chrome code and runs using system privileges. if chrome-privileged code is compromised, the attacker can take over the user's computer. javascript loaded from normal web pages is called content code. because this code is being loaded from arbitrary web pages, it is regarded as untrusted and potentially hostile, both to other websites and to the user. as well as these two levels of privilege, chrome code can create sandboxes. the security principal defined for the sandbox determines its privilege level. if an expanded principal is used, the sandbo...
Address Book examples
s to help extend the behavior of the address book. load and save listeners edit dialogs for both contacts and mailing lists expose functions for registering load and save listeners. for example, in order to register a load listener for a contact, the following should take place within the scope of the contact editor dialog: /* an example load listener for a contact * acard the nsiabcard being loaded * adocument a reference to the contact editor document */ function foo(acard, adocument) { // do something useful, like disabling // input fields that cards for this // address book 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 unregis...
Filelink Providers
, requires a username and password. other services may require the user to fill in a server string or port number. a provider implementation can choose what information it gets from the user from the setup dialog by pointing the settingsurl attribute of their nsimsgcloudfileprovider implementation to a chrome url for an xhtml page that contains a form with the extra information. that url is then loaded into an iframe directly beneath the provider menulist. note: the setup dialog window should resize itself automatically in order to fit the content of the iframe without scrollbars. custom settings fields to handle custom settings, the settings xhtml page should contain a form with the id "provider-form", with its onsubmit attribute set to "return false;". example: <form id="provider-form" o...
Index
52 thunderbird api documentation these pages have been moved from mozilla.org, and may or may not be relevant. 55 thunderbird binaries branch, trunk, comm-central, thunderbird described below are three types of generally available thunderbird packages - releases, early preview releases, and nightly builds (including trunk development builds) - and their downloaded locations. additionally, ad-hoc packages called try builds are made available on an as-needed basis to allow for testing of certain patches, and are typically announced in related bug reports. 56 thunderbird configuration files config editor, configuration files many of the tips and tricks mentioned on this site can be applied by using the built-in config editor. to access t...
MailNews Filters
un 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.cpp. this is implemented by doing a search using the filter criteria and applying the actions en masse on the resulting hits. the search is executed locally, not on the server, so that criteria like "in address book" still work. how to add a filter action add your new action to nsimsgfilteraction add cod...
Mail and RDF
d the ui mail does not link the ui to datasources in a "traditional" manner. instead of having a singleton datasource that is shared across all ui components, we have per-view datasources. this allows each template-based widget to maintain view/window-specific data with each datasource. for example...??? (sorting? what else do we store?) datasources are created when each window's javascript is loaded by declaring the datasource variables in the source javascript as global variables. in the document's onload= handler the datasources are attached to their respective widgets by setting the database property on each rdf template's parent element. reflecting data to rdf in order to have a dynamic ui that updates when the underlying content changes, a datasource must implement two key methods of ...
Access Thunderbird Window Areas
he thunderbird window you can use these helper methods. ...
customDBHeaders Preference
forrow: function(hdr) {return 0;} } function addcustomcolumnhandler() { gdbview.addcolumnhandler("colsuperfluous",columnhandler); dump("column handler being added: " + columnhandler + "\n"); } var createdbobserver = { // components.interfaces.nsiobserver observe: function(amsgfolder, atopic, adata) { dump("here here!"); addcustomcolumnhandler(); } } function doonceloaded(){ var observerservice = components.classes["@mozilla.org/observer-service;1"].getservice(components.interfaces.nsiobserverservice); observerservice.addobserver(createdbobserver, "msgcreatedbview", false); window.document.getelementbyid('foldertree').addeventlistener("select",addcustomcolumnhandler,false); } window.addeventlistener("load",doonceloaded,false); dump(" ~ ~ ~ ~ end superfluou...
Using the Multiple Accounts API
john smith preference: mail.identi...
libmime content type handlers
d the ability to decode and render various content types. this functionality will be accomplished via content type handler plugins for libmime. libmime has a homegrown object system written in c, and since the content type handler plugins need to exist in this module, a description of the libmime object system should be reviewed and understood. api's content type handler plugins are dynamically loaded and need to access internal pointers, functions that are part of the c based object system. the following xp-com interface is implemented by libmime and is necessary for content type handler plugin development. /* * this interface is implemented by content type handlers that will be * called upon by libmime to process various attachments types. the primary * purpose of these handlers will ...
Add to iPhoto
rrayref 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/directory_service;1"] .getservice(components.interfaces.nsiproperties) .get("tmpd", components.interfaces.
Library
its methods let you declare symbols exported by the library, and to manage the library. method overview close(); cdata declare(name, [abi, ], returntype[, argtype1, ...]); methods close() closes the library. you need to call this once you're done using the library. close(); parameters none. declare() declares an api from the native library, allowing it to be used from javascript. this can be used both for exported data symbols and for functions. ...
ctypes
ing the same data, but with the specified type. libraryname() returns the correct platform-specific filename for a given library name (e.g. libnss3.dylib for nss3 on os x.) string libraryname( name ); parameters name the name of the library. return value string containing the platform-specific filename of the library. open() opens a library, specified by a pathname. the library is loaded from the specified full path, or, if a partial path is specified, from the appropriate library directory based on the platform on which the application is running. see library search paths for more details. library open( libspec ); parameters libspec the native library to open, specified as a pathname string. return value a library object representing the opened library. examples ex...
Mozilla
on a handful of platforms. also, with as many as 100 engineers, it was very difficult to determine what happened in the tree that caused the instability. bonsai was created to solve these problems. how mozilla determines mime types all data handling in mozilla is based on the mime type of the content. this means that every time an uri is loaded, mozilla must find out its mime type. the several ways how this happens are described in this document. how test harnesses work mozilla test harnesses are typically composed of a python runner that invokes firefox, utilizes the browser to run tests, and reports the results. the python harness communicates with the browser by inserting an extension in...
Blocking By Domain - Plugins
, and use fallback content as specified by the html standard. plugin detection mechanisms such as navigator.mimetypes and navigator.plugins will also behave as if the plugin were not installed. there are two versions of plugin blocking: first-party plugin blocking list sites on this list may not use plugins. third-party plugin block list sites on this list may not use plugins when they are loaded into a third-party iframe in another site. criteria in order to improve firefox security and performance, there are two major categories of sites mozilla may choose to add to plugin domain blocking: sites commonly embedded in a 3rd-party context web sites which are commonly embedded into other sites using iframes can have a large impact on browser security and also cause many sites to show...
Drawing and Event Handling - Plugins
ss plug-ins can be opaque or transparent. a windowless plug-in draws itself only in response to a paint message from the browser. for information about the way html determines plug-in display mode, see using html to display plug-ins. note: windowless plug-ins were not supported on the x window system platform prior to gecko 1.9 alpha 7 (bug 137189). the npwindow structure when a plug-in is loaded, it is drawn into a target area. this target is either the windowed plug-in's native window, or the drawable of a windowless plug-in. the npwindow structure represents either the native window or a drawable. this structure contains information about coordinate position, size, the state of the plug-in (windowed or windowless), and some platform-specific information. note: when a plug-in is drawn...
Streams - Plugins
can be pushed by the browser, pulled by the plug-in, or saved to a local file and passed to the plug-in. normal mode: the browser uses the npp_write method to "push" stream data to the instance incrementally as it is available. random-access mode: the plug-in calls the npn_requestread method to "pull" stream data. in general, this mode is more expensive, because the entire stream must be downloaded to a temporary file before use unless the stream comes from a local file or an http server that supports the byte-range extension to http. file mode: the browser saves the entire stream to a local file and passes the file path to the plug-in instance through the npp_streamasfile method. use this feature only as a last resort; plug-ins should implement an incremental stream-based interface wherev...
Plugins
chnology that are a security and performance problem for firefox (and other browser) users. they may not be supported in the future. new content should not be written using flash or any other plugin technology. roadmap plugin roadmap information about the roadmap for adobe flash and other plugin support in firefox. roadmap highlights since firefox 52, plugins other than flash are not loaded by firefox. starting in firefox 55, users will be asked to choose which sites may use flash content. this feature will be rolled out gradually to firefox users. also from firefox 55 onwards, flash and other plugins can no longer be loaded from any url scheme except for http:// and https:// (bug 1335475). see also flash can now be loaded only from http/https for more useful information. starti...
Preferences System
</preferences> .. ui elements that refer to the preferences above, e.g.: <checkbox id="check1" preference="pref1" label="&check1.label;" accesskey="&check1.accesskey;"/> </prefpane> <prefpane id="pane2" label="&pane2.title;" src="chrome://uri/to/pane.xul"/> </prefwindow> pane content can be specified inline or an external chrome uri supplied for pane content to be loaded in via a dynamic overlay. you should be careful to read the higs for the platforms you are targeting and use the xul preprocessor if necessary to set different window titles as appropriate. you should also be careful to specify the width of the window (in em) as appropriate using the preprocessor for each targeted platform, as well as the height (in em) for platforms where the window size does no...
Accessibility Inspector - Firefox Developer Tools
ys, and use the left and right arrow keys to expand and collapse expandable rows (e.g., different hierarchy levels of the accessibility tree). print accessibility tree to json you can print the contents of the accessibility tree to json by right-clicking on an entry in the accessibility tab and selecting print to json: when you do, you will get a new tab with the selected accessibility tree loaded into the json viewer: once opened, you can save or copy the data as necessary. the json viewer can also show you the raw json data on a separate tab in the viewer. check for accessibility issues you can check for accessibility issues by clicking the drop-down menu next to: check for issues. the available menu items include: none — don't show the possible list of issues all issues — c...
Debugging service workers - Firefox Developer Tools
ervice worker will not necessarily update to the new version immediately, which can make debugging a pain. from updating your service worker: if your service worker has previously been installed, but then a new version of the worker is available on refresh or page load, the new version is installed in the background, but not yet activated. it is only activated when there are no longer any pages loaded that are still using the old service worker. as soon as there are no more such pages still loaded, the new service worker activates. debug important: the debug button is currently enabled only in firefox nightly. when your service worker is running, a debug button is available next to the source information (it is disabled when the service worker is stopped). when pressed, this takes you st...
Browser Toolbox - Firefox Developer Tools
n it with the ctrl + alt +shift + i key combination ( cmd + opt +shift + i on a mac). you will be presented with a dialog like this (it can be removed by setting the devtools.debugger.prompt-connection property to false): click ok, and the browser toolbox will open in its own window: you'll be able to inspect the browser's chrome windows and see, and be able to debug, all the javascript files loaded by the browser itself and by any add-ons that are running. altogether you will have access to the following developer tools: debugger (note: if you want to debug a specific add-on that is restartless or sdk-based then try the add-on debugger.) console style editor performance network monitor page inspector accessibility inspector you can debug chrome: and about: pages using the norma...
Search - Firefox Developer Tools
searching for files to search for a particular file, press control + p (or command + p on a mac) and type the search term. the source pane will display a list of all matching files as you type. you can use the up and down arrows to move through the list, and return to open the file you want: searching within a file to search for a particular substring in the file currently loaded into the source pane, press control + f (or command + f on a mac) while the source pane is focused. press return to search. the debugger will display the number of matches in the code and highlight each result: using the outline tab if you are searching for a specific function within the current javascript file, you can use the outline tab in the debugger to find it quickly. the outline tab lists the functions...
Use a source map - Firefox Developer Tools
ated by a developer. for example: sources are often combined and minified to make delivering them from the server more efficient. javascript running in a page is often machine-generated, as when compiled from a language like coffeescript or typescript. in these situations, it's much easier to debug the original source, rather than the source in the transformed state that the browser has downloaded. a source map is a file that maps from the transformed source to the original source, enabling the browser to reconstruct the original source and present the reconstructed original in the debugger. to enable the debugger to work with a source map, you must: generate the source map include a comment in the transformed file, that points to the source map. the comment's syntax is like this: /...
Debugger.Script - Firefox Developer Tools
somewhere within an expression that is assigned toa. for example: function h() { var i = function() {}; // display name: h/i f(function () {}); // display name: h/< } var s = f(function () {}); // display name: s< if the instance refers to webassembly code, throw a typeerror. url if the instance refers to a jsscript, the filename or url from which this script’s code was loaded. for scripts created by eval or the function constructor, this may be a synthesized filename, starting with a valid url and followed by information tracking how the code was introduced into the system; the entire string is not a valid url. for function.prototype’s script, this is null. if this debugger.script’s source property is non-null, then this is equal to source.url. if the instance r...
Debugger - Firefox Developer Tools
rties is initially undefined. any value assigned to a debugging handler must be either a function or undefined; otherwise a typeerror is thrown. handler functions run in the same thread in which the event occurred. they run in the compartment to which they belong, not in a debuggee compartment. onnewscript(script,global) new code, represented by the debugger.script instancescript, has been loaded in the scope of the debuggees. this method’s return value is ignored. onnewpromise(promise) a new promise object, referenced by the debugger.object instance promise, has been allocated in the scope of the debuggees. the promise’s allocation stack can be obtained using the promiseallocationstack accessor property of the debugger.object instance promise. this handler method should ret...
Debugger-API - Firefox Developer Tools
r reflect some global object’s properties as variables. the debugger instance itself is not really a shadow of anything in the debuggee; rather, it maintains the set of global objects which are to be considered debuggees. a debugger observes only execution taking place in the scope of these global objects. you can set functions to be called when new stack frames are pushed; when new code is loaded; and so on. omitted from this picture are debugger.source instances, which represent javascript compilation units. a debugger.source can furnish a full copy of its source code, and explain how the code entered the system, whether via a call to eval, a <script> element, or otherwise. a debugger.script points to the debugger.source from which it is derived. also omitted is the debugger’s debugg...
Index - Firefox Developer Tools
lip-path and also the css shape-outside property and <basic-shape> values. this guide walks you through all of the available options. 60 edit fonts fonts, guide, inspector, tools, variable fonts this article provides a tour of the font tools available in the firefox devtools. this tool contains several useful features for viewing and manipulating fonts applied to any document loaded in the browser including inspection of all fonts applied to the page, and precise adjustment of variable font axis values. 61 examine event listeners guide, inspector, tools the inspector shows the word "event" next to elements in the html pane, that have event listeners bound to them: 62 examine and edit css guide, inspector, tools you can examine and ed...
Network request details - Firefox Developer Tools
if the response is html, a preview of the rendered html appears inside the response tab, above the response payload. timings tab the timings tab provides information about how long each stage of a network request took, with 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 m...
Network request list - Firefox Developer Tools
ent parts of each request. each timeline is given a horizontal position in its row relative to the other network requests, so you can see the total time taken to load the page. for more details on the color-coding used here, see the section on the timings page. starting in firefox 45, the timeline also contains two vertical lines: the blue line marks the point at which the page's domcontentloaded event is triggered. the red line marks the point at which the page's load event is triggered. blocking specific urls if you want to view your page as it would look without a resource (e.g., if it were blocked by the browser or an extension), you can block requests matching patterns you specify. click the request blocking icon in the toolbar. this opens the blocking sidebar. (click the icon...
Use the Inspector API - Firefox Developer Tools
ion: .isnode() - returns true if selection is node. .node - returns the actual element from the page .window - the window object of the frame the selection is in. .markdirty() - marks that the page has been changed by the inspector - a warning will be shown when leaving the page, since changes made through the inspector are rewritten on reload. bindable events using on: markuploaded called when the left panel has been refreshed, after page change. ready called on first markuploaded. pseudoclass called after toggle of a pseudoclass. layout-change "low-priority change event for things like paint and resize." ...
Page Inspector - Firefox Developer Tools
see remote debugging to learn how to connect the developer tools to a remote target. user interface tour to find your way around the inspector, here's a quick tour of the ui. you can split the rules view out into its own pane, separate from the other tabs on the css pane — this is called 3-pane mode. ...
How to - Firefox Developer Tools
ofile to start a new recording, press the stopwatch icon in the recordings pane. to stop, press it again: you can also start and stop recording from the web console, using console.profile() and console.profileend(). save a profile to save a profile, click the link labeled "save" in the recordings pane: load a profile to load a profile, click "import..." and choose the file: clear all loaded profiles to clear all loaded profiles, click "clear". if you do this, you'll lose any loaded profiles that you have not saved. select a tool to switch between the waterfall, call tree, and flame chart tools, use the buttons in the toolbar: configure markers displayed to control which markers are shown in the waterfall, use the button in the toolbar: zoom in to zoom into a slice of...
UI Tour - Firefox Developer Tools
r contains buttons to: start and stop a recording import a recording you previously saved clear the recordings pane. note that if you do this, you lose any recordings you have not saved. filter the markers that are displayed in the waterfall view switch the active tool in the details pane. access the settings popup recordings pane the recordings pane lists all the recordings you have loaded, including any you have made in this session and any you have imported. at any given time, one recording is selected, and that recording is displayed in the rest of the tool. to select a different recording, click its entry in the pane. to save the recording as a json file click "save". recording overview this displays an overview of the entire recording, with the x-axis representing time. ...
Waterfall - Firefox Developer Tools
art call stack console.time(), with links to functions. stack at end (new in firefox 41). call stack at console.timeend(). if this is inside a callback from a promise, this will also show the "async stack". timestamp a single call to console.timestamp(). label the argument passed to timestamp(). domcontentloaded the document's domcontentloaded event. load the document's load event. worker event in main thread shown when the main thread sends a message to a worker, or receives a message from a worker. one of: serialize data on the main thread the main thread is serializing a message to be sent to the worker.
Web Audio Editor - Firefox Developer Tools
lick the tab and load a page that constructs an audio context. two good demos are: the voice-change-o-matic, which can apply various effects to the microphone input and also provides a visualisation of the result the violent theremin, which changes the pitch and volume of a sine wave as you move the mouse pointer visualizing the graph the web audio editor will now display the graph for the loaded audio context. here's the graph for the violent theremin demo: you can see that it uses three nodes: an oscillatornode as the source, a gainnode to control the volume, and an gainnode as the destination. connections to audioparams displaying connections to audioparams is new in firefox 34. connections between nodes are displayed as solid lines. if, instead, you've connected a node to an aud...
Console messages - Firefox Developer Tools
, 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. see mixed content for more details. loading mixed (insecure) display content on a secure page 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 loaded this display content. see mixed content for more details. this site specified bo...
Firefox Developer Tools
r view and edit page content and layout. visualise many aspects of the page including the box model, animations, and grid layouts. web console see messages logged by a web page and interact with the page using javascript. javascript debugger stop, step through, examine, and modify the javascript running in a page. network monitor see the network requests made when a page is loaded. performance tools analyze your site's general responsiveness, javascript, and layout performance. responsive design mode see how your website or app will look and behave on different devices and network types. accessibility inspector provides a means to access the page's accessibility tree, allowing you to check what's missing or otherwise needs attention. application pa...
AbstractRange - Web APIs
the contents of the range. ranges and the hierarchy of the dom in order to define a range of characters within a document in a way that is able to span across zero or more node boundaries, and which is as resilient as possible to changes to the dom, you can't simply specify the offset to the first and last characters in the html. there are a few good reasons for that. first, after your page is loaded, the browser simply isn't thinking in terms of html. once it's been loaded, the page is a tree of dom node objects, so you need to specify the beginning and ending locations of a range in terms of nodes and positions within nodes. second, in order to support the mutability of the dom tree as much as possible, you need a way to represent positions relative to nodes in the tree, rather than simply...
AbstractWorker - Web APIs
r, both of which inherit the properties of abstractworker. this code snippet demonstrates the creation of a new worker using the worker() constructor; it also shows how to then send a message to the worker. var myworker = new worker('worker.js'); first.onchange = function() { myworker.postmessage([first.value, second.value]); console.log('message posted to worker'); } the worker's code is loaded from the file "worker.js". this code assumes that there's an <input> element represented by first; an event handler for the change event is established so that when the user changes the value of first, a message is posted to the worker to let it know. you can find more examples on the mdn web docs github repository: basic dedicated worker example (run dedicated worker). basic shared worker e...
AudioContext.createMediaStreamSource() - Web APIs
); var range = document.queryselector('input'); // getusermedia block - grab stream // put it into a mediastreamaudiosourcenode // also output the visuals into a video element if (navigator.mediadevices) { console.log('getusermedia supported.'); navigator.mediadevices.getusermedia ({audio: true, video: true}) .then(function(stream) { video.srcobject = stream; video.onloadedmetadata = function(e) { video.play(); video.muted = true; }; // create a mediastreamaudiosourcenode // feed the htmlmediaelement into it var audioctx = new audiocontext(); var source = audioctx.createmediastreamsource(stream); // create a biquadfilter var biquadfilter = audioctx.createbiquadfilter(); biquadf...
AudioContext.createMediaStreamTrackSource() - Web APIs
reatebiquadfilter(), and it's configured as desired to perform a lowshelf filter on the audio coming from the source. the output from the microphone is then routed into the new biquad filter, and the filter's output is in turn routed to the audio context's destination. ...
BaseAudioContext.decodeAudioData() - Web APIs
the decoded audiobuffer is resampled to the audiocontext's sampling rate, then passed to a callback or promise. this is the preferred method of creating an audio source for web audio api from an audio track. this method only works on complete file data, not fragments of audio file data. ...
BaseAudioContext - Web APIs
. baseaudiocontext.createstereopanner() creates a stereopannernode, which can be used to apply stereo panning to an audio source. baseaudiocontext.createwaveshaper() creates a waveshapernode, which is used to implement non-linear distortion effects. baseaudiocontext.decodeaudiodata() asynchronously decodes audio file data contained in an arraybuffer. in this case, the arraybuffer is usually loaded from an xmlhttprequest's response attribute after setting the responsetype to arraybuffer. this method only works on complete files, not fragments of audio files. examples basic audio context declaration: const audiocontext = new audiocontext(); cross browser variant: const audiocontext = window.audiocontext || window.webkitaudiocontext; const audiocontext = new audiocontext(); const oscil...
Beacon API - Web APIs
example use cases of the beacon api are logging activity and sending analytics data to the server. ...
BeforeUnloadEvent - Web APIs
when a non-empty string is assigned to the returnvalue event property, a dialog box appears, asking the users for confirmation to leave the page (see example below). when no value is provided, the event is processed silently. some implementations only show the dialog box if the frame or any embedded frame receives a user gesture or user interaction. see browser compatibility for more information. ...
Body.arrayBuffer() - Web APIs
Web › API › Body › arrayBuffer
eturns a promise that resolves with an arraybuffer. 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(...
CanvasRenderingContext2D.getImageData() - Web APIs
down, and negative are up. return value an imagedata object containing the image data for the rectangle of the canvas specified. the coordinates of the rectangle's top-left corner are (sx, sy), while the coordinates of the bottom corner are (sx + sw, sy + sh). exceptions indexsizeerror thrown if either sw or sh are zero. securityerror the canvas contains or may contain pixels which were loaded from an origin other than the one from which the document itself was loaded. to avoid securityerror being thrown in this situation, configure cors to allow the source image to be used in this way. see allowing cross-origin use of images and canvas. example getting image data from a canvas this example draws a rectangle, and then uses getimagedata() to grab a portion of the canvas. html <can...
Manipulating video using canvas - Web APIs
th="160" height="96"></canvas> </div> <script type="text/javascript" src="processor.js"></script> </body> </html> the key bits to take away from this are: this document establishes two canvas elements, with the ids c1 and c2. canvas c1 is used to display the current frame of the original video, while c2 is used to display the video after performing the chroma-keying effect; c2 is preloaded with the still image that will be used to replace the green background in the video. the javascript code is imported from a script named processor.js. the javascript code the javascript code in processor.js consists of three methods. initializing the chroma-key player the doload() method is called when the xhtml document initially loads. this method's job is to prepare the variables needed...
Applying styles and colors - Web APIs
we use this method to create a canvaspattern object which is very similar to the gradient methods we've seen above. once we've created a pattern, we can assign it to the fillstyle or strokestyle properties. for example: var img = new image(); img.src = 'someimage.png'; var ptrn = ctx.createpattern(img, 'repeat'); note: like with the drawimage() method, you must make sure the image you use is loaded before calling this method or the pattern may be drawn incorrectly. a createpattern example in this last example, we'll create a pattern to assign to the fillstyle property. the only thing worth noting is the use of the image's onload handler. this is to make sure the image is loaded before it is assigned to the pattern. function draw() { var ctx = document.getelementbyid('canvas').getconte...
Basic usage of canvas - Web APIs
"> <canvas id="tutorial" width="150" height="150"></canvas> </body> </html> the script includes a function called draw(), which is executed once the page finishes loading; this is done by listening for the load event on the document. 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 two intersecting rectangles, one of which has alpha transparency. we'll explore how this works in more detail in later examples. <!doctype html> <html> <head> <meta charset="utf-8"/> <script type="application/javascript"> ...
Using channel messaging - Web APIs
essage('init', '*', [channel.port2]); } // post a message on port1 when the button is clicked function onclick(e) { e.preventdefault(); port1.postmessage(input.value); } // handle messages received on port1 function onmessage(e) { output.innerhtml = e.data; input.value = ''; } we start off by creating a new message channel by using the messagechannel() constructor. when the iframe has loaded, we register an onclick handler for our button and an onmessage handler for messagechannel.port1. finally we transfer messagechannel.port2 to the iframe using the window.postmessage method. let's explore how the iframe.contentwindow.postmessage line works in a bit more detail. it takes three arguments: the message being sent. for this initial port transfering this message could be an empty st...
Clients.claim() - Web APIs
Web › API › Clients › claim
oller for all clients within its scope. this triggers a "controllerchange" event on navigator.serviceworker in any clients that become controlled by this service worker. when a service worker is initially registered, pages won't use it until they next load. the claim() method causes those pages to be controlled immediately. be aware that this results in your service worker controlling pages that loaded regularly over the network, or possibly via a different service worker. syntax await clients.claim(); parameters none. return value a promise that resolves to undefined. example the following example uses claim() inside service worker's "activate" event listener so that clients loaded in the same scope do not need to be reloaded before their fetches will go through this service worker. ...
CloseEvent - Web APIs
internal error the server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request. 1012 service restart the server is terminating the connection because it is restarting. [ref] 1013 try again later the server is terminating the connection due to a temporary condition, e.g. it is overloaded and is casting off some of its clients. [ref] 1014 bad gateway the server was acting as a gateway or proxy and received an invalid response from the upstream server. this is similar to 502 http status code. 1015 tls handshake reserved. indicates that the connection was closed due to a failure to perform a tls handshake (e.g., the server certificate can't be...
Content Index API - Web APIs
ine web content is not easily discoverable by users. content indexing allows developers to tell the browser about their specific offline content. this allows users to discover and view what is available, whilst giving developers the ability to add and manage this content. examples could be a news website prefetching the latest articles in the background, or a content streaming app registering downloaded content. the content index api is an extension to service workers, which allows developers to add urls and metadata of already cached pages, under the scope of the current service worker. the browser can then use these entries to display offline reading to a user. as a developer you can also display these entries within your application. indexed entries do not automatically expire. it's good pr...
ConvolverNode.normalize - Web APIs
if normalize is set to false, then the convolution will be rendered with no pre-processing/scaling of the impulse response. ...
DOMHighResTimeStamp - Web APIs
starting time can be either a specific time determined by the script for a site or app, or the time origin. the time origin 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 o...
DataTransfer.clearData() - Web APIs
an> <span class="tweaked" id="target">drop zone</span> <div>status: <span id="status">drag to start</span></div> <div>data is: <span id="data">uninitialized</span></div> css span.tweaked { display: inline-block; margin: 1em 0; padding: 1em 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } javascript window.addeventlistener('domcontentloaded', function () { // select html elements var draggable = document.getelementbyid('source'); var dropable = document.getelementbyid('target'); var status = document.getelementbyid('status'); var data = document.getelementbyid('data'); var dropped = false; // register event handlers draggable.addeventlistener('dragstart', dragstarthandler); draggable.addeventlistener('dragend', dr...
Document() - Web APIs
Web › API › Document › Document
the document constructor creates a new document object that is a web page loaded in the browser and serving as an entry point into the page's content. syntax new document(); specifications specification status comment domthe definition of 'document' in that specification. living standard initial definition. ...
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 generate...
Document.open() - Web APIs
Web › API › Document › open
es the following simple code opens the document and replaces its content with a number of different html fragments, before closing it again. document.open(); document.write("<p>hello world!</p>"); document.write("<p>i am a fish</p>"); document.write("<p>the number is 42</p>"); document.close(); notes an automatic document.open() call happens when document.write() is called after the page has loaded. for years firefox and internet explorer additionally erased all javascript variables, etc., in addition to removing all nodes. this is no longer the case.document non-spec'ed parameters to document.open gecko-specific notes starting with gecko 1.9, this method is subject to the same same-origin policy as other properties, and does not work if doing so would change the document's origin. star...
Document.requestStorageAccess() - Web APIs
d in future browser sessions. reset after 30 days. when an ephemeral or persistent storage access grant expires, the number of origins the requesting origin has storage access to is decremented by one. note: if the requesting origin is not classified as a tracking origin, the access request is automatically given an ephemeral storage access grant, which will go away when the page is reloaded. the user is never shown a prompt in this case, and calling requeststorageaccess() won’t have any side effects besides changing the value returned by document.hasstorageaccess(). debugging the storage access grant threshold may make it more difficult to test your website under the condition where firefox prompts the user for access. to make testing easier, we have added two preferences in ab...
Document.title - Web APIs
Web › API › Document › title
// displays "goodbye world!" </script> </body> </html> notes this property applies to html, svg, xul, and other documents in gecko. for html documents the initial value of document.title is the text content of the <title> element. for xul it's the value of the title attribute of the <xul:window> or other top-level xul element. in xul, accessing document.title before the document is fully loaded has undefined behavior: document.title may return an empty string and setting document.title may have no effect. specifications specification status comment html living standardthe definition of 'document.title' in that specification. living standard ...
Document.visibilityState - Web APIs
possible values are: 'visible' the page content may be at least partially visible. in practice this means that the page is the foreground tab of a non-minimized window. 'hidden' the page content is not visible to the user. ...
Examples of web and XML development using the DOM - Web APIs
you can access these stylesheets and their rules individually using the stylesheet, style, and cssrule objects, as demonstrated in this example, which prints out all of the style rule selectors to the console. var ss = document.stylesheets; for(var i = 0; i < ss.length; i++) { for(var j = 0; j < ss[i].cssrules.length; j++) { dump( ss[i].cssrules[j].selectortext + "\n" );...
Element.innerHTML - Web APIs
Web › API › Element › innerHTML
ptions syntaxerror an attempt was made to set the value of innerhtml using a string which is not properly-formed html. nomodificationallowederror an attempt was made to insert the html into a node whose parent is a document. usage notes the innerhtml property can be used to examine the current html source of the page, including any changes that have been made since the page was initially loaded. reading the html contents of an element reading innerhtml causes the user agent to serialize the html or xml fragment comprised of the element's descendants. the resulting string is returned. let contents = myelement.innerhtml; this lets you look at the html markup of the element's content nodes. note: the returned html or xml fragment is generated based on the current contents of the elem...
FetchEvent() - Web APIs
g object specifying which event the object represents. this is always fetch for fetch events. init optional an object conforming to the fetcheventinit dictionary, containing options to apply to the event object. options are as follows: clientid read only the client that the current service worker is controlling. isreload read only a boolean that signifies whether the page was reloaded or not when the event was dispatched. true if yes, and false if not. typically, pressing the refresh button in a browser is a reload, while clicking a link and pressing the back button is not. if not present, it defaults to false. preloadresponse read only a promise which returns a previously-loaded response to the client. replacesclientid read only a domstring which identifies the clie...
FetchEvent.isReload - Web APIs
the isreload read-only property of the fetchevent interface returns true if the event was dispatched by the user attempting to reload the page, and false otherwise. pressing the refresh button is a reload while clicking a link and pressing the back button is not. syntax var reloaded = fetchevent.isreload value a boolean. example self.addeventlistener('fetch', function(event) { event.respondwith( if (event.isreload) { //return something } else { //return something else }; ); ​}); ...
FileReader: abort event - Web APIs
log>label { display: block; } .event-log-contents { resize: none; } js const fileinput = document.queryselector('input[type="file"]'); const preview = document.queryselector('img.preview'); const eventlog = document.queryselector('.event-log-contents'); const reader = new filereader(); function handleevent(event) { eventlog.textcontent = eventlog.textcontent + `${event.type}: ${event.loaded} bytes transferred\n`; if (event.type === "load") { preview.src = reader.result; } } function addlisteners(reader) { reader.addeventlistener('loadstart', handleevent); reader.addeventlistener('load', handleevent); reader.addeventlistener('loadend', handleevent); reader.addeventlistener('progress', handleevent); reader.addeventlistener('error', handleevent); ...
FileReader: load event - Web APIs
log>label { display: block; } .event-log-contents { resize: none; } js const fileinput = document.queryselector('input[type="file"]'); const preview = document.queryselector('img.preview'); const eventlog = document.queryselector('.event-log-contents'); const reader = new filereader(); function handleevent(event) { eventlog.textcontent = eventlog.textcontent + `${event.type}: ${event.loaded} bytes transferred\n`; if (event.type === "load") { preview.src = reader.result; } } function addlisteners(reader) { reader.addeventlistener('loadstart', handleevent); reader.addeventlistener('load', handleevent); reader.addeventlistener('loadend', handleevent); reader.addeventlistener('progress', handleevent); reader.addeventlistener('error', handleevent); ...
FileReader: loadend event - Web APIs
log>label { display: block; } .event-log-contents { resize: none; } js const fileinput = document.queryselector('input[type="file"]'); const preview = document.queryselector('img.preview'); const eventlog = document.queryselector('.event-log-contents'); const reader = new filereader(); function handleevent(event) { eventlog.textcontent = eventlog.textcontent + `${event.type}: ${event.loaded} bytes transferred\n`; if (event.type === "load") { preview.src = reader.result; } } function addlisteners(reader) { reader.addeventlistener('loadstart', handleevent); reader.addeventlistener('load', handleevent); reader.addeventlistener('loadend', handleevent); reader.addeventlistener('progress', handleevent); reader.addeventlistener('error', handleevent); ...
FileReader: loadstart event - Web APIs
log>label { display: block; } .event-log-contents { resize: none; } js const fileinput = document.queryselector('input[type="file"]'); const preview = document.queryselector('img.preview'); const eventlog = document.queryselector('.event-log-contents'); const reader = new filereader(); function handleevent(event) { eventlog.textcontent = eventlog.textcontent + `${event.type}: ${event.loaded} bytes transferred\n`; if (event.type === "load") { preview.src = reader.result; } } function addlisteners(reader) { reader.addeventlistener('loadstart', handleevent); reader.addeventlistener('load', handleevent); reader.addeventlistener('loadend', handleevent); reader.addeventlistener('progress', handleevent); reader.addeventlistener('error', handleevent); ...
FileReader: progress event - Web APIs
log>label { display: block; } .event-log-contents { resize: none; } js const fileinput = document.queryselector('input[type="file"]'); const preview = document.queryselector('img.preview'); const eventlog = document.queryselector('.event-log-contents'); const reader = new filereader(); function handleevent(event) { eventlog.textcontent = eventlog.textcontent + `${event.type}: ${event.loaded} bytes transferred\n`; if (event.type === "load") { preview.src = reader.result; } } function addlisteners(reader) { reader.addeventlistener('loadstart', handleevent); reader.addeventlistener('load', handleevent); reader.addeventlistener('loadend', handleevent); reader.addeventlistener('progress', handleevent); reader.addeventlistener('error', handleevent); ...
FileReader - Web APIs
filereader() returns a 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.o...
FileSystemDirectoryEntry.getDirectory() - Web APIs
ctoryentry object representing a subfolder named "dictionaries" located inside the specified app data directory. the success callback for this takes the resulting directory entry object and calls getfile() to get a filesystemfileentry object representing the dictionary file; the success callback for this, in turn, creates a new filereader and uses it to load the contents of the file. when that is loaded successfully (as indicated by the loadend event being fired), the loaded text is passed into json.parse() to be reconstituted into a javascript object. specifications specification status comment file and directory entries apithe definition of 'getdirectory()' in that specification. draft initial specification. browser compatibility the compatibility ta...
FileSystemDirectoryEntry.getFile() - Web APIs
ctoryentry object representing a subfolder named "dictionaries" located inside the specified app data directory. the success callback for this takes the resulting directory entry object and calls getfile() to get a filesystemfileentry object representing the dictionary file; the success callback for this, in turn, creates a new filereader and uses it to load the contents of the file. when that is loaded successfully (as indicated by the loadend event being fired), the loaded text is passed into json.parse() to be reconstituted into a javascript object. specifications specification status comment file and directory entries apithe definition of 'getfile()' in that specification. draft initial specification. browser compatibility the compatibility table o...
FileSystemFileEntry.file() - Web APIs
reader.onload = function() { successcallback(reader.result); }; reader.onerror = function() { errorcallback(reader.error); } reader.readastext(file); }, errorcallback); } this function calls file(), specifying as its success callback a method which proceeds to use a filereader to read the file as text. the filereader's load event handler is set up to deliver the loaded string to the successcallback specified when the readfile() method was called; similarly, its error handler is set up to call the errorcallback specified. specifications specification status comment file and directory entries apithe definition of 'file()' in that specification. draft initial specification. browser compatibility the compatibility table o...
FileHandle API - Web APIs
dea to monitor the operation to provide feedback to the user. such monitoring can be done using the filerequest.onprogress event handler. var progress = document.queryselector('progress'); var myfile = myfilehandle.open('readonly'); // let's read a 1gb file var action = myfile.readasarraybuffer(1000000000); action.onprogress = function (event) { if (progress) { progress.value = event.loaded; progress.max = event.total; } } action.onsuccess = function () { console.log('yeah \o/ just read a 1gb file'); } action.onerror = function () { console.log('oups :( unable to read a 1gb file') } file storage when a file handle is created, the associated file only exists as a "temporary file" as long as you hold the filehandle instance. if you want a file to survive a page refres...
Introduction to the File and Directory Entries API - Web APIs
o to the next task or game level without waiting for a download. audio or photo editor with 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 ...
FontFace.FontFace() - Web APIs
Web › API › FontFace › FontFace
ta descriptors optional a set of optional descriptors passed as an object. it can have the following keys: family: family style: style weight: weight stretch: stretch unicoderange: unicode range variant: variant featuresettings: feature settings example async function loadfonts() { const font = new fontface('myfont', 'url(myfont.woff)'); // wait for font to be loaded await font.load(); // add font to document document.fonts.add(font); // enable font with css class document.body.classlist.add('fonts-loaded'); } specifications specification status comment css font loading module level 3the definition of 'fontface constructor' 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. ...
FontFaceSet.check() - Web APIs
Web › API › FontFaceSet › check
syntax bool = afontfaceset.check(font); bool = afontfaceset.check(font, text); returns a boolean that is true if the font list is available parameters font: a font specification using the css value syntax, e.g. "italic bold 16px roboto" text: limit the font faces to those whose unicode range contains at least one of the characters in text. this does not check for individual glyph coverage. ...
Using FormData Objects - Web APIs
you can also append a file or blob directly to the formdata ob...
Guide to the Fullscreen API - Web APIs
ing to another page, changing tabs, or switching to another application (using, for example, alt-tab) while in fullscreen mode exits fullscreen mode as well. example in this example, a video is presented in a web page. pressing the return or enter key lets the user toggle between windowed and fullscreen presentation of the video. view live examples watching for the enter key when the page is loaded, this code is run to set up an event listener to watch for the enter key. document.addeventlistener("keydown", function(e) { if (e.keycode == 13) { togglefullscreen(); } }, false); toggling fullscreen mode this code is called when the user hits the enter key, as seen above. function togglefullscreen() { if (!document.fullscreenelement) { document.documentelement.requestfullscre...
Using the Gamepad API - Web APIs
tion to these events, the api also adds a gamepad object, which you can use to query the state of a connected gamepad, and a navigator.getgamepads() method which you can use to get a list of gamepads known to the page. connecting to a gamepad when a new gamepad is connected to the computer, the focused page first receives a gamepadconnected event. if a gamepad is already connected when the page loaded, the gamepadconnected event is dispatched to the focused page when the user presses a button or moves an axis. in firefox, gamepads are only exposed to a page when the user interacts with one with the page visible. this helps prevent gamepads being used for fingerprinting the user. once one gamepad has been interacted with, other gamepads that are connected will automatically be visible. you ...
GlobalEventHandlers.oncanplay - Web APIs
the oncanplay property of the globaleventhandlers mixin is the eventhandler for processing canplay events. the canplay event is fired when the user agent can play the media, but estimates that not enough data has been loaded to play the media up to its end without having to stop for further buffering of content. syntax element.oncanplay = handlerfunction; var handlerfunction = element.oncanplay; handlerfunction is either null or a javascript function specifying the handler for the event. specification specification status comment html living standardthe definition of 'oncanplay' in that specification. living standard ...
GlobalEventHandlers.oncanplaythrough - Web APIs
the oncanplaythrough property of the globaleventhandlers mixin is the eventhandler for processing canplaythrough events. the canplaythrough event is fired when the user agent can play the media and estimates that enough data has been loaded to play the media up to its end without having to stop for further buffering of content. syntax element.oncanplaythrough = handlerfunction; var handlerfunction = element.oncanplaythrough; handlerfunction is either null or a javascript function specifying the handler for the event. specification specification status comment html living standardthe definition of 'oncanplaythrough' in that specification. living standard ...
GlobalEventHandlers.onemptied - Web APIs
syntax element.onemptied = handlerfunction; var handlerfunction = element.onemptied; handlerfunction should be either null or a javascript function specifying the handler for the event. notes see the dom event handlers page for information on working with on... handlers. the emptied event is fired when 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. see the emptied event documentation for more information about the event. specification specification status comment html living standardthe definition of 'onemptied' in that specification. living standard ...
GlobalEventHandlers.onerror - Web APIs
g, and need to specify a backup image in case the one you need is not available on the server for any reason. <img src="imagenotfound.gif" onerror="this.onerror=null;this.src='imagefound.gif';" /> the reason we have the this.onerror=null in the function is that the browser will be stuck in an endless loop if the onerror image itself generates an error. notes when an error occurs in a script, loaded from a different origin, the details of the error are not reported to prevent leaking information (see bug 363897). instead the error reported is simply "script error." this behavior can be overriden in some browsers using the crossorigin attribute on <script> and having the server send the appropriate cors http response headers. a workaround is to isolate "script error." and handle it knowing t...
GlobalEventHandlers.onloadend - Web APIs
end 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
t 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 living standardthe definition of 'onloadstart' in that specification. living standard initial definition ...
GlobalEventHandlers - Web APIs
keydown event is raised. globaleventhandlers.onkeypress is an eventhandler representing the code to be called when the keypress event is raised. globaleventhandlers.onkeyup is an eventhandler representing the code to be called when the keyup event is raised. globaleventhandlers.onload is an eventhandler representing the code to be called when the load event is raised. globaleventhandlers.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 res...
HTMLAnchorElement.download - Web APIs
the value, if any, specifies the default file name for use in labeling the resource in a local file system. if the name is not a valid file name in the underlying os, the browser will adjust it. note: this value might not be used for download. this value cannot be used to determine whether the download will occur. ...
HTMLAnchorElement - Web APIs
/div> a:hover text { fill: #0095dd; pointer-events: all;} properties inherits properties from its parent, htmlelement, and implements those from htmlhyperlinkelementutils. element.accesskey is a domstring representing a single character that switches input focus to the hyperlink. htmlanchorelement.download is a domstring indicating that the linked resource is intended to be downloaded rather than displayed in the browser. the value represent the proposed name of the file. if the name is not a valid filename of the underlying os, browser will adapt it. htmlhyperlinkelementutils.hash is a usvstring representing the fragment identifier, including the leading hash mark ('#'), if any, in the referenced url. htmlhyperlinkelementutils.host is a usvstring representing the hostname...
HTMLAreaElement - Web APIs
that switches input focus to the control. htmlareaelement.alt is a domstring that reflects the alt html attribute, containing alternative text for the element. htmlareaelement.coords is a domstring that reflects the coords html attribute, containing coordinates to define the hot-spot region. htmlareaelement.download is a domstring indicating that the linked resource is intended to be downloaded rather than displayed in the browser. the value represent the proposed name of the file. if the name is not a valid filename of the underlying os, browser will adapt it. htmlhyperlinkelementutils.hash is a usvstring containing the fragment identifier (including the leading hash mark (#)), if any, in the referenced url. htmlhyperlinkelementutils.host is a usvstring containing the hostname and ...
Audio() - Web APIs
if no url is given. if a url is specified, the browser begins to asynchronously load the media resource before returning the new object. usage notes you can also use other element-creation methods, such as the document object's createelement() method, to construct a new htmlaudioelement. determining when playback can begin there are three ways you can tell when enough of the audio file has loaded to allow playback to begin: check the value of the readystate property. if it's htmlmediaelement.have_future_data, there's enough data available to begin playback and play for at least a short time. if it's htmlmediaelement.have_enough_data, then there's enough data available that, given the current download rate, you should be able to play the audio through to the end without interruption. l...
HTMLAudioElement - Web APIs
n browser's default autoplay policy will block that from happening. refer to firefox and chrome for best practices and work arounds. some of the more commonly used properties of the audio element include src, currenttime, duration, paused, muted, and volume. this snippet copies the audio file's duration to a variable: var audioelement = new audio('car_horn.wav'); audioelement.addeventlistener('loadeddata', () => { let duration = audioelement.duration; // the duration variable now holds the duration (in seconds) of the audio clip }) events inherits methods from its parent, htmlmediaelement, and from its ancestor htmlelement. listen to events using addeventlistener() or by assigning an event listener to the oneventname property of this interface. specifications specification...
HTMLButtonElement.labels - Web APIs
elist of the <label> elements associated with the <button> element. syntax var labelelements = button.labels; return value a nodelist containing the <label> elements associated with the <button> element. example html <label id="label1" for="test">label 1</label> <button id="test">button</button> <label id="label2" for="test">label 2</label> javascript window.addeventlistener("domcontentloaded", function() { const button = document.getelementbyid("test"); for(var i = 0; i < button.labels.length; i++) { console.log(button.labels[i].textcontent); // "label 1" and "label 2" } }); specifications specification status comment html living standardthe definition of 'labels' in that specification. living standard initial definition ...
HTMLCanvasElement.toDataURL() - Web APIs
image formats that use lossy compression such as image/jpeg and image/webp. if this argument is anything else, the default value for image quality is used. the default value is 0.92. other arguments are ignored. return value a domstring containing the requested data uri. exceptions securityerror the canvas's bitmap is not origin clean; at least some of its contents have or may have been loaded from a site other than the one from which the document itself was loaded. examples given this <canvas> element: <canvas id="canvas" width="5" height="5"></canvas> you can get a data-url of the canvas with the following lines: var canvas = document.getelementbyid('canvas'); var dataurl = canvas.todataurl(); console.log(dataurl); // "data:image/png;base64,ivborw0kggoaaaansuheugaaaauaaaafcaya...
HTMLIFrameElement - Web APIs
the nested content. htmliframeelement.scrolling is a domstring that indicates whether the browser should provide scrollbars for the frame. htmliframeelement.src is a domstring that reflects the src html attribute, containing the address of the content to be embedded. note that programatically removing an <iframe>'s src attribute (e.g. via element.removeattribute()) causes about:blank to be loaded in the frame in firefox (from version 65), chromium-based browsers, and safari/ios. htmliframeelement.srcdoc is a domstring that represents the content to display in the frame. htmliframeelement.width is a domstring that reflects the width html attribute, indicating the width of the frame. methods inherits properties from its parent, htmlelement. specifications speci...
Image() - Web APIs
imageelement instance. it is functionally equivalent to document.createelement('img'). disambiguation: image(), the css function notation. syntax var htmlimageelement = new image(width, height); parameters width the width of the image (i.e., the value for the width attribute). height the height of the image (i.e., the value for the height attribute). usage note the entire bitmap is loaded regardless of the sizes specified in the constructor. the size specified in the constructor is reflected through the properties htmlimageelement.width and htmlimageelement.height of the resulting instance. the intrinsic width and height of the image in css pixels are reflected through the properties htmlimageelement.naturalwidth and htmlimageelement.naturalheight. if no size is specified in the c...
HTMLInputElement.labels - Web APIs
erty returns a nodelist of the <label> elements associated with the <input> element. syntax var labelelements = input.labels; return value a nodelist containing the <label> elements associated with the <input> element. example html <label id="label1" for="test">label 1</label> <input id="test"/> <label id="label2" for="test">label 2</label> javascript window.addeventlistener("domcontentloaded", function() { const input = document.getelementbyid("test"); for(var i = 0; i < input.labels.length; i++) { console.log(input.labels[i].textcontent); // "label 1" and "label 2" } }); specifications specification status comment html living standardthe definition of 'labels' in that specification. living standard no change html5the definitio...
HTMLLinkElement.as - Web APIs
syntax var as = htmllinkelement.as htmllinkelement.as = as value a domstring. specifications specification status comment preloadthe definition of 'as' in that specification. candidate recommendation initial definition. browser compatibility the compatibility table on this page is generated from structured data. ...
HTMLLinkElement - Web APIs
6" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmllinkelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties inherits properties from its parent, htmlelement, and linkstyle. htmllinkelement.as is a domstring representing the type of content being loaded by the html link. htmllinkelement.crossorigin is a domstring that corresponds to the cors setting for this link element. see cors settings attributes for details. htmllinkelement.disabled is a boolean which represents whether the link is disabled; currently only used with style sheet links. htmllinkelement.href is a domstring representing the uri for the target resource. htmllinkelement.
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. bubbles no cancelable no interface event event handler property onabort examples const video = document.queryselector('video'); const videosrc = 'https://path/to/video.webm'; video.addeventlistener('abort', () => { console.log(`abort loading: ${videosrc}`); }); const source = document.createelement('source'); source.setattribute('src', videosrc); source.setattribute('type', 'video/webm'); video.appendchild(source); specifications specification status html living standard living standard html5 recommendation ...
HTMLMediaElement.autoplay - Web APIs
ol. for a much more in-depth look at autoplay, autoplay blocking, and how to respond whena autoplay is blocked by the user's browser, see our article autoplay guide for media and web audio apis. syntax htmlmediaelement.autoplay = true | false; var autoplay = htmlmediaelement.autoplay; value a boolean whose value is true if the media element will begin playback as soon as enough content has loaded to allow it to do so without interruption. note: some browsers offer users the ability to override autoplay in order to prevent disruptive audio or video from playing without permission or in the background. do not rely on autoplay actually starting playback and instead use play event. examples ... <video id="video" controls> <source src="https://player.vimeo.com/external/250688977.sd.mp4...
HTMLMediaElement: canplay event - Web APIs
bubbles no cancelable no interface event target element default action none event handler property globaleventhandlers.oncanplay specification html5 media examples these examples add an event listener for the htmlmediaelement's canplay event, then post a message when that event handler has reacted to the event firing. ...
HTMLMediaElement: canplaythrough event - Web APIs
bubbles no cancelable no interface event target element default action none event handler property globaleventhandlers.oncanplaythrough specification html5 media examples these examples add an event listener for the htmlmediaelement's canplaythrough event, then post a message when that event handler has reacted to the event firing. ...
HTMLMediaElement: emptied event - Web APIs
bubbles no cancelable no interface event target element default action none event handler property globaleventhandlers.onemptied specification html5 media examples these examples add an event listener for the htmlmediaelement's emptied event, then post a message when that event handler has reacted to the event firing. ...
HTMLMediaElement: error event - Web APIs
the error event is fired when the resource could not be loaded due to an error (for example, a network connectivity problem). bubbles no cancelable no interface event event handler property onerror examples const video = document.queryselector('video'); const videosrc = 'https://path/to/video.webm'; video.addeventlistener('error', () => { console.error(`error loading: ${videosrc}`); }); video.setattribute('src', videosrc); specifications specification status html living standard living standard html5 recommendation ...
HTMLMediaElement.play() - Web APIs
media source (which may be specified as a mediastream, mediasource, blob, or file, for example) doesn't represent a supported media format. other exceptions may be reported, depending on browser implementation details, media player implementation, and so forth. usage notes although the term "autoplay" is usually thought of as referring to pages that immediately begin playing media upon being loaded, web browsers' autoplay policies also apply to any script-initiated playback of media, including calls to play(). if the user agent is configured not to allow automatic or script-initiated playback of media, calling play() will cause the returned promise to be immediately rejected with a notallowederror. web sites should be prepared to handle this situation. for example, a site should not presen...
HTMLMeterElement.labels - Web APIs
elements associated with the <meter> element. syntax var labelelements = meter.labels; return value a nodelist containing the <label> elements associated with the <meter> element. example html <label id="label1" for="test">label 1</label> <meter id="test" min="0" max="100" value="70">70</meter> <label id="label2" for="test">label 2</label> javascript window.addeventlistener("domcontentloaded", function() { const meter = document.getelementbyid("test"); for(var i = 0; i < meter.labels.length; i++) { console.log(meter.labels[i].textcontent); // "label 1" and "label 2" } }); specifications specification status comment html living standardthe definition of 'labels' in that specification. living standard no change html5the definitio...
Option() - Web APIs
nt, i.e. the value attribute of the equivalent <option>. if this is not specified, the value of text is used as the value, e.g. for the associated <select> element's value when the form is submitted to the server. defaultselected optional a boolean that sets the selected attribute value, i.e. so that this <option> will be the default value selected in the <select> element when the page is first loaded. if this is not specified, a default value of false is used. note that a value of true does not set the option to selected if it is not already selected. selected optional a boolean that sets the option's selected state; the default is false (not selected). if omitted, even if the defaultselected argument is true, the option is not selected. examples just add new options /* assuming we hav...
HTMLOutputElement.labels - Web APIs
elist of the <label> elements associated with the <output> element. syntax var labelelements = output.labels; return value a nodelist containing the <label> elements associated with the <output> element. example html <label id="label1" for="test">label 1</label> <output id="test">output</output> <label id="label2" for="test">label 2</label> javascript window.addeventlistener("domcontentloaded", function() { const output = document.getelementbyid("test"); for(var i = 0; i < output.labels.length; i++) { console.log(output.labels[i].textcontent); // "label 1" and "label 2" } }); specifications specification status comment html living standardthe definition of 'labels' in that specification. living standard no change html5the defini...
HTMLProgressElement.labels - Web APIs
s associated with the <progress> element. syntax var labelelements = progress.labels; return value a nodelist containing the <label> elements associated with the <progress> element. example html <label id="label1" for="test">label 1</label> <progress id="test" value="70" max="100">70%</progress> <label id="label2" for="test">label 2</label> javascript window.addeventlistener("domcontentloaded", function() { const progress = document.getelementbyid("test"); for(var i = 0; i < progress.labels.length; i++) { console.log(progress.labels[i].textcontent); // "label 1" and "label 2" } }); specifications specification status comment html living standardthe definition of 'labels' in that specification. living standard no change html5the ...
HTMLScriptElement - Web APIs
living standard html 5.1the definition of 'htmlscriptelement' in that specification. recommendation html5the definition of 'htmlscriptelement' in that specification. recommendation the following propert...
HTMLSelectElement.labels - Web APIs
ntax var labelelements = select.labels; return value a nodelist containing the <label> elements associated with the <select> element. example html <label id="label1" for="test">label 1</label> <select id="test"> <option value="1">option 1</option> <option value="2">option 2</option> </select> <label id="label2" for="test">label 2</label> javascript window.addeventlistener("domcontentloaded", function() { const select = document.getelementbyid("test"); for(var i = 0; i < select.labels.length; i++) { console.log(select.labels[i].textcontent); // "label 1" and "label 2" } }); specifications specification status comment html living standardthe definition of 'labels' in that specification. living standard no change html5the defini...
HTMLSelectElement.options - Web APIs
ption> elements contained by the <select> element. syntax var options = select.options; return value a htmloptionscollection containing the <option> elements contained by the <select> element. example html <label for="test">label</label> <select id="test"> <option value="1">option 1</option> <option value="2">option 2</option> </select> javascript window.addeventlistener("domcontentloaded", function() { const select = document.getelementbyid("test"); for(var i = 0; i < select.options.length; i++) { console.log(select.options[i].label); // "option 1" and "option 2" } }); specifications specification status comment html living standardthe definition of 'options' in that specification. living standard no change html5the definit...
HTMLTextAreaElement.labels - Web APIs
<label> elements associated with the <textarea> element. syntax var labelelements = textarea.labels; return value a nodelist containing the <label> elements associated with the <textarea> element. example html <label id="label1" for="test">label 1</label> <textarea id="test">some text</textarea> <label id="label2" for="test">label 2</label> javascript window.addeventlistener("domcontentloaded", function() { const textarea = document.getelementbyid("test"); for(var i = 0; i < textarea.labels.length; i++) { console.log(textarea.labels[i].textcontent); // "label 1" and "label 2" } }); specifications specification status comment html living standardthe definition of 'labels' in that specification. living standard no change html5the ...
HTMLVideoElement.msIsStereo3D - Web APIs
this proprietary property is specific to internet explorer and microsoft edge. syntax htmlvideoelement.msisstereo3d: boolean; value boolean value set to true indicates that the video source is stereo 3d. ...
HTMLVideoElement - Web APIs
mirror gets or sets whether a video element is flipped horizontally in the display. htmlvideoelement.msinsertvideoeffect() inserts the specified video effect into the media pipeline. htmlvideoelement.msislayoutoptimalforplayback read only indicates whether the video can be rendered more efficiently. htmlvideoelement.msisstereo3d read only determines whether the system considers the loaded video source to be stereo 3-d or not. value set to true indicates source is stereo 3d. htmlvideoelement.mszoom controls whether the video frame is trimmed to fit the video display. methods inherits methods from its parent, htmlmediaelement, and from its ancestor htmlelement. htmlvideoelement.getvideoplaybackquality() returns a videoplaybackquality object that contains the current pla...
In depth: Microtasks and the JavaScript runtime environment - Web APIs
gents that are separate from the "main" code; the browser may use a single event loop for all of the workers of a given type or may use multiple event loops to handle them. worklet event loop a worklet event loop is the event loop used to drive agents which run the code for the workelets for a given agent. this includes worklets of type worklet, audioworklet, and paintworklet. several windows loaded from the same origin may be running on the same event loop, each queueing tasks onto the event loop so that their tasks take turns with the processor, one after another. keep in mind that web parlance, the word "window" actually means "browser-level container that web content runs within," including an actual window, a tab, or a frame. there are specific circumstances in which this sharing of an...
The HTML DOM API - Web APIs
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 document events defined by the html standard to allow access to m...
HTML Drag and Drop API - Web APIs
n application. ...
History.length - Web APIs
Web › API › History › length
syntax const length = history.length specifications specification status comment html living standardthe definition of 'history.length' in that specification. ...
Working with the History API - Web APIs
use the url bar to display http://mozilla.org/bar.html, but won't cause the browser to load bar.html or even check that bar.html exists. suppose now that the user navigates to http://google.com, then clicks the back button. at this point, the url bar will display http://mozilla.org/bar.html and history.state will contain the stateobj. the popstate event won't be fired because the page has been reloaded. the page itself will look like bar.html. if the user clicks back once again, the url will change to http://mozilla.org/foo.html, and the document will get a popstate event, this time with a null state object. here too, going back doesn't change the document's contents from what they were in the previous step, although the document might update its contents manually upon receiving the popstate e...
History API - Web APIs
examples the following example assigns a listener to the onpopstate property. and then illustrates some of the methods of the history object to add, replace, and move within the browser history for the current tab. window.onpopstate = function(event) { alert(`location: ${document.location}, state: ${json.stringify(event.state)}`) } history.pushstate({page: 1}, "title 1", "?page=1") hi...
IDBCursor.continuePrimaryKey() - Web APIs
e continueprimarykey() method of the idbcursor interface advances the cursor to the to the item whose key matches the key parameter as well as whose primary key matches the primary key parameter. a typical use case, is to resume the iteration where a previous cursor has been closed, without having to compare the keys one by one. calling this method more than once before new cursor data has been loaded - for example, calling continueprimarykey() twice from the same onsuccess handler - results in an invalidstateerror being thrown on the second call because the cursor’s got value flag has been unset. this method is only valid for cursors coming from an index. using it for cursors coming from an object store will throw an error. note: this feature is available in web workers. syntax cursor.c...
IDBObjectStore.createIndex() - Web APIs
ongs to is not active (e.g. has been deleted or removed.) in firefox previous to version 41, an invalidstateerror was raised in this case as well, which was misleading; this has now been fixed (see bug 1176165.) example in the following example you can see the idbopendbrequest.onupgradeneeded handler being used to update the database structure if a database with 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>'; }; dbop...
IDBObjectStore.deleteIndex() - Web APIs
was raised in this case as well, which was misleading; this has now been fixed (see bug 1176165.) notfounderror occurs if there is no index with the given name (case-sensitive) in the database. example in the following example you can see the idbopendbrequest.onupgradeneeded handler being used to update the database structure if a database with a higher version number is loaded. idbobjectstore.createindex is used to create new indexes on the object store, after 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,...
IDBOpenDBRequest.onupgradeneeded - Web APIs
the onupgradeneeded property of the idbopendbrequest interface is the event handler for the upgradeneeded event, triggered when a database of a bigger version number than the existing stored database is loaded. the event passed to the listener is an idbversionchangeevent. inside the event handler function you can include code to upgrade the database structure, as shown in the example below. note: this feature is available in web workers. syntax idbopendbrequest.onupgradeneeded = function(event) { ... }; example in the following example you can see the onupgradeneeded handler being used 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; // request version 3 of t...
IDBOpenDBRequest - Web APIs
n the same database. also available via the onblocked property. upgradeneeded fired when an attempt was made to open a database with a version number higher than its current version. also available via the onupgradeneeded property. example in the following example you can see the onupgradeneeded handler being used 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...
Using IndexedDB - Web APIs
d to consider what happens if the user has the old version of your app open in one tab and then loads the new version of your app in another. when you call open() with a greater version than the actual version of the database, all other open databases must explicitly acknowledge the request before you can start making changes to the database (an onblocked event is fired until they are closed or reloaded). here's how it works: var openreq = mozindexeddb.open("mytestdatabase", 2); openreq.onblocked = function(event) { // if some other tab is loaded with the database, then it needs to be closed // before we can proceed. console.log("please close all other tabs with this site open!"); }; openreq.onupgradeneeded = function(event) { // all other databases have been closed. set everything up...
IntersectionObserver - Web APIs
all observed targets. intersectionobserver.unobserve() tells the intersectionobserver to stop observing a particular target element. examples var intersectionobserver = new intersectionobserver(function(entries) { // if intersectionratio is 0, the target is out of view // and we do not need to do anything. if (entries[0].intersectionratio <= 0) return; loaditems(10); console.log('loaded new items'); }); // start observing intersectionobserver.observe(document.queryselector('.scrollerfooter')); specifications specification status comment intersection observerthe definition of 'intersectionobserver' in that specification. working draft ...
MediaStream.onaddtrack - Web APIs
a function to be called when the addtrack event occurs on a mediastream instance. this happens when a new track of any kind is added to the media stream. this event is fired when the browser adds a track to the stream (such as when a rtcpeerconnection is renegotiated or a stream being captured using htmlmediaelement.capturestream() gets a new set of tracks because the media element being captured loaded a new source. the addtrack event does not get fired when javascript code explicitly adds tracks to the stream (by calling addtrack()). syntax mediastream.onaddtrack = eventhandler; value this should be set to a function which you provide that accepts as input a mediastreamtrackevent object representing the addtrack event which has occurred. the mediastreamtrack representing the track which ...
MediaStream.onremovetrack - Web APIs
on to be called when the removetrack event occurs on a mediastream instance. this happens when a track of any kind is removed from the media stream. this event is fired when the browser removes a track from the stream (such as when a rtcpeerconnection is renegotiated or a stream being captured using htmlmediaelement.capturestream() gets a new set of tracks because the media element being captured loaded a new source. the removetrack event does not get fired when javascript code explicitly removes tracks from the stream (by calling removetrack()). syntax mediastream.onremovetrack = eventhandler; value this should be set to a function which you provide that accepts as input a mediastreamtrackevent object representing the removetrack event which has occurred. the mediastreamtrack representing...
MediaStreamAudioSourceNode - Web APIs
); var range = document.queryselector('input'); // getusermedia block - grab stream // put it into a mediastreamaudiosourcenode // also output the visuals into a video element if (navigator.mediadevices) { console.log('getusermedia supported.'); navigator.mediadevices.getusermedia ({audio: true, video: true}) .then(function(stream) { video.srcobject = stream; video.onloadedmetadata = function(e) { video.play(); video.muted = true; }; // create a mediastreamaudiosourcenode // feed the htmlmediaelement into it var audioctx = new audiocontext(); var source = audioctx.createmediastreamsource(stream); // create a biquadfilter var biquadfilter = audioctx.createbiquadfilter(); biquadf...
MediaStreamTrackAudioSourceNode - Web APIs
); var range = document.queryselector('input'); // getusermedia block - grab stream // put it into a mediastreamaudiosourcenode // also output the visuals into a video element if (navigator.mediadevices) { console.log('getusermedia supported.'); navigator.mediadevices.getusermedia ({audio: true, video: true}) .then(function(stream) { video.srcobject = stream; video.onloadedmetadata = function(e) { video.play(); video.muted = true; }; // create a mediastreamaudiosourcenode // feed the htmlmediaelement into it var audioctx = new audiocontext(); var source = audioctx.createmediastreamsource(stream); // create a biquadfilter var biquadfilter = audioctx.createbiquadfilter(); biquadf...
Recording a media element - Web APIs
is used to create an url that references the blob; this is then made the value of the recorded video playback element's src attribute (so that you can play the video from the blob) as well as the target of the download button's link. then the download button's download attribute is set. while the download attribute can be a boolean, you can also set it to a string to use as the name for the downloaded file. so by setting the download link's download attribute to "recordedvideo.webm", we tell the browser that clicking the button should download a file named "recordedvideo.webm" whose contents are the recorded video. lines 17-18 the size and type of the recorded media are output to the log area below the two videos and the download button. line 20 the catch() for all the promises outputs t...
MerchantValidationEvent.validationURL - Web APIs
he payment handler-specific data needed to validate the merchant. this data should be passed into the complete() method to let the user agent complete the transaction. syntax validationurl = merchantvalidationevent.validationurl; value a read-only usvstring giving the url from which to load payment handler specific data needed to complete the merchant verification process. once this has been loaded, it should be passed into complete(), either directly or using a promise. see merchant validation in payment processing concepts for more information on the merchant validation process. specifications specification status comment payment request apithe definition of 'merchantvalidationevent.validationurl' in that specification. candidate recommendation initial def...
MessageChannel - Web APIs
roperties messagechannel.port1 read only returns port1 of the channel. messagechannel.port2 read only returns port2 of the channel. constructor messagechannel() returns a new messagechannel object with two new messageport objects. example in the following example, you can see a new channel being created using the messagechannel.messagechannel constructor. when the iframe has loaded, we register an onmessage handler for messagechannel.port1 and transfer messagechannel.port2 to the iframe using the window.postmessage method along with a message. when a message is received back from the iframe, the onmessage function simply outputs the message to a paragraph. var channel = new messagechannel(); var output = document.queryselector('.output'); var iframe = document.queryselec...
MessagePort - Web APIs
. events message fired when a messageport object receives a message. also available via the onmessage property. messageerror fired when a messageport object receives a message that can't be deserialized. also available via the onmessageerror property. example in the following example, you can see a new channel being created using the messagechannel() constructor. when the iframe has loaded, we register an onmessage handler for messagechannel.port1 and transfer messagechannel.port2 to the iframe using the window.postmessage method along with a message. when a message is received back from the iframe, the onmessage function simply outputs the message to a paragraph. var channel = new messagechannel(); var output = document.queryselector('.output'); var iframe = document.queryselect...
Navigator.sendBeacon() - Web APIs
e relative or absolute. data a arraybuffer, arraybufferview, blob, domstring, formdata, or urlsearchparams object containing the data to send. return 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 s...
PageTransitionEvent.persisted - Web APIs
the persisted read-only property indicates if a webpage is loading from a cache. syntax window.addeventlistener('pageshow', function(event) { if (event.persisted) { console.log('page was loaded from cache.'); } }); value a boolean. specifications specification status comment html living standardthe definition of 'pagetransitionevent: persisted' in that specification. living standard initial definition ...
PageTransitionEvent - Web APIs
the pagetransitionevent event object is available inside handler functions for the pageshow and pagehide events, fired when a document is being loaded or unloaded. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 20%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 120" 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" alignment-baseline="middle">event</text></a><polyline points="76,25 86,20 86,3...
Page Visibility API - Web APIs
cument's tab being in the background or part of a window that is minimized, or because the device's screen is off. prerender the page's content is being prerendered and is not visible to the user. a document may start in the prerender state, but will never switch to this state from any other state, since a document can only prerender once. note: not all browsers support prerendering. unloaded the page is in the process of being unloaded from memory. note: not all browsers support the unloaded value. document.onvisibilitychange an eventlistener providing the code to be called when the visibilitychange event is fired. //startsimulation and pausesimulation defined elsewhere function handlevisibilitychange() { if (document.hidden) { pausesimulation(); } else { ...
PaintWorklet.registerPaint - Web APIs
return value undefined exceptions typeerror thrown when one of the arguments is invalid or missing. invalidmodificationerror thrown when the a worklet already exists with the specified name. examples the following shows registering an example worklet module. this should be in a separate js file. note that registerpaint() is called without a reference to paintworklet. the file itself is loaded through css.paintworklet.addmodule() (documented here on the parent class of paintworklet, at worklet.addmodule(). /* checkboardworklet.js */ 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 = 0; y < geom.height/size; y++) { for(let x = 0; x < geom.widt...
PaymentRequest.show() - Web APIs
alue a promise that eventually resolves with a paymentresponse. the promise is resolved when the user accepts the payment request (such as by clicking a "pay" button in the browser's payment sheet). exceptions aborterror the returned promise rejects with an aborterror if the user agent is already showing a payment panel. only one payment panel may be visible at a time across all documents loaded by the user agent. the promise is also rejected with aborterror if the user cancels the payment request. invalidstateerror the promise rejects with an invalidstateerror if the same payment has already been shown for this request (its state is interactive because it is being shown already). notsupportederror the promise rejects with a notsupportederror if the user agent does not support th...
Payment processing concepts - Web APIs
e(fetchvalidationdata(event.validationurl)); } in this example, fetchvalidationdata() is a function which loads the payment handler specific identifying information from the address given by validationurl. note this function must go through the merchant server, because a client typically does not access the validation url itself. by then delivering this data (or a promise which resolves to the loaded data) to the payment handler by passing it into complete(), the payment handler can use the retrieved data and whatever algorithm and other data to support in order to verify that the merchant can use the payment handler. thus, it's important to note that the user agent never sends a merchantvalidation event, unless the user agent itself implements a payment handler. for instance, safari has int...
Using the Payment Request API - Web APIs
ut flow needs to know whether paymentrequest.canmakepayment() will return true even before all line items and their prices are known, you can instantiate paymentrequest with dummy data and pre-query .canmakepayment(). if you call .canmakepayment() multiple times, keep in mind that the first parameter to the paymentrequest constructor should contain the same method names and data. // the page has loaded. should the page use paymentrequest? // if paymentrequest fails, should the page fallback to manual // web form checkout? const supportedpaymentmethods = ... let shouldcallpaymentrequest = true; let fallbacktolegacyonpaymentrequestfailure = false; (new paymentrequest(supportedpaymentmethods, {total: {label: 'stub', amount: {currency: 'usd', value: '0.01'}}}) .canmakepayment() .then(function(r...
PerformanceEventTiming - Web APIs
od: 'post', keepalive: true}); } // use a try/catch instead of feature detecting `first-input` // support, since some browsers throw when using the new `type` option. // https://bugs.webkit.org/show_bug.cgi?id=209216 try { function onfirstinputentry(entry) { // only report fid if the page wasn't hidden prior to // the entry being dispatched. this typically happens when a // page is loaded in a background tab. if (entry.starttime < firsthiddentime) { const fid = entry.processingstart - entry.starttime; // report the fid value to an analytics endpoint. sendtoanalytics({fid}); } } // create a performanceobserver that calls `onfirstinputentry` for each entry. const po = new performanceobserver((entrylist) => { entrylist.getentries().foreach(onfirs...
PerformanceNavigationTiming - Web APIs
ws: performanceresourcetiming.initiatortyperead only returns "navigation". the interface also supports the following properties: performancenavigationtiming.domcomplete read only a domhighrestimestamp representing a time value equal to the time immediately before the browser sets the current document readiness of the current document to complete. performancenavigationtiming.domcontentloadedeventend read only a domhighrestimestamp representing the time value equal to the time immediately after the current document's domcontentloaded event completes. performancenavigationtiming.domcontentloadedeventstart read only a domhighrestimestamp representing the time value equal to the time immediately before the user agent fires the domcontentloaded event at the current document. perform...
PerformanceTiming.domInteractive - Web APIs
e 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 status comment navigation timingthe definition of 'performancetiming.dominteractive' in that specification. recomme...
PerformanceTiming - Web APIs
n the parser started its work, that is when its document.readystate changes to 'loading' and the corresponding readystatechange event is thrown. performancetiming.dominteractive read only when the parser finished its work on the main document, that is when its document.readystate changes to 'interactive' and the corresponding readystatechange event is thrown. performancetiming.domcontentloadedeventstart read only right before the parser sent the domcontentloaded event, that is right after all the scripts that need to be executed right after parsing have been executed. performancetiming.domcontentloadedeventend read only right after all the scripts that need to be executed as soon as possible, in order or not, have been executed. performancetiming.domcomplete read only whe...
Using the Permissions API - Web APIs
user for permission; it runs the revealposition() function if permission is granted (which shows the map), or the positiondenied() function if permission is denied (which makes the "enable geolocation" button appear). "denied" the "enable geolocation" button is revealed (this code needs to be here too, in case the permission state is already set to denied for this origin when the page is first loaded). function handlepermission() { navigator.permissions.query({name:'geolocation'}).then(function(result) { if (result.state == 'granted') { report(result.state); geobtn.style.display = 'none'; } else if (result.state == 'prompt') { report(result.state); geobtn.style.display = 'none'; navigator.geolocation.getcurrentposition(revealposition,positiondenied,ge...
ProgressEvent() - Web APIs
the progressevent() constructor returns a newly created progressevent, representing the current completion of a long process. syntax progressevent = new progressevent(type, {lengthcomputable: abooleanvalue, loaded: anumber, total: anumber}); arguments the progressevent() constructor also inherits arguments from event(). type is a domstring representing the name of the type of the progressevent. it is case-sensitive. lengthcomputable optional is a 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. it defaults to false. loaded optional is an unsigned long long representing the amount of work already performed by the underlying process. the ra...
Push API - Web APIs
Web › API › Push API
this lets developers deliver asynchronous notifications and updates to users that opt in, resulting in better engagement with timely new content. push concepts and usage when implementing pushmanager subscriptions, it is vitally important that you protect against csrf/xsrf issues in your app. ...
RTCRtpReceiver.getCapabilities() static function - Web APIs
ic function, this is always called using the form: capabilities = rtcrtpreceiver.getcapabilities("audio"); the returned set of capabilities is the most optimistic possible list. it is entirely possible that certain combinations of options may fail to work when you actually try to use them. calling rtcrtpreceiver.getcapabilities() doesn't prime the browser in any way to handle media. nothing is loaded, fetched, or otherwise prepared. it's simply a means of determining what might be usable before starting to try to access media. because the set of capabilities available tend to be stable for a length of time (people don't install and uninstall codecs and the like very often), the media capabilities can in whole or in part provide a cross-origin method for identifying a user. for that reason, i...
RTCRtpSender.getCapabilities() static function - Web APIs
static function, this is always called using the form: capabilities = rtcrtpsender.getcapabilities("audio"); the returned set of capabilities is the most optimistic possible list. it is entirely possible that certain combinations of options may fail to work when you actually try to use them. calling rtcrtpsender.getcapabilities() doesn't prime the browser in any way to handle media. nothing is loaded, fetched, or otherwise prepared. it's simply a means of determining what might be usable before starting to try to access media. because the set of capabilities available tend to be stable for a length of time (people don't install and uninstall codecs and the like very often), the media capabilities can in whole or in part provide a cross-origin method for identifying a user. for that reason, i...
Resource Timing API - Web APIs
nd after connecting to the server, respectively. the last three timestamps are, in order: requeststart - the timestamp before the browser starts requesting the resource from the server; responsestart - the timestamp after the browser receives the first byte of the response from the server; and responseend - the timestamp after the browser receives the last byte of the resource. if the resource is loaded via a secure connection a secureconnectionstart timestamp will be available between the connection start and end events. 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 or...
SVGElement: error event - Web APIs
the error event is fired when an svg element does not load properly or when an error occurs during script execution. this basically implements the standard error dom event. bubbles yes cancelable no interface svgevent event handler property onerror examples svgelem.addeventlistener('error', () => { console.log('svg not loaded properly.'); }) specifications specification status comment scalable vector graphics (svg) 2the definition of 'error' in that specification. candidate recommendation initial definition ...
SVGElement: load event - Web APIs
the load event fires on an svgelement when it is loaded in the browser, e.g. in the dom in the case of an embedded <svg>. it is basically the same as the standard load dom event. bubbles no cancelable no interface svgevent event handler property onload examples svgelem.addeventlistener('load', () => { console.log('svg loaded.'); }) specifications specification status comment scalable vector graphics (svg) 2the definition of 'load' in that specification. candidate recommendation initial definition ...
SVGElement: unload event - Web APIs
the unload event is fired when the dom implementation removes an svg document from a window or frame. bubbles no cancelable no interface svgevent event handler property onunload examples svgelem.addeventlistener('unload', () => { console.log('svg unloaded.'); }) specifications specification status comment scalable vector graphics (svg) 2the definition of 'unload' in that specification. candidate recommendation initial definition ...
SVGElement - Web APIs
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 document is being resized. also available via the onresize property. scroll fired when an svg document view is being shifted along the x and/or y axes. also available via the onscroll property. unload fired when the dom implementation removes an svg document from a window or frame. also available via the on...
Using the Screen Capture API - Web APIs
security in order to function when feature policy is enabled, you will need the display-capture permission. this can be done using the feature-policy http header or—if you're using the screen capture api in an <iframe>, the <iframe> element's allow attribute. ...
ScriptProcessorNode: audioprocess event - Web APIs
fired when an input buffer of a script processor is ready to be processed. ...
Selection.rangeCount - Web APIs
after the user clicks on the page, rangecount is 1, even if no selection is visible. a user can normally only select one range at a time, so the rangecount will usually be 1. scripting can be used to make the selection contain more than one range. gecko browsers allow multiple selections across table cells. firefox allows to select multiple ranges in the document by using ctrl+click (unless the click within an element with display: table-cell). ...
ServiceWorker - Web APIs
can be associated with the same service worker, each through a unique serviceworker object. a serviceworker object is available in the serviceworkerregistration.active property, and the serviceworkercontainer.controller property — this is a service worker that has been activated and is controlling the page (the service worker has been successfully registered, and the controlled page has been reloaded.) the serviceworker interface is dispatched a set of lifecycle events — install and activate — and functional events including fetch. a serviceworker object has an associated serviceworker.state, related to its lifecycle. properties the serviceworker interface inherits properties from its parent, worker. serviceworker.scripturl read only returns the serviceworker serialized script url...
ServiceWorkerContainer.startMessages() - Web APIs
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 the page has finished loading, but want to start processing the messages right away. note: the messages start being sent automatically whe...
Streams API - Web APIs
rocess them as desired by the developer. concepts and usage streaming involves breaking a resource that you want to receive over a network down into small chunks, then processing it bit by bit. this is something browsers do anyway when receiving assets to be shown on webpages — videos buffer and more is gradually available to play, and sometimes you'll see images display gradually as more is loaded. but this has never been available to javascript before. previously, if we wanted to process a resource of some kind (be it a video, or a text file, etc.), we'd have to download the entire file, wait for it to be deserialized into a suitable format, then process the whole lot after it is fully received. with streams being available to javascript, this all changes — you can now start processin...
TextTrack.mode - Web APIs
Web › API › TextTrack › mode
maintained and events are firing at the appropriate times; the track's text is also being drawn appropriately based on the styling and the track's kind. this is the default value if the text track's default boolean attribute is specified. usage notes the default mode is disabled, unless the default boolean attribute is specified, in which case the default mode is showing. when a text track is loaded in the disabled state, the corresponding webvtt file is not loaded until the state changes to either showing or hidden. this way, the 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 p...
TimeRanges.end() - Web APIs
Web › API › TimeRanges › end
oesn't correspond to an existing range. example given a video element with the id "myvideo": var v = document.getelementbyid("myvideo"); var buf = v.buffered; var numranges = buf.length; if (buf.length == 1) { // only one range if (buf.start(0) == 0 && buf.end(0) == v.duration) { // the one range starts at the beginning and ends at // the end of the video, so the whole thing is loaded } } this example looks at the time ranges and looks to see if the entire video has been loaded. specifications specification status comment html living standardthe definition of 'timeranges.end()' in that specification. living standard initial definition ...
TimeRanges.length - Web APIs
Web › API › TimeRanges › length
t. syntax length = timeranges.length; example given a video element with the id "myvideo": var v = document.getelementbyid("myvideo"); var buf = v.buffered; var numranges = buf.length; if (buf.length == 1) { // only one range if (buf.start(0) == 0 && buf.end(0) == v.duration) { // the one range starts at the beginning and ends at // the end of the video, so the whole thing is loaded } } this example looks at the time ranges and looks to see if the entire video has been loaded. specifications specification status comment html living standardthe definition of 'timeranges.length()' in that specification. living standard initial definition ...
TimeRanges.start() - Web APIs
Web › API › TimeRanges › start
oesn't correspond to an existing range. example given a video element with the id "myvideo": var v = document.getelementbyid("myvideo"); var buf = v.buffered; var numranges = buf.length; if (buf.length == 1) { // only one range if (buf.start(0) == 0 && buf.end(0) == v.duration) { // the one range starts at the beginning and ends at // the end of the video, so the whole thing is loaded } } this example looks at the time ranges and looks to see if the entire video has been loaded. specifications specification status comment html living standardthe definition of 'timeranges.start()' in that specification. living standard initial definition ...
Touch events - Web APIs
the page loads, the startup() function shown below will be called. function startup() { var el = document.getelementbyid("canvas"); el.addeventlistener("touchstart", handlestart, false); el.addeventlistener("touchend", handleend, false); el.addeventlistener("touchcancel", handlecancel, false); el.addeventlistener("touchmove", handlemove, false); } document.addeventlistener("domcontentloaded", startup); this simply sets up all the event listeners for our <canvas> element so we can handle the touch events as they occur. tracking new touches we'll keep track of the touches in-progress. var ongoingtouches = []; when a touchstart event occurs, indicating that a new touch on the surface has occurred, the handlestart() function below is called. function handlestart(evt) { evt.prev...
URL.createObjectURL() - Web APIs
ecified source object. examples see using object urls to display images. usage notes memory management each time you call createobjecturl(), a new object url is created, even if you've already created one for the same object. each of these must be released by calling url.revokeobjecturl() when you no longer need them. browsers will release object urls automatically when the document is unloaded; however, for optimal performance and memory usage, if there are safe times when you can explicitly unload them, you should do so. using object urls for media streams in older versions of the media source specification, attaching a stream to a <video> element required creating an object url for the mediastream. this is no longer necessary, and browsers are removing support for doing this. imp...
VTTCue - Web APIs
Web › API › VTTCue
f text within the cue box. vttcue.text returns a domstring with the contents of the cue. methods getcueashtml() returns the cue text as a documentfragment. ...
VideoPlaybackQuality.totalVideoFrames - Web APIs
the videoplaybackquality interface's totalvideoframes read-only property returns the total number of video frames that have been displayed or dropped since the media was loaded. syntax value = videoplaybackquality.totalvideoframes; value the total number of frames that the <video> element has displayed or dropped since the media was loaded into it. essentially, this is the number of frames the element would have presented had no problems occurred. this value is reset when the media is reloaded or replaced. example this example calls getvideoplaybackquality() to obtain a videoplaybackquality object, then determines what percentage of frames have been lost by either corruption or being dropped. if that exceeds 10% (0.1), a function called lostframesthresholdexceeded() is called to, perhaps...
WebGLRenderingContext.vertexAttrib[1234]f[v]() - Web APIs
ribute, but you want to draw everything in a single color, you can use vertexattrib to achieve that without creating a buffer filled with only one value or having to create a separate shader which uses a uniform for the color. this value will be used if a bound array buffer has not been enabled with enablevertexattribarray. attributes may be matrices, in which case columns of the matrix must be loaded into successive vertex attribute slots. the values set with vertexattribpointer are context-global, i.e. they aren't part of the shader state (like generix vertex attribute indexes to shader variable bindings) and aren't part of the vertex array object state (like enabled vertex attribute arrays). the only way to change the values is by calling this function again. examples const a_foobar = gl...
Clearing with colors - Web APIs
anvas element is displayed only if canvas is not supported. --> <canvas>your browser does not seem to support html5 canvas.</canvas> body { text-align : center; } canvas { display : block; width : 280px; height : 210px; margin : auto; padding : 0; border : none; background-color : black; } // run everything inside window load event handler, to make sure // dom is fully loaded and styled before trying to manipulate it, // and to not mess up the global scope. we are giving the event // handler a name (setupwebgl) so that we can refer to the // function object within the function itself. window.addeventlistener("load", function setupwebgl (evt) { "use strict" // cleaning after ourselves. the event handler removes // itself, because it only needs to run once. win...
Detect WebGL - Web APIs
properties and variables you can tweak are different for each api. <p>[ here would go the result of webgl feature detection ]</p> <button>press here to detect webglrenderingcontext</button> body { text-align : center; } button { display : block; font-size : inherit; margin : auto; padding : 0.6em; } // run everything inside window load event handler, to make sure // dom is fully loaded and styled before trying to manipulate it. window.addeventlistener("load", function() { var paragraph = document.queryselector("p"), button = document.queryselector("button"); // adding click event handler to button. button.addeventlistener("click", detectwebglcontext, false); function detectwebglcontext () { // create canvas element. the canvas is not added to the // document...
Compressed texture formats - Web APIs
parameter(gl.compressed_texture_formats). (e.g. ext.compressed_rgba_s3tc_dxt1_ext for the webgl_compressed_texture_s3tc extension.) these can then be used with compressedteximage[23]d or compressedtexsubimage[23]d instead of teximage2d calls. note that webgl makes no functionality available to compress or decompress textures: they must already be in a compressed format and can then be directly uploaded to video memory. all formats support 2d textures. which formats support texture_2d_array and texture_3d targets (in combination with compressedteximage3d) are noted in the following table. compressed texture extensions and which targets they support. extension notes texture_2d_array texture_3d webgl_compressed_texture_astc yes yes webgl_compre...
Adding 2D content to a WebGL context - Web APIs
checked. to get its value, we call gl.getshaderparameter(), specifying the shader and the name of the parameter we want to check (gl.compile_status). if that's false, we know the shader failed to compile, so show an alert with log information obtained from the compiler using gl.getshaderinfolog(), then delete the shader and return null to indicate a failure to load the shader. if the shader was loaded and successfully compiled, the compiled shader is returned to the caller. to use this code we call it like this const shaderprogram = initshaderprogram(gl, vssource, fssource); after we've created a shader program we need to look up the locations that webgl assigned to our inputs. in this case we have one attribute and two uniforms. attributes receive values from buffers. each iteration of...
Animating objects with WebGL - Web APIs
(now) { now *= 0.001; // convert to seconds const deltatime = now - then; then = now; drawscene(gl, programinfo, buffers, deltatime); requestanimationframe(render); } requestanimationframe(render); this code uses requestanimationframe to ask the browser to call the function "render" on each frame. requestanimationframe passes us the time in milliseconds since the page loaded. we convert that to seconds and then subtract from it the last time to compute deltatime which is the number of second since the last frame was rendered. at the end of drawscene we add the code to update squarerotation. squarerotation += deltatime; this code uses the amount of time that's passed since the last time we updated the value of squarerotation to determine how far to rotate the squ...
Animating textures in WebGL - Web APIs
arantees 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 texture data to webgl. that means that you'll not only need to deploy code like using a secure web server, but you'll need a secure server to test with as well. see how do you set up a local testing server? for help. using the video frames as a texture the next change is to inittexture(), which becomes much simpler, since it no longer needs to...
Getting started with WebGL - Web APIs
and games, such as three.js and babylon.js. preparing to render in 3d the first thing you need in order to use webgl for rendering is a canvas. the html fragment below declares a canvas that our sample will draw into. <body> <canvas id="glcanvas" width="640" height="480"></canvas> </body> preparing the webgl context the main() function in our javascript code, is called when our script is loaded. its purpose is to set up the webgl context and start rendering content. // // start here // function main() { const canvas = document.queryselector("#glcanvas"); // initialize the gl context const gl = canvas.getcontext("webgl"); // only continue if webgl is available and working if (gl === null) { alert("unable to initialize webgl. your browser or machine may not support it."); ...
WebGL model view projection - Web APIs
position of the camera being changed, altering what the viewer is currently able to see. the sections below offer an in-depth look into the ideas behind and implementation of the model, view, and projection matrices. these matrices are core to moving data around on the screen, and are concepts that transcend individual frameworks and engines. clip space in a webgl program, data is typically uploaded to the gpu with its own coordinate system and then the vertex shader transforms those points into a special coordinate system known as clip space. any data which extends outside of the clip space is clipped off and not rendered. however, if a triangle straddles the border of this space then it is chopped up into new triangles, and only the parts of the new triangles that are in clip space are kep...
A simple RTCDataChannel sample - Web APIs
ifting. the webrtc api makes heavy use of promises. they make it very easy to chain the steps of the connection process together; if you haven't already read up on this functionality of ecmascript 2015, you should read up on them. similarly, this example uses arrow functions to simplify syntax. starting up when the script is run, we set up an load event listener, so that once the page is fully loaded, our startup() function is called. function startup() { connectbutton = document.getelementbyid('connectbutton'); disconnectbutton = document.getelementbyid('disconnectbutton'); sendbutton = document.getelementbyid('sendbutton'); messageinputbox = document.getelementbyid('message'); receivebox = document.getelementbyid('receivebox'); // set event listeners for user interface widgets...
Using DTMF with WebRTC - Web APIs
audio is true. offeroptions an rtcofferoptions object providing options to specify when calling rtcpeerconnection.createoffer(). in this case, we state that we want to receive audio but not video. dialbutton and logelement these variables will be used to store references to the dial button and the <div> into which logging information will be written. they'll get set up when the page is first loaded. see initialization below. initialization when the page loads, we do some basic setup: we fetch references to the dial button and the log output box elements, and we use addeventlistener() to add an event listener to the dial button so that clicking it calls the connectanddial() function to begin the connection process. window.addeventlistener("load", function() { logelement = document.quer...
Writing WebSocket client applications - Web APIs
fferedamount attribute before attempting to close the connection to determine if any data has yet to be transmitted on the network. if this value isn't 0, there's pending data still, so you may wish to wait before closing the connection. security considerations websockets should not be used in a mixed content environment; that is, you shouldn't open a non-secure websocket connection from a page loaded using https or vice-versa. most browsers now only allow secure websocket connections, and no longer support using them in insecure contexts. ...
Movement, orientation, and motion: A WebXR example - Web APIs
exes into the position table for each vertex; the vertex normals; and the texture coordinates for each vertex. this is all taken directly from the webgl sample code, so refer to lighting in webgl and its preceding articles creating 3d objects using webgl and using textures in webgl. then our loadtexture() function is called to load the texture file. now that the rendering structures and data are loaded, we start preparing to run the xrsession. we connect the session to the webgl layer so it konws what to use as a rendering surface by calling xrsession.updaterenderstate() with a baselayer set to a new xrwebgllayer. we then look at the value of the session_type constant to see whether the webxr context should be immersive or inline. immersive sessions use the local reference space, while inline...
Web Animations API Concepts - Web APIs
iming—and one that handles visual change over time—animation. the timing model keeps track of how far along a set timeline we've come. the animation model determines what the animated object should look like at any given time. timing the timing model is the backbone of working with the waapi. each document has a master timeline, document.timeline, which stretches from the moment the page is loaded to infinity — or until the window is closed. spread along that timeline according to their durations are our animations. each animation is anchored to a point in the timeline by its starttime, representing the moment along the document’s timeline when the animation starts playing. all the animation's playback relies on this timeline: seeking the animation moves the animation’s position alo...
Window: beforeunload event - Web APIs
the document is still visible and the event is still cancelable at this point. bubbles no cancelable yes interface event event handler property onbeforeunload this event enables a web page to trigger a confirmation dialog asking the user if they really want to leave the page. if the user confirms, the browser navigates to the new page, otherwise it cancels the navigation. according to the specification, to show the confirmation dialog an event handler should call preventdefault() on the event. ...
Window.content - Web APIs
Web › API › Window › content
owser or <iframe>) with type="content-primary" attribute on it — the most famous example is firefox main window, browser.xul. in such cases, content returns a reference to the window object for the document currently displayed in the browser. it is a shortcut for browserref.contentwindow. in unprivileged content (webpages), content is normally equivalent to top (except in the case of a webpage loaded in a sidebar, content still refers to the window of the currently selected tab). note: some examples use _content instead of content. the former has been deprecated for a long time, and you should use content in any new code. syntax var windowobject = window.content; example executing the following code in a chrome xul window with a <browser type="content-primary"/> element in it draws a ...
Window.controllers - Web APIs
xulcontrollers (nsicontrollers). specification xul-specific. not part of specification. by default, a window's controller contains the code that supports the global window commands. chrome code can add controllers (to be used in conjunction with the godocommand and goupdatecommand functions in globaloverlay.js). however, the added controllers must be explicitly removed when the window is unloaded, as this is not done automatically. each missing removal can cause bug 415775: assertion: xpconnect is being called on a scope without a 'components' property! ...
Window.history - Web APIs
Web › API › Window › history
see manipulating the browser history for examples and details. in particular, that article explains security features of the pushstate() and replacestate() methods that you should be aware of before using them. ...
Window.matchMedia() - Web APIs
Web › API › Window › matchMedia
javascript let mql = window.matchmedia('(max-width: 600px)'); document.queryselector(".mq-value").innertext = mql.matches; the javascript code simply passes the media query to match into matchmedia() to compile it, then sets the <span>'s innertext to the value of the results' matches property, so that it indicates whether or not the document matches the media query at the moment the page was loaded. html <span class="mq-value"></span> a simple <span> to receive the output. css .mq-value { font: 18px arial, sans-serif; font-weight: bold; color: #88f; padding: 0.4em; border: 1px solid #dde; } result see testing media queries programmatically for additional code examples. specifications specification status comment css object model (cssom) vi...
Privileged features - Web APIs
dows platforms, a dependent window does not show on the task bar. a dependent window also stays in front of the parent window. dependent windows are not implemented on macos x, this option will be ignored. the dependent feature is currently under revision to be removed (bug 214867) in msie 6, the nearest equivalent to this feature is the showmodelessdialog() method. chrome if on, the page is loaded as window's only content, without any of the browser's interface elements. there will be no context menu defined by default and none of the standard keyboard shortcuts will work. the page is supposed to provide a user interface of its own, usually this feature is used to open xul documents (standard dialogs like the javascript console are opened this way). dialog the dialog feature removes al...
Window.parent - Web APIs
Web › API › Window › parent
the window.parent property is a reference to the parent of the current window or subframe. if a window does not have a parent, its parent property is a reference to itself. when a window is loaded in an <iframe>, <object>, or <frame>, its parent is the window with the element embedding the window. syntax var parentwindow = window.parent; example if (window.parent != window.top) { // we're deeper than one down } specifications specification status comment html living standardthe definition of 'window.parent' in that specification. living standard ...
Window.sizeToContent() - Web APIs
the window.sizetocontent() method sizes the window according to its content. in order for it to work, the dom content should be loaded when this function is called—for example, once the domcontentloaded event has been thrown. the minimal size of the window can be clamped. syntax window.sizetocontent() example window.sizetocontent(); specification this feature is not part of any specification. ...
WorkerGlobalScope.console - Web APIs
however, if you are calling console.log() from a sharedworkerglobalscope, the global browser console will receive the logs. specifications not yet part of any specification. ...
Worklet.addModule() - Web APIs
Web › API › Worklet › addModule
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 specified script is invalid or could not be loaded. syntaxerror the specified moduleurl is invalid. examples audioworklet example const audioctx = new audiocontext(); const audioworklet = audioctx.audioworklet; await audioworklet.addmodule('modules/bypassfilter.js', { credentials: 'omit', }); paintworklet example css.paintworklet.addmodule('https://mdn.github.io/houdini-examples/csspaint/intro/worklets/hilite.js'); once a paintworklet...
XMLDocument.async - Web APIs
Web › API › XMLDocument › async
document.async can be set to indicate whether a xmldocument.load() call should be an asynchronous or synchronous request. true is the default value, indicating that documents should be loaded asynchronously. (it has been possible to load documents synchronously since 1.4 alpha.) example function loadxmldata(e) { alert(new xmlserializer().serializetostring(e.target)); // gives querydata.xml contents as string } var xmldoc = document.implementation.createdocument("", "test", null); xmldoc.async = false; xmldoc.onload = loadxmldata; xmldoc.load('querydata.xml'); ...
XMLDocument.load() - Web APIs
Web › API › XMLDocument › load
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). examples var xmldoc = document.implementation.createdocument("", "test", null); function documentloaded (e) { alert(new xmlserializer().serializetostring(e.target)); // gives querydata.xml contents as string } xmldoc.addeventlistener("load", documentloaded, false); xmldoc.load('querydata.xml'); see also the load sample in the xml tests directory. (to test this functionality, create the files on your local disk or on a webserver rather than loading the load.html file from the lxr-generated page...
How to check the security state of an XMLHTTPRequest over SSL - Web APIs
the connection secure? was the used ssl certificate valid and what are its details (owner, expiration, certificate authority, etc.)? notes: this code requires elevated privileges to run; you can only call it from a browser extension or from a xulrunner application. the channel property becomes available only after the request is sent and the connection was established, that is, on readystate loaded, interactive or completed. by setting the mozbackgroundrequest property of the request object and modifying the example appropriately, you can create your own alert dialog to handle ssl exceptions in your firefox extension or xulrunner application. // adapted from the patch for moztcpsocket error reporting (bug 861196). const {cc,ci} = require("chrome"); function createtcperrorfromfailedxhr(x...
XMLHttpRequest() - Web APIs
be sent unless explicitly added using setrequestheader. mozsystem boolean: setting this flag to true allows making cross-site connections without requiring the server to opt-in using cors. requires setting mozanon: true, i.e. this can't be combined with sending cookies or other user credentials. this only works in privileged (reviewed) apps (bug 692677); it does not work on arbitrary webpages loaded in firefox ...
XMLHttpRequest: abort event - Web APIs
m; padding: .2rem; } input { width: 11rem; margin: .5rem; } js const xhrbuttonsuccess = document.queryselector('.xhr.success'); const xhrbuttonerror = document.queryselector('.xhr.error'); const xhrbuttonabort = document.queryselector('.xhr.abort'); const log = document.queryselector('.event-log'); function handleevent(e) { log.textcontent = log.textcontent + `${e.type}: ${e.loaded} bytes transferred\n`; } function addlisteners(xhr) { xhr.addeventlistener('loadstart', handleevent); xhr.addeventlistener('load', handleevent); xhr.addeventlistener('loadend', handleevent); xhr.addeventlistener('progress', handleevent); xhr.addeventlistener('error', handleevent); xhr.addeventlistener('abort', handleevent); } function runxhr(url) { log.textcontent = ...
XMLHttpRequest: error event - Web APIs
m; padding: .2rem; } input { width: 11rem; margin: .5rem; } js const xhrbuttonsuccess = document.queryselector('.xhr.success'); const xhrbuttonerror = document.queryselector('.xhr.error'); const xhrbuttonabort = document.queryselector('.xhr.abort'); const log = document.queryselector('.event-log'); function handleevent(e) { log.textcontent = log.textcontent + `${e.type}: ${e.loaded} bytes transferred\n`; } function addlisteners(xhr) { xhr.addeventlistener('loadstart', handleevent); xhr.addeventlistener('load', handleevent); xhr.addeventlistener('loadend', handleevent); xhr.addeventlistener('progress', handleevent); xhr.addeventlistener('error', handleevent); xhr.addeventlistener('abort', handleevent); } function runxhr(url) { log.textcontent = ...
XMLHttpRequest: load event - Web APIs
m; padding: .2rem; } input { width: 11rem; margin: .5rem; } js const xhrbuttonsuccess = document.queryselector('.xhr.success'); const xhrbuttonerror = document.queryselector('.xhr.error'); const xhrbuttonabort = document.queryselector('.xhr.abort'); const log = document.queryselector('.event-log'); function handleevent(e) { log.textcontent = log.textcontent + `${e.type}: ${e.loaded} bytes transferred\n`; } function addlisteners(xhr) { xhr.addeventlistener('loadstart', handleevent); xhr.addeventlistener('load', handleevent); xhr.addeventlistener('loadend', handleevent); xhr.addeventlistener('progress', handleevent); xhr.addeventlistener('error', handleevent); xhr.addeventlistener('abort', handleevent); } function runxhr(url) { log.textcontent = ...
XMLHttpRequest: loadend event - Web APIs
m; padding: .2rem; } input { width: 11rem; margin: .5rem; } js const xhrbuttonsuccess = document.queryselector('.xhr.success'); const xhrbuttonerror = document.queryselector('.xhr.error'); const xhrbuttonabort = document.queryselector('.xhr.abort'); const log = document.queryselector('.event-log'); function handleevent(e) { log.textcontent = log.textcontent + `${e.type}: ${e.loaded} bytes transferred\n`; } function addlisteners(xhr) { xhr.addeventlistener('loadstart', handleevent); xhr.addeventlistener('load', handleevent); xhr.addeventlistener('loadend', handleevent); xhr.addeventlistener('progress', handleevent); xhr.addeventlistener('error', handleevent); xhr.addeventlistener('abort', handleevent); } function runxhr(url) { log.textcontent = ...
XMLHttpRequest: loadstart event - Web APIs
m; padding: .2rem; } input { width: 11rem; margin: .5rem; } js const xhrbuttonsuccess = document.queryselector('.xhr.success'); const xhrbuttonerror = document.queryselector('.xhr.error'); const xhrbuttonabort = document.queryselector('.xhr.abort'); const log = document.queryselector('.event-log'); function handleevent(e) { log.textcontent = log.textcontent + `${e.type}: ${e.loaded} bytes transferred\n`; } function addlisteners(xhr) { xhr.addeventlistener('loadstart', handleevent); xhr.addeventlistener('load', handleevent); xhr.addeventlistener('loadend', handleevent); xhr.addeventlistener('progress', handleevent); xhr.addeventlistener('error', handleevent); xhr.addeventlistener('abort', handleevent); } function runxhr(url) { log.textcontent = ...
XMLHttpRequest.multipart - Web APIs
ial response must be multipart/x-mixed-replace or an error will occur. all requests must be asynchronous. this enables support for server push; for each xml document that's written to this request, a new xml dom document is created and the onload handler is called between documents. note: when this is set, the onload handler and other event handlers are not reset after the first xmldocument is loaded, and the onload handler is called after each part of the response is received. ...
XMLHttpRequest: progress event - Web APIs
m; padding: .2rem; } input { width: 11rem; margin: .5rem; } js const xhrbuttonsuccess = document.queryselector('.xhr.success'); const xhrbuttonerror = document.queryselector('.xhr.error'); const xhrbuttonabort = document.queryselector('.xhr.abort'); const log = document.queryselector('.event-log'); function handleevent(e) { log.textcontent = log.textcontent + `${e.type}: ${e.loaded} bytes transferred\n`; } function addlisteners(xhr) { xhr.addeventlistener('loadstart', handleevent); xhr.addeventlistener('load', handleevent); xhr.addeventlistener('loadend', handleevent); xhr.addeventlistener('progress', handleevent); xhr.addeventlistener('error', handleevent); xhr.addeventlistener('abort', handleevent); } function runxhr(url) { log.textcontent = ...
XMLHttpRequest.readyState - Web APIs
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, loading and done, the names readystate_uninitialized (0), readystate_loading (1), readystate_loaded (2), readystate_interactive (3) and readystate_complete (4) are used. example var xhr = new xmlhttprequest(); console.log('unsent', xhr.readystate); // readystate will be 0 xhr.open('get', '/api', true); console.log('opened', xhr.readystate); // readystate will be 1 xhr.onprogress = function () { console.log('loading', xhr.readystate); // readystate will be 3 }; xhr.onload = function ()...
XSL Transformations in Mozilla FAQ - Web APIs
g the current dom tree. having xslt stylesheet specific to particular media would require to retransform the original xml source, which counteracts the expectations of the user. thus, using media in <?xml-stylesheet ?> is strongly discouraged. future builds might only load an xslt stylesheet if media is not specified, or if the specified media include screen. this does not affect css stylesheets loaded from the generated dom, those honor media just like in pages without xslt. how do i do transformnode? there is transformtodocument and transformtofragment starting with mozilla 1.2 final, see using the mozilla javascript interface to xsl transformations. why does internet explorer require a different xslt namespace than mozilla? ie up to version 6 required a deprecated namespace of a xslt wor...
msCaching - Web APIs
Web › API › msCaching
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 mscaching read/write property specifies whether stream data downloaded using xmlhttprequestis cached to disk or not. this proprietary method is specific to internet explorer and microsoft edge. syntax cachestate = object.mscaching values type: domstring property value description auto disables caching for stream or ms-stream data. enabled enables caching for stream or ms-stream data. disabled disables caching for any data. see also mscac...
Using the alert role - Accessibility
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 an element with an alert role and adds it to the document structure. let myalert = document.createelement("p"); myalert.setatt...
ARIA: feed role - Accessibility
hild that can serve as a distinguishing label. each article should preferably have aria-describedby referring to one or more elements inside the article that serve as the primary content of the article. each article element has aria-posinset set to a value that represents its position in the feed and an aria-setsize set to a value that represents either the total number of articles that have been loaded or the total number in the feed, depending on which value is more helpful to users. if the total number in the feed is not known, set aria-setsize="-1". required javascript features none, except as required by any attributes. for example, setting aria-busy to true during the update operation if needed, and then to false upon completion. examples example implementation of feed pattern spec...
ARIA: tab role - Accessibility
s with aria-selected=true inside the parent element and sets it to false, then sets the triggering element's aria-selected to true. after that, we find all tabpanel elements in the grandparent element, make them all hidden, and finally select the element whose id is equal to the triggering tab's aria-controls and removes the hidden attribute, making it visible. ...
Accessibility Information for Web Authors - Accessibility
window (view > source code ctrl+u or right-click on the status bar). two panes are added at the bottom of the view source code window: the left pane contains the errors and warnings (with their correspondent line number) and the right pane identifies the checkpoint along with an example and a clickable link to the reference/guideline. just wonderful! the html advanced validator may also be downloaded from firefox add-ons: html validator. color contrast analyzer by juicy studio "contrast is the perceived difference between two adjacent colors. (...) contrast is extremely important in web design." wheel of color: pump up the contrast, robert hess, msdn "for this year's list of worst design mistakes, (...) i asked readers of my newsletter to nominate the usability problems th...
-moz-context-properties - CSS: Cascading Style Sheets
note that if a color is set directly on the svg, but then the context color is also specified, the context color overrides the direct color. note: you can find a working example on github. specifications not part of any standard. ...
:-moz-user-disabled - CSS: Cascading Style Sheets
note: this selector is mainly intended to be used by theme developers. ...
::placeholder - CSS: Cascading Style Sheets
nitive concerns. an alternate approach to providing placeholder information is to include it outside of the input in close visual proximity, then use aria-describedby to programmatically associate the <input> with its hint. with this implementation, the hint content is available even if information is entered into the input field, and the input appears free of preexisting input when the page is loaded. most screen reading technology will use aria-describedby to read the hint after the input's label text is announced, and the person using the screen reader can mute it if they find the extra information unnecessary. <label for="user-email">your email address</label> <span id="user-email-hint" class="input-hint">example: jane@sample.com</span> <input id="user-email" aria-describedby="user-email-...
:disabled - CSS: Cascading Style Sheets
Web › CSS › :disabled
<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 < billingitems.length; i++) { billingitems[i].di...
src - CSS: Cascading Style Sheets
Web › CSS › @font-face › src
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 external references or locally-installed font face names. when a font is needed the user agent it...
At-rules - CSS: Cascading Style Sheets
Web › CSS › At-rule
eria of the given condition. @document — a conditional group rule that will apply its content if the document in which the style sheet is applied meets the criteria of the given condition. (deferred to level 4 of css spec) @page — describes the aspect of layout changes that will be applied when printing the document. @font-face — describes the aspect of an external font to be downloaded. @keyframes — describes the aspect of intermediate steps in a css animation sequence. @viewport — describes the aspects of the viewport for small screen devices. (currently at the working draft stage) @counter-style — defines specific counter styles that are not part of the predefined set of styles. (at the candidate recommendation stage, but only implemented in gecko as of writi...
CSS Fonts - CSS: Cascading Style Sheets
Web › CSS › CSS Fonts
it lets you define the style of a font, such as its family, size and weight, line height, and the glyph variants to use when multiple are available for a single character. basic example the following example shows a simple use of basic font properties to style a paragraph of text. ...
Shapes From Images - CSS: Cascading Style Sheets
m to be used for shapes. due to this requirement for cors compatible images, if you are previewing your file locally without using a local web server, your shape will not work. is it a cors issue? devtools can help you to identify cors errors. in chrome the console will alert you to cors problems. in firefox if you inspect the property you will be alerted to the fact that the image could not be loaded. this should alert you to the fact that your image cannot be used as the source of a shape due to cors. setting a threshold the shape-image-threshold property enables the creation of shapes from areas which are not fully transparent. if the value of shape-image-threshold is 0.0 (which is the initial value) then the area must be fully transparent. if the value is 1.0 then it is fully opaque. val...
background-image - CSS: Cascading Style Sheets
er specified is drawn as if it is closest to the user. the borders of the element are then drawn on top of them, and the background-color is drawn beneath them. how the images are drawn relative to the box and its borders is defined by the background-clip and background-origin css properties. if a specified image cannot be drawn (for example, when the file denoted by the specified uri cannot be loaded), browsers handle it as they would a none value. note: even if the images are opaque and the color won't be displayed in normal circumstances, web developers should always specify a background-color. if the images cannot be loaded—for instance, when the network is down—the background color will be used as a fallback. syntax each background image is specified either as the keyword none or a...
font-family - CSS: Cascading Style Sheets
ted element. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. values are separated by commas to indicate that they are alternatives. the browser will select the first font in the list that is installed or that can be downloaded using a @font-face at-rule. it is often convenient to use the shorthand property font to set font-size and other font related properties all at once. you should always include at least one generic family name in a font-family list, since there's no guarantee that any given font is available. this lets the browser select an acceptable fallback font when necessary. the font-family property speci...
Guide to scroll anchoring - CSS: Cascading Style Sheets
as a user of the web, you are probably familiar with the problem that scroll anchoring solves. you browse to a long page on a slow connection and begin to scroll to read the content; while you are busy reading, the part of the page you are looking at suddenly jumps. this has happened because large images or some other elements have just loaded further up in the content. scroll anchoring is a browser feature that aims to solve this problem of content jumping, which happens if content loads in after the user has already scrolled to a new part of the document. how does it work? scroll anchoring adjusts the scroll position to compensate for the changes outside of the viewport. this means that the point in the document the user is looking at remains in the viewport, which may mean their scroll po...
table-layout - CSS: Cascading Style Sheets
wsers use an automatic table layout algorithm. the widths of the table and its cells are adjusted to fit the content. fixed table and column widths are set by the widths of table and col elements or by the width of the first row of cells. cells in subsequent rows do not affect column widths. under the "fixed" layout method, the entire table can be rendered once the first table row has been downloaded and analyzed. this can speed up rendering time over the "automatic" layout method, but subsequent cell content might not fit in the column widths provided. cells use the overflow property to determine whether to clip any overflowing content, but only if the table has a known width; otherwise, they won't overflow the cells. formal definition initial valueautoapplies totable and inline-table ele...
user-select - CSS: Cascading Style Sheets
the user-select css property controls whether the user can select text. this doesn't have any effect on content loaded as chrome, except in textboxes. /* keyword values */ user-select: none; user-select: auto; user-select: text; user-select: contain; user-select: all; /* global values */ user-select: inherit; user-select: initial; user-select: unset; /* mozilla-specific values */ -moz-user-select: none; -moz-user-select: text; -moz-user-select: all; /* webkit-specific values */ -webkit-user-select: none; -webkit-user-select: text; -webkit-user-select: all; /* doesn't work in safari; use only "none" or "text", or else it will allow typing in the <html> container */ /* microsoft-specific values */ -ms-user-select: none; -ms-user-selec...
Video player styling basics - Developer guides
opriate icons, the background colour of the button is set to be transparent, non-repeated, and the element should fully contain the image. simple :hover and :focus states are then set for each button that simply alters the opacity of the button: .controls button:hover, .controls button:focus { opacity:0.5; } to obtain appropriate button images, a set of free common control set icons was downloaded from the web. each image was then converted to a base64 encoded string (using an online base64 image encoder), since the images are quite small, the resultant encoded strings are quite short. since some buttons have dual functionality, e.g. play/pause, and mute/unmute, these buttons have different states that need to be styled. as mentioned earlier, a `data-state` variable is used to indicate wh...
Creating a cross-browser video player - Developer guides
indicating its current value. it also needs to have a maximum value set so that it can display its range correctly, and this can be done via the max attribute, which needs to be set to the maximum playing time of the video. this is obtained from the video's duration attribute, which again is part of the media api. ideally, the correct value of the video's duration attribute is available when the loadedmetadata event is raised, which occurs when the video's metadata has been loaded: video.addeventlistener('loadedmetadata', function() { progress.setattribute('max', video.duration); }); unfortunately in some mobile browsers, when loadedmetadata is raised — if it even is raised — video.duration may not have the correct value, or even any value at all. so something else needs to be done. m...
Audio and video manipulation - Developer guides
for efficiency, you should consider using requestanimationframe() instead of settimeout() when running on browsers that support it. note: due to potential security issues if your video is on a different domain than your code, you'll need to enable cors (cross origin...
Constraint validation - Developer guides
t to the onchange event for the <select> and the oninput event for the <input>: window.onload = function () { document.getelementbyid("country").onchange = checkzip; document.getelementbyid("zip").oninput = checkzip; } you can see a live example of the postal code validation. limiting the size of a file before its upload another common constraint is to limit the size of a file to be uploaded. checking this on the client side before the file is transmitted to the server requires combining the constraint validation api, and especially the field.setcustomvalidity() method, with another javascript api, here the file api. here is the html part: <label for="fs">select a file smaller than 75 kb : </label> <input type="file" id="fs"> this displays: the javascript reads the file selecte...
HTML5 Parser - Developer guides
Web › Guide › HTML › HTML5 › HTML5 Parser
ous common html elements as children of svg elements (without foreignobject) will immediately break out of svg or mathml context. this may make some typos have surprising effects. performance improvement with speculative parsing unrelated to the requirements of html5 specification, the gecko 2 parser uses speculative parsing, in which it continues parsing a document while scripts are being downloaded and executed. this results in improved performance compared to older parsers, because most of the time, gecko can complete these tasks in parallel. to best take advantage of speculative parsing, and help your pages to load as quickly as possible, ensure that when you call document.write(), you write a balanced sub-tree within that chunk of script. a balanced sub-tree is html code in which any el...
Introduction to HTML5 - Developer guides
> doing so will cause even browsers that don't presently support html5 to enter into standards mode, which means that they'll interpret the long-established parts of html in an html5-compliant way while ignoring the new features of html5 they don't support. this is much simpler than the former doctypes, and shorter, making it easier to remember and reducing the amount of bytes that must be downloaded. declaring the character set with the <meta charset> the first thing done on a page is usually indicating the character set that is used. in previous versions of html, it was done using a very complex <meta> element. now, it is very simple: <meta charset="utf-8"> place this right after your <head>, as some browsers restart the parsing of an html document if the declared character set is diffe...
HTML5 - Developer guides
Web › Guide › HTML › HTML5
to animate between different states or using css animations to animate parts of the page without a triggering event, you can now control mobile elements on your page. typography improvement authors have better control to reach better typography. they can control text-overflow and hyphenation, but also can add a shadow to it or control more precisely its decorations. custom typefaces can be downloaded and applied thanks to the new @font-face at-rule. new presentational layouts in order to improve the flexibility of designs, two new layouts have been added: the css multi-column layouts and css flexible box layout. ...
Index - Developer guides
Web › Guide › Index
g media 'live' to computers and devices. this is a fairly complex and nascent subject with a lot of variables, so in this article, we'll introduce you to the subject and let you know how you can get started. 11 media buffering, seeking, and time ranges apps, buffer, html5, timeranges, video, buffering, seeking sometimes it's useful to know how much <audio> or <video> has downloaded or is playable without delay — a good example of this is the buffered progress bar of an audio or video player. this article discusses how to build a buffer/seek bar using timeranges, and other features of the media api. 12 setting up adaptive streaming media sources audio, hls, html5, http live streaming, mpeg-dash, video, adaptive streaming let's say you want to set up an...
HTML attribute: rel - HTML: Hypertext Markup Language
Web › HTML › Attributes › rel
orts an external resource to be used as a stylesheet. the type attribute is not needed as it's a text/css stylesheet, as that is the default value. if it's not a stylesheet of type text/css it is best to declare the type. while this attribute defines the link as being a stylesheet, the interaction with other attributes and other keyterms within the rel value impact whether the stylesheet is downloaded and / or used. when used with the alternate keyword, it defines an alternative style sheet. in this case, include a non-empty title. the external stylesheet will not be used or even downloaded if the media does not match the value of the media attribute. requires the use of the cors protocol for cross-origin fetching. tag valid for the <a>, and <area> elements, it gives a tag (identifie...
<applet>: The Embed Java Applet element - HTML: Hypertext Markup Language
Web › HTML › Element › applet
played on browsers that do not support java. page designers should also remember that content enclosed within the <applet> element may also be rendered as alternative text. archive this attribute refers to an archived or compressed version of the applet and its associated class files, which might help reduce download time. code this attribute specifies the url of the applet's class file to be loaded and executed. applet filenames are identified by a .class filename extension. the url specified by code might be relative to the codebase attribute. codebase this attribute gives the absolute or relative url of the directory where applets' .class files referenced by the code attribute are stored. datafld this attribute, supported by internet explorer 4 and higher, specifies the column name fr...
<body>: The Document Body element - HTML: Hypertext Markup Language
Web › HTML › Element › body
lement instead. link color of text for unvisited hypertext links. this method is non-conforming, use css color property in conjunction with the :link pseudo-class instead. onafterprint function to call after the user has printed the document. onbeforeprint function to call when the user requests printing of the document. onbeforeunload function to call when the document is about to be unloaded. onblur function to call when the document loses focus. onerror function to call when the document fails to load properly. onfocus function to call when the document receives focus. onhashchange function to call when the fragment identifier part (starting with the hash ('#') character) of the document's current address has changed. onlanguagechange function to call when the preferred ...
manifest - HTML: Hypertext Markup Language
Web › HTML › Element › html › manifest
note: manifest-based caching mechanism has been deprecated. use service workers instead. the manifest attribute has only effect during early stages of page load, thus changing it via regular dom interfaces has no effect, window.applicationcache interface instead. ...
<input type="file"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › file
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. value a domstring representing the path to the selected file. ...
<input type="hidden"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › hidden
ing edited content one of the most common uses for hidden inputs is to keep track of what database record needs to be updated when an edit form is submitted. a typical workflow looks like this: user decides to edit some content they have control over, such as a blog post, or a product entry. they get started by pressing the edit button. the content to be edited is taken from the database and loaded into an html form to allow the user to make changes. after editing, the user submits the form, and the updated data is sent back to the server to be updated in the database. the idea here is that during step 2, the id of the record being updated is kept in a hidden input. when the form is submitted in step 3, the id is automatically sent back to the server with the record content. the id lets ...
<meta>: The Document-level Metadata element - HTML: Hypertext Markup Language
Web › HTML › Element › meta
s served with a text/html mime type — not in documents served with an xml mime type. default-style sets the name of the default css style sheet set. x-ua-compatible if specified, the content attribute must have the value "ie=edge". user agents are required to ignore this pragma. refresh this instruction specifies: the number of seconds until the page should be reloaded - only if the content attribute contains a positive integer. the number of seconds until the page should redirect to another - only if the content attribute contains a positive integer followed by the string ';url=', and a valid url. accessibility concerns pages set with a refresh value run the risk of having the time interval being too short. people navigating with the aid of ass...
<script>: The Script element - HTML: Hypertext Markup Language
Web › HTML › Element › script
which do not pass the standard cors checks. to allow error logging for sites which use a separate domain for static media, use this attribute. see cors settings attributes for a more descriptive explanation of its valid arguments. defer this boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing domcontentloaded. scripts with the defer attribute will prevent the domcontentloaded event from firing until the script has loaded and finished evaluating. this attribute must not be used if the src attribute is absent (i.e. for inline scripts), in this case it would have no effect. the defer attribute has no effect on module scripts — they defer by default. scripts with the defer attribute will exe...
<template>: The Content Template element - HTML: Hypertext Markup Language
Web › HTML › Element › template
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. ...
HTML elements reference - HTML: Hypertext Markup Language
Web › HTML › Element
<slot> the html <slot> element—part of the web components technology suite—is a placeholder inside a web component that you can fill with your own markup, which lets you create separate dom trees and present them together. <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. obsolete and deprecated elements warning: these are old html elements which are deprecated and should not be used. you should never use them in new projects, and should replace them in old projects as soon as you can. they are listed here for informational purposes only. element description ...
HTML: Hypertext Markup Language
Web › HTML
e common problems provides links to sections of content explaining how to use html to solve very common problems when creating a web page: dealing with titles, adding images or videos, emphasizing content, creating a basic form, etc. advanced topics cors enabled image the crossorigin attribute, in combination with an appropriate cors header, 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 t...
HTTP authentication - HTTP
ials that are inadequate to access a given resource, the server should respond with the 403 forbidden status code. unlike 401 unauthorized or 407 proxy authentication required, authentication is impossible for this user. authentication of cross-origin images a potential security hole recently been fixed by browsers is authentication of cross-site images. from firefox 59 onwards, image resources loaded from different origins to the current document are no longer able to trigger http authentication dialogs (bug 1423146), preventing user credentials being stolen if attackers were able to embed an arbitrary image into a third-party page. character encoding of http authentication browsers use utf-8 encoding for usernames and passwords. firefox once used iso-8859-1, but changed to utf-8 for parit...
Identifying resources on the Web - HTTP
defined; on a video or audio document, the browser will try to go to the time the anchor represents. it is worth noting that the part after the #, also known as fragment identifier, is never sent to the server with the request. usage notes when using urls in html content, you should generally only use a few of these url schemes. when referring to subresources — that is, files that are being loaded as part of a larger document — you should only use the http and https schemes. increasingly, browsers are removing support for using ftp to load subresources, for security reasons. ftp is still acceptable at the top level (such as typed directly into the browser's url bar, or the target of a link), although some browsers may delegate loading ftp content to another application. examples https...
Resource URLs - HTTP
x browser extensions to load resources internally, but some of the information is available to sites the browser connects to as well. syntax resource urls are composed of two parts: a prefix (resource:), and a url pointing to the resource you want to load: resource://<url> an example: resource://gre/res/svg.css when arrows are found in the resource url's ('->'), it means that the first file loaded the next one: resource://<file-loader> -> <file-loaded> please refer to identifying resources on the web for more general details. in this article, we focus on resource uris, which are used internally by firefox to point to built-in resources. threats because some of the information shared by resource: urls is available to websites, a web page could run internal scripts and inspect internal ...
Browser detection using the user agent - HTTP
having a headache over how to deal with the flip-phone-like device thing. never be satisfied with your webpage until you can open up the dev tools side panel and resize the screen while the webpage looks smooth, fluid, and dynamically resized. the simplest way to do this is to separate all the code that moves content around based on screen size to a single function that is called when the page is loaded and at each resize event thereafter. if there is a lot calculated by this layout function before it determines the new layout of the page, then consider debouncing the event listener such that it is not called as often. also note that there is a huge difference between the media queries (max-width: 25em), not all and (min-width: 25em), and (max-width: 24.99em): (max-width: 25em) excludes (max-wid...
Reason: Credential is not supported if the CORS header ‘Access-Control-Allow-Origin’ is ‘*’ - HTTP
...
HTTP conditional requests - HTTP
ity 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 potential problem: if the downloaded resource has been modified between both downloads, the obtained ranges will correspond to two different versions of the resource, and the final document will be corrupted. to prevent this, conditional requests are used. for ranges, there are two ways of doing this. the more flexible one makes use of if-unmodified-since and if-match and the server returns an error if the precondition fails; the c...
Using Feature Policy - HTTP
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 iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. 'none': the feature is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self'...
Accept-Encoding - HTTP
. even if both the client and the server supports the same compression algorithms, the server may choose not to compress the body of a response, if the identity value is also acceptable. two common cases lead to this: the data to be sent is already compressed and a second compression won't lead to smaller data to be transmitted. this may be the case with some image formats; the server is overloaded and cannot afford the computational overhead induced by the compression requirement. typically, microsoft recommends not to compress if a server uses more than 80% of its computational power. as long as the identity value, meaning no encoding, is not explicitly forbidden, by an identity;q=0 or a *;q=0 without another explicitly set value for identity, the server must never send back a 406 not a...
CSP: base-uri - HTTP
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. 'strict-dynamic' the strict-dynamic source expression specifies 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 allow-list or source expressions such as 'self' or 'unsafe-inline' are ignored. see script-src for an example. 'report-sample' requires a sample of the violating code to be included in the violation report. examples meta tag configuration <meta http-equiv="content-security-policy" content="base-uri 'self'"> apache configuration <ifmodule mo...
CSP: child-src - HTTP
for workers, non-compliant requests are treated as fatal network errors by the user agent. csp version 2 directive type fetch directive default-src fallback yes. if this directive is absent, the user agent will look for the default-src directive. ...
CSP: connect-src - HTTP
the apis that are restricted are: <a> ping, fetch, xmlhttprequest, websocket, eventsource, and navigator.sendbeacon(). note: connect-src 'self' does not resolve to websocket schemas in all browsers, more info: https://github.com/w3c/webappsec-csp/issues/7 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. ...
CSP: default-src - HTTP
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. 'strict-dynamic' the strict-dynamic source expression specifies 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 allow-list or source expressions such as 'self' or 'unsafe-inline' are ignored. see script-src for an example. 'report-sample' requires a sample of the violating code to be included in the violation report. examples no inheritance with default-src if there are other directives specified, default-src does not influence them. the following head...
CSP: font-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 font-src policy: content-security-policy: font-src <source>; content-security-policy: font-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: form-action - HTTP
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. 'strict-dynamic' the strict-dynamic source expression specifies 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 allow-list or source expressions such as 'self' or 'unsafe-inline' are ignored. see script-src for an example. 'report-sample' requires a sample of the violating code to be included in the violation report. examples meta tag configuration <meta http-equiv="content-security-policy" content="form-action 'none'"> apache configuration <ifmodule...
CSP: frame-ancestors - HTTP
host are not allowed. examples: 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 a...
CSP: img-src - HTTP
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. 'strict-dynamic' the strict-dynamic source expression specifies 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 allow-list or source expressions such as 'self' or 'unsafe-inline' are ignored. see script-src for an example. 'report-sample' requires a sample of the violating code to be included in the violation report. examples violation cases given this csp header: content-security-policy: img-src https://example.com/ the following <img> is blocked an...
CSP: navigate-to - HTTP
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. 'strict-dynamic' the strict-dynamic source expression specifies 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 allow-list or source expressions such as 'self' or 'unsafe-inline' are ignored. see script-src for an example. 'report-sample' requires a sample of the violating code to be included in the violation report. examples meta tag configuration <meta http-equiv="content-security-policy" content="navigate-to 'none'"> violation case using a <form>...
CSP: plugin-types - HTTP
instantiation of an <embed>, <object> or <applet> element will fail if: the element to load does not declare a valid mime type, the declared type does not match one of specified types in the plugin-types directive, the fetched resource does not match the declared type. csp version 2 directive type document directive default-src fallback no. not setting this allows anything. ...
CSP: require-sri-for - HTTP
for style; content-security-policy: require-sri-for script style; script requires sri for scripts. style requires sri for style sheets. script style requires sri for both, scripts and style sheets. examples if you set your site to require sri for script and styles using this directive: content-security-policy: require-sri-for script style <script> elements like the following will be loaded as they use a valid integrity attribute. <script src="https://code.jquery.com/jquery-3.1.1.slim.js" integrity="sha256-5i/mq300m779n2ovdrl16lbohwxnudzl/r2avuxyxwa=" crossorigin="anonymous"></script> however, scripts without integrity won't load anymore: <script src="https://code.jquery.com/jquery-3.1.1.slim.js"></script> ...
CSP: script-src-elem - HTTP
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. 'strict-dynamic' the strict-dynamic source expression specifies 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 allow-list or source expressions such as 'self' or 'unsafe-inline' are ignored. see script-src for an example. 'report-sample' requires a sample of the violating code to be included in the violation report. examples fallback to script-src if script-src-elem is absent, user agent falls back to the script-src directive, and if that is absent as...
CSP: style-src - HTTP
s violation cases given this csp header: content-security-policy: style-src https://example.com/ the following stylesheets are blocked and won't load: <link href="https://not-example.com/styles/main.css" rel="stylesheet" type="text/css" /> <style> #inline-style { background: red; } </style> <style> @import url("https://not-example.com/styles/print.css") print; </style> as well as styles loaded using the link header: link: <https://not-example.com/styles/stylesheet.css>;rel=stylesheet inline style attributes are also blocked: <div style="display:none">foo</div> as well as styles that are applied in javascript by setting the style attribute directly, or by setting csstext: document.queryselector('div').setattribute('style', 'display:none;'); document.queryselector('div').style.csst...
Content-Security-Policy-Report-Only - HTTP
n.example.com. content-security-policy-report-only: default-src 'none'; style-src cdn.example.com; report-uri /_/csp-reports the html of signup.html looks like this: <!doctype html> <html> <head> <title>sign up</title> <link rel="stylesheet" href="css/style.css"> </head> <body> ... content ... </body> </html> can you spot the violation? stylesheets are only allowed to be loaded from cdn.example.com, yet the website tries to load one from its own origin (http://example.com). a browser capable of enforcing csp will send the following violation report as a post request to http://example.com/_/csp-reports, when the document is visited: { "csp-report": { "document-uri": "http://example.com/signup.html", "referrer": "", "blocked-uri": "http://example.com/css/st...
Content-Type - HTTP
length: 68137 content-type: multipart/form-data; boundary=---------------------------974767299852498929531610575 -----------------------------974767299852498929531610575 content-disposition: form-data; name="description" some text -----------------------------974767299852498929531610575 content-disposition: form-data; name="myfile"; filename="foo.txt" content-type: text/plain (content of the uploaded file foo.txt) -----------------------------974767299852498929531610575-- specifications specification title rfc 7233, section 4.1: content-type in multipart hypertext transfer protocol (http/1.1): range requests rfc 7231, section 3.1.1.5: content-type hypertext transfer protocol (http/1.1): semantics and content ...
Cross-Origin-Embedder-Policy - HTTP
which you'll need to set as well. to check if cross origin isolation has been successful, you can test against the crossoriginisolated property available to window and worker contexts: if (crossoriginisolated) { // post sharedarraybuffer } else { // do something else } avoiding coep blockage with cors if you enable coep using require-corp and have a cross origin resource that needs to be loaded, it needs to support cors and you need to explicitly mark the resource as loadable from another origin to avoid blockage from coep. for example, you can use the crossorigin attribute for this image from a third-party site: <img src="https://thirdparty.com/img.png" crossorigin> specifications specification html living standardthe definition of 'cross-origin-embedder-policy...
Cross-Origin-Opener-Policy - HTTP
its opener's browsing context group unless the opener itself has a coop of same-origin or same-origin-allow-popups. same-origin-allow-popups retains references to newly opened windows or tabs which either don't set coop or which opt out of isolation by setting a coop of unsafe-none. same-origin isolates the browsing context exclusively to same-origin documents. cross-origin documents are not loaded in the same browsing context. examples certain features depend on cross-origin isolation certain features like sharedarraybuffer objects or performance.now() with unthrottled timers are only available if your document has a coop header with the value same-origin value set. cross-origin-opener-policy: same-origin cross-origin-embedder-policy: require-corp see also the cross-origin-embedder-...
Cross-Origin-Resource-Policy - HTTP
exercise caution using this header in a production environment. ...
Feature-Policy: accelerometer - HTTP
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 iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. 'none': the feature is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self'...
Feature-Policy: ambient-light-sensor - HTTP
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 iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. 'none': the feature is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self'...
Feature-Policy: autoplay - HTTP
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 iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. 'none': the feature is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self'...
Feature-Policy: battery - HTTP
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 iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. 'none': the feature is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self'...
Feature-Policy: camera - HTTP
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 iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. 'none': the feature is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self'...
Feature-Policy: display-capture - HTTP
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 iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. 'none': the feature is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self'...
Feature-Policy: document-domain - HTTP
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 iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. 'none': the feature is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self'...
Feature-Policy: encrypted-media - HTTP
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 iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. 'none': the feature is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self'...
Feature-Policy: fullscreen - HTTP
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 iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. 'none': the feature is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self'...
Feature-Policy: geolocation - HTTP
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 iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. 'none': the feature is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self'...
Feature-Policy: gyroscope - HTTP
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 iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. 'none': the feature is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self'...
Feature-Policy: layout-animations - HTTP
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 iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. 'none': the feature is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self'...
Feature-Policy: legacy-image-formats - HTTP
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 iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. 'none': the feature is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self'...
Feature-Policy: magnetometer - HTTP
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 iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. 'none': the feature is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self'...
Feature-Policy: microphone - HTTP
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 iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. 'none': the feature is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self'...
Feature-Policy: midi - HTTP
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 iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. 'none': the feature is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self'...
Feature-Policy: oversized-images - HTTP
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 iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. 'none': the feature is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self'...
Feature-Policy: payment - HTTP
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 iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. 'none': the feature is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self'...
Feature-Policy: picture-in-picture - HTTP
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 iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. 'none': the feature is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self'...
Feature-Policy: publickey-credentials-get - HTTP
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 iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. 'none': the feature is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self'...
Feature-Policy: screen-wake-lock - HTTP
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 iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. 'none': the feature is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self'...
Feature-Policy: sync-xhr - HTTP
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 iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. 'none': the feature is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self'...
Feature-Policy: unoptimized-images - HTTP
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 iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. 'none': the feature is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self'...
Feature-Policy: usb - HTTP
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 iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. 'none': the feature is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self'...
Feature-Policy: vibrate - HTTP
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 iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. 'none': the feature is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self'...
Feature-Policy: wake-lock - HTTP
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 iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. 'none': the feature is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self'...
web-share - HTTP
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 iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. 'none': the feature is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self'...
Feature-Policy: xr-spatial-tracking - HTTP
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 iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. 'none': the feature is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self'...
Feature-Policy - HTTP
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 iframe allow attribute only) the feature will be allowed in this iframe, as long as the document loaded into it comes from the same origin as the url in the iframe's src attribute. 'none': the feature is disabled in top-level and nested browsing contexts. <origin(s)>: the feature is allowed for specific origins (for example, https://example.com). origins should be separated by a space. the values * (enable for all origins) or 'none' (disable for all origins) may only be used alone, while 'self'...
If-None-Match - HTTP
etween 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 requests ...
Save-Data - HTTP
the save-data header field is a boolean which, in requests, indicates the client's preference for reduced data usage. this could be for reasons such as high transfer costs, slow connection speeds, etc. a value of on indicates explicit user opt-in into a reduced data usage mode on the client, and when communicated to origins allows them to deliver alternative content to reduce the data downloaded such as smaller image and video resources, different markup and styling, disabled polling and automatic updates, and so on. note: disabling http/2 server push (rfc 7540, section 8.2: server push) might be desirable too for reducing data downloads. syntax save-data: <sd-token> directives <sd-token> a numerical value indicating whether the client wants to opt in to reduced data usage mode. on i...
X-Content-Type-Options - HTTP
ers to block content sniffing that was happening and could transform non-executable mime types into executable mime types. since then, other browsers have introduced it, even if their mime sniffing algorithms were less aggressive. starting with firefox 72, the opting out of mime sniffing is also applied to top-level documents if a content-type is provided. this can cause html web pages to be downloaded instead of being rendered when they are served with a mime type other than text/html. make sure to set both headers correctly. site security testers usually expect this header to be set. note: x-content-type-options only apply request-blocking due to nosniff for request destinations of "script" and "style". however, it also enables cross-origin read blocking (corb) protection for html, txt, jso...
X-DNS-Prefetch-Control - HTTP
ee 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 setting the network.dns.disableprefetchfromhttps preference to false. examples turning on and off prefetching you can either send the x-dns-prefetch-control header server-side, or from individual documents, using the http-equiv attribute on the <meta> element, like this: <meta http-equiv="x-dns-prefetch-control" content="off"> you can reverse t...
X-Frame-Options - HTTP
policy http header has a frame-ancestors directive which obsoletes this header for supporting browsers. header type response header forbidden header name no syntax there are two possible directives for x-frame-options: x-frame-options: deny x-frame-options: sameorigin directives if you specify deny, not only will attempts to load the page in a frame fail when loaded from other sites, attempts to do so will fail when loaded from the same site. on the other hand, if you specify sameorigin, you can still use the page in a frame as long as the site including it in a frame is the same as the one serving the page. deny the page cannot be displayed in a frame, regardless of the site attempting to do so. sameorigin the page can only be displayed in a frame on ...
HTTP Public Key Pinning (HPKP) - HTTP
n-sha256="base64+backup=="; max-age=5184000; includesubdomains' always; lighttpd the following line with your relevant key information (pin-sha256="..." fields) will enable hpkp on lighttpd. setenv.add-response-header = ( "public-key-pins" => "pin-sha256=\"base64+primary==\"; pin-sha256=\"base64+backup==\"; max-age=5184000; includesubdomains") note: this requires the mod_setenv server.module loaded which can be included by the following if not already loaded. server.modules += ( "mod_setenv" ) iis add the following line to the web.config file to send the public-key-pins header: <system.webserver> ... <httpprotocol> <customheaders> <add name="public-key-pins" value="pin-sha256=&quot;base64+primary==&quot;; pin-sha256=&quot;base64+backup==&quot;; max-age=5184000; includesub...
200 OK - HTTP
Web › HTTP › Status › 200
etched and is transmitted in the message body. head: the entity headers are in the message body. post: the resource describing the result of the action is transmitted in the message body. trace: the message body contains the request message as received by the server. the successful result of a put or a delete is often not a 200 ok but a 204 no content (or a 201 created when the resource is uploaded for the first time). status 200 ok specifications specification title rfc 7231, section 6.3.1: 200 ok hypertext transfer protocol (http/1.1): semantics and content ...
302 Found - HTTP
Web › HTTP › Status › 302
of bugged software out there. it is therefore recommended to set the 302 code only as a response for get or head methods and to use 307 temporary redirect instead, as the method change is explicitly prohibited in that case. in the cases where you want the method used to be changed to get, use 303 see other instead. this is useful when you want to give a response to a put method that is not the uploaded resource but a confirmation message such as: 'you successfully uploaded xyz'. status 302 found specifications specification title rfc 7231, section 6.4.3: 302 found hypertext transfer protocol (http/1.1): semantics and content ...
303 See Other - HTTP
Web › HTTP › Status › 303
this response code is usually sent back as a result of put or post. the method used to display this redirected page is always get. ...
307 Temporary Redirect - HTTP
Web › HTTP › Status › 307
ct status response code indicates that the resource requested has been temporarily moved to the url given by the location headers. the method and the body of the original request are reused to perform the redirected request. in the cases where you want the method used to be changed to get, use 303 see other instead. this is useful when you want to give an answer to a put method that is not the uploaded resources, but a confirmation message (like "you successfully uploaded xyz"). the only difference between 307 and 302 is that 307 guarantees that the method and the body will not be changed when the redirected request is made. with 302, some old clients were incorrectly changing the method to get: the behavior with non-get methods and 302 is then unpredictable on the web, whereas the behavior wi...
503 Service Unavailable - HTTP
Web › HTTP › Status › 503
this response should be used for temporary conditions and the retry-after http header should, if possible, contain the estimated time for the recovery of the service. note: together with this response, a user-friendly page explaining the problem should be sent. ...
HTTP response status codes - HTTP
Web › HTTP › Status
rvers are required to support (and therefore that must not return this code) are get and head. 502 bad gateway this error response means that the server, while working as a gateway to get a response needed to handle the request, got an invalid response. 503 service unavailable the server is not ready to handle the request. common causes are a server that is down for maintenance or that is overloaded. note that together with this response, a user-friendly page explaining the problem should be sent. this responses should be used for temporary conditions and the retry-after: http header should, if possible, contain the estimated time before the recovery of the service. the webmaster must also take care about the caching-related headers that are sent along with this response, as these temporary ...
Introduction - JavaScript
ures which are only currently available in the latest versions of firefox, so using the most recent version of firefox is recommended. the web console tool built into firefox is useful for experimenting with javascript; you can use it into two modes: single-line input mode, and multi-line input mode. single-line input in the web console the web console shows you information about the currently loaded web page, and also includes a javascript interpreter that you can use to execute javascript expressions in the current page. to open the web console (ctrl+shift+i on windows and linux or cmd-option-k on mac), open the tools menu in firefox, and select "developer â–¶ web console". the web console appears at the bottom of the browser window. along the bottom of the console is an input line that ...
Regular expressions - JavaScript
, and split() methods of string. this chapter describes javascript regular expressions. creating a regular expression you construct a regular expression in one of two ways: using a regular expression literal, which consists of a pattern enclosed between slashes, as follows: let re = /ab+c/; regular expression literals provide compilation of the regular expression when the script is loaded. if the regular expression remains constant, using this can improve performance. or calling the constructor function of the regexp object, as follows: let re = new regexp('ab+c'); using the constructor function provides runtime compilation of the regular expression. use the constructor function when you know the regular expression pattern will be changing, or you don't know the patte...
TypeError: can't access dead object - JavaScript
ns to keep strong references to dom objects after their parent document has been destroyed. a dead object, is holding a strong (keep alive) reference to a dom element that persists even after it was destroyed in the dom. to avoid these issues, references to dom nodes in foreign document should instead be stored in an object which is specific to that document, and cleaned up when the document is unloaded, or stored as weak references. examples checking if an object is dead components.utils offers a isdeadwrapper() method, which privileged code might use. if (components.utils.isdeadwrapper(window)) { // dead } unprivileged code has no access to component.utils and might just be able catch the exception. try { string(window); } catch (e) { console.log("window is likely dead"); } ...
ReferenceError: "x" is not defined - JavaScript
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 = 'bar'; foo.substring(1); // "ar" wrong ...
Error: Permission denied to access property "x" - JavaScript
the javascript exception "permission denied to access property" occurs when there was an attempt to access an object for which you have no permission. message error: permission denied to access property "x" error type error. what went wrong? there was attempt to access an object for which you have no permission. this is likely an <iframe> element loaded from a different domain for which you violated the same-origin policy. examples no permission to access document <!doctype html> <html> <head> <iframe id="myframe" src="http://www1.w3c-test.org/common/blank.html"></iframe> <script> onload = function() { console.log(frames[0].document); // error: permission denied to access property "document" } </script> </head> <body></body> </html> ...
Promise.any() - JavaScript
t fulfils first }) // expected output: "done quick" rejections with aggregateerror promise.any() rejects with an aggregateerror if no promise fulfils. const perr = new promise((resolve, reject) => { reject('always fails'); }); promise.any([perr]).catch((err) => { console.log(err); }) // expected output: "aggregateerror: no promise in promise.any was resolved" displaying the first image loaded in this example, we have a function that fetches an image and returns a blob. we use promise.any() to fetch a couple of images and display the first one available (i.e. whose promise has resolved). function fetchanddecode(url) { return fetch(url).then(response => { if(!response.ok) { throw new error(`http error! status: ${response.status}`); } else { return response.blob()...
WebAssembly.Memory() constructor - JavaScript
with an initial size of 10 pages (640kib), and a maximum size of 100 pages (6.4mib). its buffer property will return an arraybuffer. var memory = new webassembly.memory({initial:10, maximum:100}); the second way to get a webassembly.memory object is to have it exported by a webassembly module. the following example (see memory.html on github, and view it live also) fetches and instantiates the loaded memory.wasm byte code using the webassembly.instantiatestreaming() method, while importing the memory created in the line above. it then stores some values in that memory, then exports a function and uses it to sum some values. webassembly.instantiatestreaming(fetch('memory.wasm'), { js: { mem: memory } }) .then(obj => { var i32 = new uint32array(memory.buffer); for (var i = 0; i < 10; i++) ...
WebAssembly.Memory.prototype.buffer - JavaScript
it then stores some values in that memory, then exports a function and uses it to sum some values. ...
WebAssembly.Memory - JavaScript
with an initial size of 10 pages (640kib), and a maximum size of 100 pages (6.4mib). its buffer property will return an arraybuffer. var memory = new webassembly.memory({initial:10, maximum:100}); the second way to get a webassembly.memory object is to have it exported by a webassembly module. the following example (see memory.html on github, and view it live also) fetches and instantiates the loaded memory.wasm byte code using the webassembly.instantiatestreaming() method, while importing the memory created in the line above. it then stores some values in that memory, then exports a function and uses it to sum some values. webassembly.instantiatestreaming(fetch('memory.wasm'), { js: { mem: memory } }) .then(obj => { var i32 = new uint32array(memory.buffer); for (var i = 0; i < 10; i++) ...
WebAssembly.Module.customSections() - JavaScript
xt format over to .wasm. the wast2wasm command available as part of the wabt tool has a --debug-names option — specify this during conversion to get a .wasm with a names custom section, for example: wast2wasm simple-name-section.was -o simple-name-section.wasm --debug-names examples using customsections the following example (see the custom-section.html source and live example) compiles the loaded simple-name-section.wasm byte code. we then do a check using webassembly.module.customsections, looking to see whether the module instance contains a "name" custom section by checking that its length is more than 0. since there is a "name" section in the example, an arraybuffer object is returned. webassembly.compilestreaming(fetch('simple-name-section.wasm')) .then(function(mod) { var namese...
WebAssembly.Module.exports() - JavaScript
bly.module.exports(module); parameters module a webassembly.module object. return value an array containing objects representing the exported functions of the given module. exceptions if module is not a webassembly.module object instance, a typeerror is thrown. examples using exports the following example (see our index-compile.html demo on github, and view it live also) compiles the loaded simple.wasm byte code using the webassembly.compilestreaming() method and then sends it to a worker using postmessage(). var worker = new worker("wasm_worker.js"); webassembly.compilestreaming(fetch('simple.wasm')) .then(mod => worker.postmessage(mod) ); in the worker (see wasm_worker.js) we define an import object for the module to use, then set up an event handler to receive the module fro...
WebAssembly.Module.imports() - JavaScript
syntax webassembly.module.imports(module); parameters module a webassembly.module object. return value an array containing objects representing the imported functions of the given module. exceptions if module is not a webassembly.module object instance, a typeerror is thrown. examples using imports the following example (see imports.html source code; see it live also) compiles the loaded simple.wasm module. this module is then queried for its imports. webassembly.compilestreaming(fetch('simple.wasm')) .then(function(mod) { var imports = webassembly.module.imports(mod); console.log(imports[0]); }); the output looks like this: { module: "imports", name: "imported_func", kind: "function" } specifications specification webassembly javascript interface...
WebAssembly.Module - JavaScript
string name. webassembly.module.exports() given a module, returns an array containing descriptions of all the declared exports. webassembly.module.imports() given a module, returns an array containing descriptions of all the declared imports. examples sending a compiled module to a worker the following example (see our index-compile.html demo on github, and view it live also) compiles the loaded simple.wasm byte code using the webassembly.compilestreaming() method and then sends the resulting module instance to a worker using postmessage(). var worker = new worker("wasm_worker.js"); webassembly.compilestreaming(fetch('simple.wasm')) .then(mod => worker.postmessage(mod) ); in the worker (see wasm_worker.js) we define an import object for the module to use, then set up an event handle...
WebAssembly.Table.prototype.get() - JavaScript
function reference you want to retrieve. return value a function reference — this is an exported webassembly function, a javascript wrapper for an underlying wasm function. exceptions if index is greater than or equal to table.prototype.length, a rangeerror is thrown. examples using get the following example (see table.html on github, and view it live also) compiles and instantiates the loaded table.wasm byte code using the webassembly.instantiatestreaming() method. it then retrieves the references stored in the exported table. webassembly.instantiatestreaming(fetch('table.wasm')) .then(function(obj) { var tbl = obj.instance.exports.tbl; console.log(tbl.get(0)()); // 13 console.log(tbl.get(1)()); // 42 }); note how you've got to include a second function invocation operator a...
WebAssembly.compile() - JavaScript
arraybuffer containing the binary code of the .wasm module you want to compile. return value a promise that resolves to a webassembly.module object representing the compiled module. exceptions if buffersource is not a typed array, a typeerror is thrown. if compilation fails, the promise rejects with a webassembly.compileerror. examples using compile the following example compiles the loaded simple.wasm byte code using the compile() function and then sends it to a worker using postmessage(). var worker = new worker("wasm_worker.js"); fetch('simple.wasm').then(response => response.arraybuffer() ).then(bytes => webassembly.compile(bytes) ).then(mod => worker.postmessage(mod) ); note: you'll probably want to use webassembly.compilestreaming() in most cases, as it is more effic...
WebAssembly.instantiate() - JavaScript
etch('simple.wasm').then(response => response.arraybuffer() ).then(bytes => webassembly.instantiate(bytes, importobject) ).then(result => result.instance.exports.exported_func() ); note: you can also find this example at index.html on github (view it live also). second overload example the following example (see our index-compile.html demo on github, and view it live also) compiles the loaded simple.wasm byte code using the webassembly.compilestreaming() method and then sends it to a worker using postmessage(). var worker = new worker("wasm_worker.js"); webassembly.compilestreaming(fetch('simple.wasm')) .then(mod => worker.postmessage(mod) ); in the worker (see wasm_worker.js) we define an import object for the module to use, then set up an event handler to receive the module fro...
Strict mode - JavaScript
ace; // !!! } function private() { } // !!! } function fun(static) { 'use strict'; } // !!! two mozilla-specific caveats: first, if your code is javascript 1.7 or greater (for example in chrome code or when using the right <script type="">) and is strict mode code, let and yield have the functionality they've had since those keywords were first introduced. but strict mode code on the web, loaded with <script src=""> or <script>...</script>, won't be able to use let/yield as identifiers. second, while es5 unconditionally reserves the words class, enum, export, extends, import, and super, before firefox 5 mozilla reserved them only in strict mode. second, strict mode prohibits function statements, not at the top level of a script or function. in normal mode in browsers, function statement...
start_url - Web app manifests
note: the start_url member is purely advisory, and a user agent may ignore it or allow the user to alter it at install time or afterwards. ...
Web app manifests
web app manifests are part of a collection of web technologies called progressive web apps (pwas), which are websites that can be installed to a device’s homescreen without an app store. unlike regular web apps with simple homescreen links or bookmarks, pwas can be downloaded in advance and can work offline, as well as use regular web apis. the web app manifest provides information about a web application in a json text file, necessary for the web app to be downloaded and be presented to the user similarly to a native app (e.g., be installed on the homescreen of a device, providing users with quicker access and a richer experience). pwa manifests include its name, author, icon(s), version, description, and list of all the necessary resources (among other things). can pwa manifest contai...
<mglyph> - MathML
Web › MathML › Element › mglyph
the mathml <mglyph> element is used to display non-standard symbols where existing unicode characters are not available. it may be used within token elements. attributes alt this attribute defines the alternative text describing the image. users will see this displayed if the image url is wrong, the image is not in one of the supported formats, or until the image is downloaded. class, id, style provided for use with stylesheets. height the height of the image. href used to set a hyperlink to a specified uri. mathbackground the background color (if the image has transparency). you can use #rgb, #rrggbb and html color names. src the image url. valign specifies the vertical alignment with respect to the current baseline. width the width of the image. examples <math> <mi><mg...
Using images in HTML - Web media technologies
Web › Media › images
and compatibility factors. additionally, this article provides guidance for selecting the best image file type for a given situation. mapping the width and height attributes of media container elements to their aspect-ratio this changes how browsers load images so their aspect ratios are calculated by the browser early on and can later be used to correct the display size of an image before it's loaded. other topics related topics that may be of interest. learn html: responsive images in this article, we'll learn about the concept of responsive images — images that work well on devices with widely differing screen sizes, resolutions, and other such features — and look at what tools html provides to help implement them. ...
OpenSearch description format
) <image height="16" width="16" type="image/x-icon">https://example.com/favicon.ico</image> <!-- or --> <image height="16" width="16">data:image/x-icon;base64,aaabaaeaebaaa … daaa=</image> firefox caches the icon as a base64 data: uri (search plug-ins are stored in the profile's searchplugins/ folder). http: and https: urls are converted to data: uris when this is done. note: for icons loaded remotely (that is, from https:// uris as opposed to data: uris), firefox will reject icons larger than 10 kilobytes. url describes the url or urls to use for the search. the template attribute indicates the base url for the search query. firefox supports three url types: type="text/html" specifies the url for the actual search query. type="application/x-suggestions+json" specifies t...
Optimizing startup performance - Web Performance
e made asynchronous, with a little work. getting asynchronous here are some suggestions for how to build your startup process to be as asynchronous as possible (whether it's a new app or a port): use the defer or async attribute on script tags needed by the web application. this allows html parsers to continue processing the document, instead of having to wait until the scripts have been downloaded and executed before continuing. if you need to decode asset files (for example, decoding jpeg files and turning them into raw texture data for later use by webgl), that's great to do in workers. when dealing with data supported by the browser (for example, decoding image data), use the decoders built into the browser or device rather than rolling your own or using one from the original codebase...
Performance budgets - Web Performance
time to interactive), a custom metric (e.g. time to hero element), or a threshold over a period of time. why do i need a performance budget? a budget exists to reflect your reachable goals. it's a tradeoff between user experience, against other performance indicators (e.g. conversion rate). these goals can be: timing based (e.g. time to interactive, first contentful paint). quantity-based (e.g. amount of js files/total image size). rule-based (e.g. pagespeed index, lighthouse score). ...
Add to Home screen - Progressive web apps (PWAs)
in our demo. name/short_name: these fields provide an app name to be displayed when representing the app in different places. name provides the full app name, and short_name provides a shortened name to be used when there is insufficient space to display the full name. you are advised to provide both if your app's name is particularly long. start_url: provides a path to the asset that should be loaded when the added-to-home screen app is launched. note that this has to be a relative url pointing to the site index, relative to the url of the manifest. also, be aware that chrome requires this before it will display the install banner, whereas firefox doesn't require it for showing the home-with-a-plus icon. the manifest for our sample app looks like this: { "background_color": "purple", "...
How to make PWAs installable - Progressive web apps (PWAs)
ing system, the web app's icon may be badged with a small icon that indicates that it's a web app. in the screen shot above, for example, the app has a tiny firefox icon, indicating that it's a web app that uses the firefox runtime. splash screen in some browsers, a splash screen is also generated from the information in the manifest, which is shown when the pwa is launched and while it's being loaded started up. the icon and the theme and background colors are used to create this screen. summary in this article, we learned about how we can make pwas installable with a properly-configured web manifest, and how the user can then install the pwa with the "add to home screen" feature of their browser. for more information on a2hs, be sure to read our add to home screen guide. browser suppor...
Graphic design for responsive sites - Progressive web apps (PWAs)
makes sense to reduce visual clutter on a mobile layout. css media queries allow us to serve different css rules dependant on viewport dimensions, and you should consider using mobile first media queries where possible. this means that the default layout before any media queries are encountered in the css is the small screen/mobile layout, not the wide screen/desktop layout. so when the page is loaded on a mobile device, the mobile will only download the mobile assets, and not the desktop resource assets. making html <img>s responsive is not as easy, as there is currently no native mechanism to serve different html images depending on context. there are a number of workarounds, but none of them are perfect right now. for an overview of what's available, read choosing a responsive image soluti...
Mobile first - Progressive web apps (PWAs)
out having the mobile implementation as a default layer to build on. we consider the overall experience during the planning stage, look at what subset of features will be available on mobile, desktop, etc. in tandem and how they will be implemented. then at implementation stage, we present the mobile layout and functionality as the default configuration provided, before additional information is loaded on top of that, whenever appropriate. this means that mobiles (often the target devices with the least available memory, bandwidth or processing power available) can be given an experience suitable for them as quickly as possible, and as free as possible of extraneous information. for example: if you are serving different styling and layout information for different viewport sizes, etc., it ma...
The building blocks of responsive design - Progressive web apps (PWAs)
s. if you wish, you can point to multiple video files via <source> attributes, each with their own source and mime type: <video controls> <source src="videos/720/crystal720.mp4" type="video/mp4"> <source src="videos/720/crystal720.webm" type="video/webm"> </video> but you can go one step further. you can include media attributes on the <source> element containing media queries — the video loaded in the browser will depend on both the format the browser supports, and the results of the media tests. so for example: <video controls> <source src="videos/320/crystal320.mp4" type="video/mp4" media="all and (max-width: 480px)"> <source src="videos/320/crystal320.webm" type="video/webm" media="all and (max-width: 480px)"> <source src="videos/720/crystal720.mp4" type="video/mp4" media="all...
Progressive web apps (PWAs)
s, and a manifest file. secure contexts (https) the web application must be served over a secure network. being a secure site is not only a best practice, but it also establishes your web application as a trusted site especially if users need to make secure transactions. most of the features related to a pwa such as geolocation and even service workers are available only once the app has been loaded using https. service workers a service worker is a script that allows intercepting and control of how a web browser handles its network requests and asset caching. with service workers, web developers can create reliably fast web pages and offline experiences. manifest file a json file that controls how your app appears to the user and ensures that progressive web apps are discoverable. it de...
Applying SVG effects to HTML content - SVG: Scalable Vector Graphics
flexible approach to adding text compared to plain html text. by creating the text using svg elements combined with html you can make a variety of different text effects. you can rotate the text: <svg height="60" width="200"> <text x="0" y="15" fill="blue" transform="rotate(30 20,50)">example text</text> </svg> using external references svg used for clipping, masking, and filtering can be loaded from an external source, as long as that source comes from the same origin as the html document to which it's applied. for example, if your css is in a file named default.css, it can look like this: .target { clip-path: url(resources.svg#c1); } the svg is then imported from a file named resources.svg, using the clip path with the id c1. ...
SVG Conditional Processing Attributes - SVG: Scalable Vector Graphics
s that can be specified on some svg elements to control whether or not the element on which it appears should be rendered. externalresourcesrequired requiredextensions requiredfeatures systemlanguage attributes externalresourcesrequired deprecated since svg 2 if set to true, it indicates that the browser must wait for all the external resources necessary to render that element to be loaded before processing the associated element. value: false|true; animatable: no requiredextensions list all the browser specific capabilities that must be supported by the borwser to be allowed to render the associated element. value: a list of space-separated uri; animatable: no requiredfeatures deprecated since svg 2 list all the features, as defined is the svg 1.1 specification, that must be...
SVG Event Attributes - SVG: Scalable Vector Graphics
Web › SVG › Attribute › Events
roll, onunload document element event attributes oncopy, oncut, onpaste global event attributes oncancel, oncanplay, oncanplaythrough, onchange, onclick, onclose, oncuechange, ondblclick, ondrag, ondragend, ondragenter, ondragexit, ondragleave, ondragover, ondragstart, ondrop, ondurationchange, onemptied, onended, onerror, onfocus, oninput, oninvalid, onkeydown, onkeypress, onkeyup, onload, onloadeddata, onloadedmetadata, onloadstart, onmousedown, onmouseenter, onmouseleave, onmousemove, onmouseout, onmouseover, onmouseup, onmousewheel, onpause, onplay, onplaying, onprogress, onratechange, onreset, onresize, onscroll, onseeked, onseeking, onselect, onshow, onstalled, onsubmit, onsuspend, ontimeupdate, ontoggle, onvolumechange, onwaiting graphical event attributes onactivate, onfocusin, onf...
begin - SVG: Scalable Vector Graphics
Web › SVG › Attribute › begin
should begin, i.e. become active. value <begin-value-list> default value 0s animatable no the <begin-value-list> is a semicolon-separated list of values. each value can be one of the following: <offset-value> this value defines a clock-value that represents a point in time relative to the beginning of the svg document (usually the load or domcontentloaded event). negative values are valid. <syncbase-value> this value defines a syncbase and an optional offset from that syncbase. the element's animation start time is defined relative to the begin or active end of another animation. a valid syncbase-value consists of an id reference to another animation element followed by a dot and either begin or end to identify whether to synchronize with the b...
end - SVG: Scalable Vector Graphics
Web › SVG › Attribute › end
tetransform>, and <set> usage notes default value none value <end-value-list> animatable no the <end-value-list> is a semicolon-separated list of values. each value can be one of the following: <offset-value> this value defines a clock-value that represents a point in time relative to the beginning of the svg document (usually the load or domcontentloaded event). negative values are valid. <syncbase-value> this value defines a syncbase and an optional offset from that syncbase. the element's animation end time is defined relative to the begin or active end of another animation. a valid syncbase-value consists of an id reference to another animation element followed by a dot and either begin or end to identify whether to synchronize with the beg...
restart - SVG: Scalable Vector Graphics
Web › SVG › Attribute › restart
atable no always this value indicates that the animation can be restarted at any time. whennotactive this value indicates that the animation can only be restarted when it is not active (i.e. after the active end). attempts to restart the animation during its active duration are ignored. never this value indicates that the animation cannot be restarted for the time the document is loaded. specifications specification status comment svg animations level 2the definition of 'restart' in that specification. editor's draft no change scalable vector graphics (svg) 1.1 (second edition)the definition of 'restart' in that specification. recommendation initial definition ...
textLength - SVG: Scalable Vector Graphics
oes not extend farther than that distance, using the method or methods specified by the lengthadjust attribute. by default, only the spacing between characters is adjusted, but the glyph size can also be adjusted if you change lengthadjust. by using textlength, you can ensure that your svg text displays at the same width regardless of conditions including web fonts failing to load (or not having loaded yet). four elements are using this attribute: <text>, <textpath>, <tref>, and <tspan> html, body, svg { height: 100%; } <svg viewbox="0 0 200 60" xmlns="http://www.w3.org/2000/svg"> <text y="20" textlength="6em">small text length</text> <text y="40" textlength="120%">big text length</text> </svg> usage notes value <length-percentage> | <number> default value ...
xlink:show - SVG: Scalable Vector Graphics
ed resource is opened in a new window or tab. this is similar to the effect achieved by an html <a> element with target set to _blank. replace this value specifies that the referenced resource is opened in the same window or tab. this is similar to the effect achieved by an html <a> element with target set to _self. embed this value specifies that instead of linking to the resource it will be loaded and shown within the document. this is similar to the effect achieved by an html <img> element. other this value indicates that other markup present in the link, i.e. the target attribute, determines its behavior. none this value specifies that there is no indication for how to refer to the linked resource. specifications specification status comment scalable ve...
SVG Attribute reference - SVG: Scalable Vector Graphics
Web › SVG › Attribute
document event attributes onabort, onerror, onresize, onscroll, onunload global event attributes oncancel, oncanplay, oncanplaythrough, onchange, onclick, onclose, oncuechange, ondblclick, ondrag, ondragend, ondragenter, ondragexit, ondragleave, ondragover, ondragstart, ondrop, ondurationchange, onemptied, onended, onerror, onfocus, oninput, oninvalid, onkeydown, onkeypress, onkeyup, onload, onloadeddata, onloadedmetadata, onloadstart, onmousedown, onmouseenter, onmouseleave, onmousemove, onmouseout, onmouseover, onmouseup, onmousewheel, onpause, onplay, onplaying, onprogress, onratechange, onreset, onresize, onscroll, onseeked, onseeking, onselect, onshow, onstalled, onsubmit, onsuspend, ontimeupdate, ontoggle, onvolumechange, onwaiting graphical event attributes onactivate, onfocusin, onf...
<image> - SVG: Scalable Vector Graphics
Web › SVG › Element › image
to include dynamic svg elements, try <use> with an external url. ...
<script> - SVG: Scalable Vector Graphics
Web › SVG › Element › script
while svg's script element is equivalent to the html <script> element, it has some discrepancies, like it uses the href attribute instead of src and it doesn't support ecmascript modules so far (see browser compatibility below for details) html,body,svg { height:100% } <svg viewbox="0 0 10 10" xmlns="http://www.w3.org/2000/svg"> <script> // <![cdata[ window.addeventlistener('domcontentloaded', () => { function getcolor () { const r = math.round(math.random() * 255).tostring(16).padstart(2,'0') const g = math.round(math.random() * 255).tostring(16).padstart(2,'0') const b = math.round(math.random() * 255).tostring(16).padstart(2,'0') return `#${r}${g}${b}` } document.queryselector('circle').addeventlistener('click', (e) => { e.target.style.fi...
Linking - SVG: Scalable Vector Graphics
Web › SVG › Linking
button graphical elements here --> </g> </a> </svg> the specification says that the browser should navigate to the html document page2.html when the button graphics are clicked. however, target does not work with mozilla's implementation of the svg <a> element in firefox 1.5. (the problem will be fixed in firefox 2.0.) anyway, the resultant behavior in moz svg is that page2.html will be loaded into the frame where the svg button was (i.e. you would now have page2.html embedded inside a 100x50 pixel frame inside page1.html). to get around this, requires a little ugly javascript hacking: button.svg: <?xml version="1.1" encoding="utf-8"?> <svg xmlns="http://www.w3.org/2000/svg"> <g onclick="top.document.href='page2.html'" cursor="pointer"> <!-- button graphical elements here --> ...
SVG as an Image - SVG: Scalable Vector Graphics
4 / thunderbird 3.3 / seamonkey 2.1) introduced support for using svg in these contexts: css list-style-image css content svg <image> element svg <feimage> element canvas drawimage function restrictions for security purposes, gecko places some restrictions on svg content when it's being used as an image: javascript is disabled. external resources (e.g. images, stylesheets) cannot be loaded, though they can be used if inlined through data: uris. :visited-link styles aren't rendered. platform-native widget styling (based on os theme) is disabled. note that the above restrictions are specific to image contexts; they don't apply when svg content is viewed directly, or when it's embedded as a document via the <iframe>, <object>, or <embed> elements. specifications specifi...
Mixed content - Web security
, background-image, and so forth). <object> (data attribute) navigator.sendbeacon (url attribute) other resource types like web fonts and workers may be considered active mixed content, as they are in chrome. warnings in web console the firefox web console displays a mixed content warning message in the net pane when a page on your website has this issue. the mixed content resource that was loaded via http will show up in red, along with the text "mixed content", which links to this page. as well as finding these warnings in the web console, you could use content security policy (csp) to report issues. you could also use an online crawler like ssl-check or missing padlock that will check your website recursively and find links to insecure content. starting in firefox 23, mixed active c...
Same-origin policy - Web security
it helps isolate potentially malicious documents, reducing possible attack vectors. definition of an origin two urls have the same origin if the protocol, port (if specified), and host are the same for both. you may see this referenced as the "scheme/host/port tuple", or just "tuple". ...
Securing your site - Web security
ity problems with your site. this article explains some of those and shows how to configure your server to serve files with the correct mime types. http strict transport security the strict-transport-security: http header lets a website specify that it may only be accessed using https. http access control the cross-origin resource sharing standard provides a way to specify what content may be loaded from other domains. you can use this to prevent your site from being used improperly; in addition, you can use it to establish resources that other sites are expressly permitted to use. content security policy an added layer of security that helps to detect and mitigate certain types of attacks, including cross site scripting (xss) and data injection attacks. these attacks are used for everythi...
Subresource Integrity - Web security
bute of any <script> or <link> element. an integrity value begins with at least one string, with each string including a prefix indicating a particular hash algorithm (currently the allowed prefixes are sha256, sha384, and sha512), followed by a dash, and ending with the actual base64-encoded hash. note: an integrity value may contain multiple hashes separated by whitespace. a resource will be loaded if it matches one of those hashes. example integrity string with base64-encoded sha384 hash: sha384-oqvuafxrkap7fdgccy5uykm6+r9gqq8k/uxy9rx7hnqlgyl1kpzqho1wx4jwy8wc so oqvuafxrkap7fdgccy5uykm6+r9gqq8k/uxy9rx7hnqlgyl1kpzqho1wx4jwy8wc is the "hash" part, and the prefix sha384 indicates that it's a sha384 hash. note: an integrity value's "hash" part is, strictly speaking, a cryptographic dige...
Web security
leakage referer header policy: privacy and security concerns there are privacy and security risks associated with the referer http header. this article describes them and offers advice on mitigating those risks. robots.txt to be written site maps to be written integrity same-origin policy the same-origin policy is a critical security mechanism that restricts how a document or script loaded from one origin can interact with a resource from another origin. it helps isolate potentially malicious documents, reducing possible attack vectors. subresource integrity subresource integrity (sri) is a security feature that enables browsers to verify that resources they fetch (for example, from a cdn) are delivered without unexpected manipulation. it works by allowing you to provide a crypto...
Web Components
across the shadow dom boundary into the standard dom (true), or not (false). event.composedpath: returns the event’s path (objects on which listeners will be invoked). this does not include nodes in shadow trees if the shadow root was created with shadowroot.mode closed. html templates <template> contains an html fragment that is not rendered when a containing document is initially loaded, but can be displayed at runtime using javascript, mainly used as the basis of custom element structures. the associated dom interface is htmltemplateelement. <slot> a placeholder inside a web component that you can fill with your own markup, which lets you create separate dom trees and present them together. the associated dom interface is htmlslotelement. the slot global html attribute assi...
Resources - XSLT: Extensible Stylesheet Language Transformations
...
Basic Example - XSLT: Extensible Stylesheet Language Transformations
ode()"/> </xsl:copy> </xsl:template> </xsl:stylesheet> the example loads using synchronous xmlhttprequest both the .xsl (xslstylesheet) and the .xml (xmldoc) files into memory. the .xsl file is then imported (xsltprocessor.importstylesheet(xslstylesheet)) and the transformation run (xsltprocessor.transformtofragment(xmldoc, document)). this allows fetching of data after the page has been loaded, without initiating a fresh page load. figure 6 : example var xslstylesheet; var xsltprocessor = new xsltprocessor(); var mydom; var xmldoc; function init(){ // load the xslt file, example1.xsl var myxmlhttprequest = new xmlhttprequest(); myxmlhttprequest.open("get", "example1.xsl", false); myxmlhttprequest.send(null); xslstylesheet = myxmlhttprequest.responsexml; xsltprocessor.
Introduction - XSLT: Extensible Stylesheet Language Transformations
xslt allows the author to directly manipulate the structure of a document. ...
Caching compiled WebAssembly modules - WebAssembly
this article explains the best practices around this. ...
Index - WebAssembly
tion target so that they can run on the web. it is also designed to run alongside javascript, allowing both to work together. 2 caching compiled webassembly modules caching, indexeddb, javascript, module, webassembly, compile, wasm caching is useful for improving the performance of an app — we can store compiled webassembly modules on the client so they don't have to be downloaded and compiled every time. this article explains the best practices around this. 3 compiling a new c/c++ module to webassembly c, c++, compiling, emscripten, webassembly, wasm when you’ve written a new code module in a language like c/c++, you can compile it into webassembly using a tool like emscripten. let’s look at how it works. 4 compiling an existing c modul...
Compiling from Rust to WebAssembly - WebAssembly
finally, create the index.js referenced in the html file and give it these contents: const js = import("./node_modules/hello-wasm/hello_wasm.js"); js.then(js => { js.greet("webassembly"); }); note that you need to fill in your npm username again. this imports the new module from the node_modules folder. this isn't considered a best practice, but this is a demo, so it's ok for now. once it's loaded, it calls the greet function from that module, passing "webassembly" as a string. note how there's nothing special here, yet we're calling into rust code. as far as the javascript code can tell, this is just a normal module. we're done making files. let's give this a shot: $ npm install $ npm run serve this starts a web server. load http://localhost:8080 and an alert box appears on the screen,...
Using the WebAssembly JavaScript API - WebAssembly
this article teaches you what you’ll need to know. note: if you are unfamiliar with the basic concepts mentioned in this article and need more explanation, read webassembly concepts first, then come back. some simple examples let’s run through some examples that explain how to use the webassembly javascript api, and how to use it to load a wasm module in a web page. note: you can find the sample code in our webassembly-examples github repo. ...
WebAssembly
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 functions exported webassembly functions are the javascript reflections of webassembly functions which allow calling webassembly code from javascript. this article describes what they are. understanding webassembly text format this article explains...