Search completed in 1.06 seconds.
343 results for "exit":
Your results are loading. Please wait...
GlobalEventHandlers.ondragexit - Web APIs
the globaleventhandler.ondragexit property is an event handler for the dragexit event. the ondragexit event is a gecko specific event listener. if you are building a drag-and-drop feature for a website please see the ondragleave event listener instead. syntax var dragexithandler = targetelement.ondragexit; return value dragexithandler the dragexit event handler for element targetelement. example this example demonstrates using the ondragexit attribute handler to set an element's dragexit event handler. <!doctype html> <html lang=en> <title>examples of using the drag and drop global event attribute</title> <meta content="width=device-width"> <style> div { margin: 0em; padding: 2em; } #source { color: blue; border: 1px solid black; } #target { border: ...
... function dragleave_handler(ev) { console.log("dragleave"); // change the source element's border back to white ev.currenttarget.style.background = "white"; } function dragend_handler(ev) { console.log("dragend"); // change the target element's background color to visually indicate // the drag ended. ...
...onsole.log("dragleave"); // change the source element's border back to white ev.currenttarget.style.background = "white"; } function dragend_handler(ev) { console.log("dragend"); // change the target element's background color to visually indicate // the drag ended. ...
...And 5 more matches
Document.exitFullscreen() - Web APIs
example this example causes the current document to toggle in and out of a full-screen presentation whenever the mouse button is clicked within it. ...
... example this example causes the current document to toggle in and out of a full-screen presentation whenever the mouse button is clicked within it. ...
... example this example causes the current document to toggle in and out of a full-screen presentation whenever the mouse button is clicked within it. ...
...And 3 more matches
PR_CExitMonitor
decrement the entry count associated with a cached monitor. syntax #include <prcmon.h> prstatus pr_cexitmonitor(void *address); parameters the function has the following parameters: address the address of the protected object--the same address previously passed to pr_centermonitor. returns the function returns one of the following values: if successful, pr_success. if unsuccessful, pr_failure. this may indicate that the address parameter is invalid or that the calling thread is not in the monitor. description using the value specified in the address parameter to find a monitor in the monitor cache, pr_cexitmonitor decrements the entry count associated with the monitor. if the decremented entry count is zero, the monitor is exited. ...
PR_ExitMonitor
decrements the entry count associated with a specified monitor and, if the entry count reaches zero, releases the monitor's lock. syntax #include <prmon.h> prstatus pr_exitmonitor(prmonitor *mon); parameter the function has the following parameter: mon a reference to an existing structure of type prmonitor. the monitor object referenced must be one for which the calling thread currently holds the lock. returns the function returns one of the following values: if successful, pr_success. if unsuccessful (the calling thread has not entered the monitor), pr_failure. description if the decremented entry count is zero, pr_exitmonitor releases the monitor's lock. threads that were blocked trying to enter the monitor will be rescheduled. ...
PR_ProcessExit
causes an immediate, nongraceful, forced termination of the process. syntax #include <prinit.h> void pr_processexit(printn status); parameter pr_processexit has one parameter: status the exit status code of the process. ...
Document: dragexit event - Web APIs
the dragexit event is fired when an element is no longer the drag operation's immediate selection target. bubbles yes cancelable no default action none. interface dragevent event handler property ondragexit examples see the drag event for example code or this jsfiddle demo. specifications specification status comment html living standardthe definition of 'dragexit' in that specification. living standard ...
Document.exitPointerLock() - Web APIs
the exitpointerlock() method asynchronously releases a pointer lock previously requested through element.requestpointerlock. to track the success or failure of the request, it is necessary to listen for the pointerlockchange and pointerlockerror events. syntax document.exitpointerlock(); specifications specification status comment pointer lockthe definition of 'document' in that specification. candidate recommendation extend the document interface ...
Index - Web APIs
Web › API › Index
esult based on an xpath expression and other given parameters. 908 document.execcommand() api, dom, method, needsexample, reference, editor when an html document has been switched to designmode, its document object exposes an execcommand method to run commands that manipulate the current editable region, such as form inputs or contenteditable elements. ...
...and() api, dom, method, needsexample, reference, editor when an html document has been switched to designmode, its document object exposes an execcommand method to run commands that manipulate the current editable region, such as form inputs or contenteditable elements. ...
... when an html document has been switched to designmode, its document object exposes an execcommand method to run commands that manipulate the current editable region, such as form inputs or contenteditable elements. ...
...And 8 more matches
Fullscreen API - Web APIs
this makes it possible to present desired content—such as an online game—using the user's entire screen, removing all browser user interface elements and other applications from the screen until full-screen mode is shut off. see the article guide to the fullscreen api for details on how to use the api. note: support for this api varies somewhat across browsers, with many requiring vendor prefixes and/or not implementing the latest specification. ...
...creen api has no interfaces of its own. instead, it augments several other interfaces to add the methods, properties, and event handlers needed to provide full-screen functionality. these are listed in the following sections. methods the fullscreen api adds methods to the document and element interfaces to allow turning off and on full-screen mode. methods on the document interface document.exitfullscreen() requests that the user agent switch from full-screen mode back to windowed mode. returns a promise which is resolved once full-screen mode has been completely shut off. methods on the element interface element.requestfullscreen() asks the user agent to place the specified element (and, by extension, its descendants) into full-screen mode, removing all of the browser's ui elemen...
... available as html content attributes. in other words, you cannot specify event handlers for fullscreenchange and fullscreenerror in the html content. they must be added by javascript code. event handlers on documents document.onfullscreenchange an event handler for the fullscreenchange event that's sent to a document when that document is placed into full-screen mode, or when that document exits full-screen mode. this handler is called only when the entire document is presented in full-screen mode. document.onfullscreenerror an event handler for the fullscreenerror event that gets sent to a document when an error occurs while trying to enable or disable full-screen mode for the entire document. event handlers on elements element.onfullscreenchange an event handler which is calle...
...And 7 more matches
Introduction to NSPR
number of native threads. global threads are scheduled by the host os--not by nspr--either within a process or across processes on the entire host. global threads correspond to native threads on the host os. nspr threads can also be either user threads or system threads. nspr provides a function, pr_cleanup, that synchronizes process termination. pr_cleanup waits for the last user thread to exit before returning, whereas it ignores system threads when determining when a process should exit. this arrangement implies that a system thread should not have volatile data that needs to be safely stored away. priorities for nspr threads are based loosely on hints provided by the client and sometimes constrained by the underlying operating system. therefore, priorities are not rigidly defined. f...
...ing is about protecting data, not code. a monitored invariant is a boolean expression over the monitored data. the expression may be false only when a thread is in the monitor (holding the monitor's mutex). this requirement implies that when a thread first enters the monitor, an evaluation of the invariant expression must yield a true. the thread must also reinstate the monitored invariant before exiting the monitor. therefore, evaluation of the expression must also yield a true at that point in execution. a trivial example might be as follows. suppose an object has three values, v1, v2, and sum. the invariant is that the third value is the sum of the other two. expressed mathematically, the invariant is sum = v1 + v2. any modification of v1 or v2 requires modification of sum. since that is a...
... flux. note: evaluation of the invariant expression is a conceptual requirement and is rarely done in practice. it is valuable to formally define the expression during design, write it down, and adhere to it. it is also useful to implement the expression during development and test it where appropriate. the thread makes an absolute assertion of the expression's evaluation both on entering and on exiting the monitor. acquiring a lock is a synchronous operation. once the lock primitive is called, the thread returns only when it has acquired the lock. should another thread (or the same thread) already have the lock held, the calling thread blocks, waiting for the situation to improve. that blocked state is not interruptible, nor is it timed. condition variables condition variables facilitate ...
...And 6 more matches
Enc Dec MAC Using Key Wrap CertReq PKCS10 CSR
commands */ typedef enum { generate_csr, add_cert_to_db, save_cert_to_header, encrypt, decrypt, sign, verify, unknown } commandtype; typedef enum { symkey = 0, mackey = 1, iv = 2, mac = 3, pad = 4, pubkey = 5, lab = 6, certenc= 7, certvfy= 8, sig = 9 } headertype; /* * print usage message and exit */ static void usage(const char *progname) { fprintf(stderr, "\nusage: %s %s %s %s %s %s %s %s %s %s\n\n", progname, " -<g|a|h|e|ds|v> -d <dbdirpath> ", "[-p <dbpwd> | -f <dbpwdfile>] [-z <noisefilename>] [-a <\"\">]", "-s <subject> -r <csr> | ", "-n <nickname> -t <trust> -c <cert> [ -r <csr> -u <issuernickname> [-x <\"\"...
... fprintf(stderr, "%-30s - certificate signing request \n\n", "-r <csr>"); fprintf(stderr, "%-30s - generate a self-signed cert [optional]\n\n", "-x"); fprintf(stderr, "%-30s - to enable ascii [optional]\n\n", "-a"); fprintf(stderr, "%-30s - to save certificate to header file as sig verification [optional]\n\n", "-v"); exit(-1); } /* * validate the options used for generate csr command */ static void validategeneratecsrcommand(const char *progname, const char *dbdir, certname *subject, const char *subjectstr, const char *certreqfilename) { prbool validationfailed = pr_false; if (!subje...
...= pr_true; } if (!certreqfilename) { pr_fprintf(pr_stderr, "%s -g -d %s -s %s -r: certificate request file name not found\n", progname, dbdir, subjectstr); validationfailed = pr_true; } if (validationfailed) { fprintf(stderr, "\nusage: %s %s \n\n", progname, "-g -d <dbdirpath> -s <subject> -r <csr> \n"); exit(-1); } } /* * validate the options used for add cert to db command */ static void validateaddcerttodbcommand(const char *progname, const char *dbdir, const char *nicknamestr, const char *truststr, const char *certfilename, const char *certreqfile...
...And 6 more matches
sample2
ostring #define port_errortostring(err) pr_errortostring((err), pr_language_i_default) #endif /* sample 6 commands */ typedef enum { generate_csr, add_cert_to_db, save_cert_to_header, encrypt, decrypt, sign, verify, unknown } commandtype; typedef enum { symkey = 0, mackey = 1, iv = 2, mac = 3, pad = 4, pubkey = 5, lab = 6, certenc= 7, certvfy= 8, sig = 9 } headertype; /* * print usage message and exit */ static void usage(const char *progname) { fprintf(stderr, "\nusage: %s %s %s %s %s %s %s %s %s %s\n\n", progname, " -<g|a|h|e|ds|v> -d <dbdirpath> ", "[-p <dbpwd> | -f <dbpwdfile>] [-z <noisefilename>] [-a <\"\">]", "-s <subject> -r <csr> | ", "-n <nickname> -t <trust> -c <cert> [ -r <csr> -u <issuernickname> [-x <\"\">] -m <serialnumber> ] | ", "-n <nickname> -b <headerfilename> | ", "-b <hea...
...rintf(stderr, "%-30s - certificate issuer nickname\n\n", "-u <issuernickname>"); fprintf(stderr, "%-30s - certificate signing request \n\n", "-r <csr>"); fprintf(stderr, "%-30s - generate a self-signed cert [optional]\n\n", "-x"); fprintf(stderr, "%-30s - to enable ascii [optional]\n\n", "-a"); fprintf(stderr, "%-30s - to save certificate to header file as sig verification [optional]\n\n", "-v"); exit(-1); } /* * validate the options used for generate csr command */ static void validategeneratecsrcommand(const char *progname, const char *dbdir, certname *subject, const char *subjectstr, const char *certreqfilename) { prbool validationfailed = pr_false; if (!subject) { pr_fprintf(pr_stderr, "%s -g -d %s -s: improperly formatted name: \"%s\"\n", progname, dbdir, subjectstr); validationfailed = p...
...d %s -s: improperly formatted name: \"%s\"\n", progname, dbdir, subjectstr); validationfailed = pr_true; } if (!certreqfilename) { pr_fprintf(pr_stderr, "%s -g -d %s -s %s -r: certificate request file name not found\n", progname, dbdir, subjectstr); validationfailed = pr_true; } if (validationfailed) { fprintf(stderr, "\nusage: %s %s \n\n", progname, "-g -d <dbdirpath> -s <subject> -r <csr> \n"); exit(-1); } } /* * validate the options used for add cert to db command */ static void validateaddcerttodbcommand(const char *progname, const char *dbdir, const char *nicknamestr, const char *truststr, const char *certfilename, const char *certreqfilename, const char *issuernamestr, const char *serialnumberstr, prbool selfsign) { prbool validationfailed = pr_false; if (!nicknamestr) { pr_fprintf(pr_st...
...And 6 more matches
Guide to the Fullscreen API - Web APIs
activating full-screen mode given an element that you'd like to present in full-screen mode (such as a <video>, for example), you can present it in full-screen mode by simply calling its requestfullscreen() method. ...
...e trying to emulate webkit's behavior on gecko, you need to place the element you want to present inside another element, which you'll make fullscreen instead, and use css rules to adjust the inner element to match the appearance you want. notification when fullscreen mode is successfully engaged, the document which contains the element receives a fullscreenchange event. when fullscreen mode is exited, the document again receives a fullscreenchange event. note that the fullscreenchange event doesn't provide any information itself as to whether the document is entering or exiting fullscreen mode, but if the document has a non null fullscreenelement, you know you're in fullscreen mode. when a fullscreen request fails it's not guaranteed that you'll be able to switch into fullscreen mode. fo...
...ullscreenerror event. when a fullscreen request fails, firefox will log an error message to the web console explaining why the request failed. in chrome and newer versions of opera however, no such warning is generated. note: fullscreen requests need to be called from within an event handler or otherwise they will be denied. getting out of full screen mode the user always has the ability to exit fullscreen mode of their own accord; see things your users want to know. you can also do so programmatically by calling the document.exitfullscreen() method. other information the document provides some additional information that can be useful when developing fullscreen web applications: documentorshadowroot.fullscreenelement the fullscreenelement property tells you the element that's curr...
...And 6 more matches
Using microtasks in JavaScript with queueMicrotask() - Web APIs
this event loop may be either the browser's main event loop or the event loop driving a web worker. this lets the given function run without the risk of interfering with another script's execution, yet also ensures that the microtask runs before the user agent has the opportunity to react to actions taken by the microtask. ...
...the difference between microtasks and tasks seems minor. and they are similar; both are made up of javascript code which gets placed on a queue and run at an appropriate time. however, whereas the event loop runs only the tasks present on the queue when the iteration began, one after another, it handles the microtask queue very differently. there are two key differences. first, each time a task exits, the event loop checks to see if the task is returning control to other javascript code. if not, it runs all of the microtasks in the microtask queue. the microtask queue is, then, processed multiple times per iteration of the event loop, including after handling events and other callbacks. second, if a microtask adds more microtasks to the queue by calling queuemicrotask(), those newly-added m...
... queuemicrotask(() => { /* code to run in the microtask here */ }); the microtask function itself takes no parameters, and does not return a value. when to use microtasks in this section, we'll take a look at scenarios in which microtasks are particularly useful. generally, it's about capturing or checking results, or performing cleanup, after the main body of a javascript execution context exits, but before any event handlers, timeouts and intervals, or other callbacks are processed. when is that useful? the main reason to use microtasks is simply that: to ensure consistent ordering of tasks, even when results or data is available synchronously, but while simultaneously reducing the risk of user-discernible delays in operations. ensuring ordering on conditional use of promises one s...
...And 6 more matches
Looping code - Learn web development
cessive loop, until the condition is no longer true. we haven't explicitly illustrated this above, but we could think about the farmer being able to collect say 2 portions of food per hour. after each hour, the amount of food he has collected is incremented by two, and he checks whether he has enough food. ...
... food per hour. after each hour, the amount of food he has collected is incremented by two, and he checks whether he has enough food. if he has reached 10 portions (the point where the condition is no longer true, so the loop exits), he can stop collecting and go home. ...
...if not, the farmer spends an hour collecting two portions of food, and the loop runs again. ...
...And 5 more matches
Pointer Lock API - Web APIs
fullscreen api, extends dom elements by adding a new method, requestpointerlock(). ...
...k; canvas.requestpointerlock() if a user has exited pointer lock via the default unlock gesture, or pointer lock has not previously been entered for this document, an event generated as a result of an engagement gesture must be received by the document before requestpointerlock will succeed. (from https://w3c.github.io/pointerlock/#extensions-to-the-element-interface) pointerlockelement and exitpointerlock() the pointer lock api also extends the document interface, adding both a new property and a new method. the new property is used for accessing the currently locked element (if any), and is named pointerlockelement and the new method on document is exitpointerlock() and, as the name implies, it is used to exit the pointer lock. the pointerlockelement property is useful for determinin...
...pointer locked (e.g., for doing a boolean check) and also for obtaining a reference to the locked element, if any. ...
...And 5 more matches
NSS Tools modutil
password on a token creating database files this example creates a set of security management database files in the specified directory: modutil -create -dbdir c:\databases the security module database tool displays a warning: warning: performing this operation while communicator is running couldcause corruption of your security databases. if communicator iscurrently running, you should exit communicator before continuing thisoperation. type 'q <enter>' to abort, or <enter> to continue: after you press enter, the tool displays the following: creating "c:\databases\key3.db"...done.creating "c:\databases\cert8.db"...done.creating "c:\databases\secmod.db"...done. displaying module information this example gives detailed information about the specified module: modutil -list "ne...
...le makes the specified module a default provider for the rsa, dsa, and rc2 security mechanisms: modutil -default "cryptographic module" -dbdir c:\databases -mechanisms rsa:dsa:rc2 the security module database tool displays a warning: warning: performing this operation while communicator is running couldcause corruption of your security databases. if communicator iscurrently running, you should exit communicator before continuing thisoperation. type 'q <enter>' to abort, or <enter> to continue: after you press enter, the tool displays the following: using database directory c:\databases...successfully changed defaults. enabling a slot this example enables a particular slot in the specified module: modutil -enable "cryptographic module" -slot "cryptographic reader" -dbdir c:\database...
...ults. enabling a slot this example enables a particular slot in the specified module: modutil -enable "cryptographic module" -slot "cryptographic reader" -dbdir c:\databases the security module database tool displays a warning: warning: performing this operation while communicator is running couldcause corruption of your security databases. if communicator iscurrently running, you should exit communicator before continuing thisoperation. type 'q <enter>' to abort, or <enter> to continue: after you press enter, the tool displays the following: using database directory c:\databases...slot "cryptographic reader" enabled. enabling fips compliance this example enables fips 140-2 compliance in communicator's internal module: modutil -dbdir "c:\databases" -fips true the security m...
...And 4 more matches
Bytecode Descriptions
emoved from the stack except by jsop::moreiter and jsop::enditer, or by error handling. the script's jsscript::trynotes() must mark the body of the for-in loop, i.e. exactly those instructions that begin executing with iter on the stack, starting with the next instruction (always jsop::loophead). ...
...p, i.e. exactly those instructions that begin executing with iter on the stack, starting with the next instruction (always jsop::loophead). code must not jump into or out of this region: control can enter only by executing jsop::iter and can exit only by executing a jsop::enditer or by exception unwinding. (a jsop::enditer is always emitted at the end of the loop, and extra copies are emitted on "exit slides", where a break, continue, or return statement exits the loop.) typically a single try note entry marks the contiguous chunk of bytecode from the instruction after jsop::iter to jsop::enditer (inclusive); but if that range contains any instructions on exit slides, after a jsop::enditer, then those must be correctly noted as outside the loop. format: jof_ic moreiter stack: iter ⇒ iter,...
...ate over. the magic value must be used only by jsop::isnoiter and jsop::enditer. isnoiter stack: val ⇒ val, done test whether the value on top of the stack is magicvalue(js_no_iter_value) and push the boolean result. iternext stack: val ⇒ val no-op instruction to hint to ionbuilder that the value on top of the stack is the string key in a for-in loop. enditer stack: iter, iterval ⇒ exit a for-in loop, closing the iterator. iter must be a propertyiteratorobject pushed by jsop::iter. iteration checkisobj operands: (checkisobjectkind kind) stack: result ⇒ result check that the top value on the stack is an object, and throw a typeerror if not. kind is used only to generate an appropriate error message. implements: getiterator step 5, iteratornext step 3. both operations call ...
...And 4 more matches
Tracing JIT
xecution. the monitor then calls into the native code of the trace, passing in a pointer to the state structure as the sole argument. the native code of the trace runs, modifying the state structure and native stack, as well as calling native spidermonkey c functions, and reading from and writing to objects in the spidermonkey heap. the native code returns a pointer to a structure called a side exit. the monitor inspects the side exit and, depending on the exit condition, reconstructs a certain number of interpreter frames and flushes a certain set of writes back to the spidermonkey heap. frame reconstruction is necessary because a trace may inline a number of function calls, and may exit before those function calls return. write flushing is necessary because all writes to imported values i...
...epending on the exit condition, reconstructs a certain number of interpreter frames and flushes a certain set of writes back to the spidermonkey heap. frame reconstruction is necessary because a trace may inline a number of function calls, and may exit before those function calls return. write flushing is necessary because all writes to imported values in the native stack are deferred until trace-exit, as an optimization. if the side exit condition indicates that the trace exited successfully -- simply running out of native code or hitting a branch condition that no native code yet exists to handle -- the monitor will inspect the hit count for the trace-exiting pc. if that pc has itself grown hot, the monitor will immediately transition to recording mode starting with the exiting pc. otherwis...
...indicates that the trace exited successfully -- simply running out of native code or hitting a branch condition that no native code yet exists to handle -- the monitor will inspect the hit count for the trace-exiting pc. if that pc has itself grown hot, the monitor will immediately transition to recording mode starting with the exiting pc. otherwise it will return to monitoring mode. if the side exit condition indicates that the trace exited unsuccessfully -- due to encountering sufficient memory pressure to trigger a garbage collection, running out of native stack space, expiring a timer or any similar abnormal condition -- the monitor returns to monitoring mode. some other terminology may be helpful when reading the code: the term guard denotes a condition that is checked by an executi...
...And 4 more matches
NSPR's Position On Abrupt Thread Termination
this memo describes my position on a facility that is currently under discussion for inclusion in the netscape portable runtime (nspr); the ability of a thread to abruptly exit. i resist including this function in nspr because it results in bad programming practice and unsupportable programs. threads are not processes. abrupt termination has been available in the unix/c environment for some time (exit()), and i assume that the basic semantics defined there are applicable here. in that environment, exit() may be called and any time, and results in the calling thread's immediate termination. in the situation where it was defined (unix), which has only a single thread of execution, that is equivalent to terminating the process. the process abstraction is then responsible for closing al...
...all open files and reclaiming all storage that may have been allocated during the process' lifetime. this practice does not extend to threads. threads run within the confines of a process (or similar abstractions in other environments). threads are lightweight because they do not maintain the full protection domain provided by a process. ...
...ractice does not extend to threads. threads run within the confines of a process (or similar abstractions in other environments). threads are lightweight because they do not maintain the full protection domain provided by a process. so in a threaded environment, what is the parallel to unix' exit()? nspr has defined a function, callable by any thread within a process at any time, called pr_processexit(). this is identical to unix exit() and was so named in an effort to make the obvious even more so. when called, the process exits, closing files and reclaiming the process' storage. certain people have been disappointed when nspr did not provide a functional equivalent to exit just a particular thread. apparently they have failed to consider the ramifications. if a thread was to abruptly termina...
...And 3 more matches
Creating JavaScript jstest reftests
'); } reportcompare(0, 0, 'ok'); handling abnormal test terminations some tests can terminate abnormally even though the test has technically passed. earlier we discussed the deprecated approach of using the -n naming scheme to identify tests whose passed, failed status is flipped by the post test processing code in jsdriver.pl and post-process-logs.pl. ...
...ortcompare(0, 0, 'ok'); handling abnormal test terminations some tests can terminate abnormally even though the test has technically passed. earlier we discussed the deprecated approach of using the -n naming scheme to identify tests whose passed, failed status is flipped by the post test processing code in jsdriver.pl and post-process-logs.pl. ...
...inate abnormally even though the test has technically passed. earlier we discussed the deprecated approach of using the -n naming scheme to identify tests whose passed, failed status is flipped by the post test processing code in jsdriver.pl and post-process-logs.pl. a different approach is to use the expectexitcode(exitcode) function which outputs a string: --- note: in this testcase, we expect exit code <exitcode> --- that tells the post-processing scripts jsdriver.pl or post-process-logs.pl that the test passes if the shell or browser terminates with that exit code. multiple calls to expectexitcode will tell the post-processing scripts that the test actually passed if any of the exit codes are found when the test terminates. this approach has limited use, however. in the javascript shell...
...And 3 more matches
LIR - Archive of obsolete content
48 not in use immediate 49 immi in...
... 48 not in use immediate 49 immi int immediate 50 immq 64 bi...
... 48 not in use immediate 49 immi int immediate 50 immq 64 bit quad immediate 51 immd ...
...And 2 more matches
HTTP logging
bile, etc. in that case you can set environment variables *before* you launch firefox. note that this approach winds up logging the whole browser history, so files can get rather large (they compress well :) setting environment variables differs by operating system. don't let the scary-looking command line stuff frighten you off; it's not hard at all! windows if firefox is already running, exit out of it. open a command prompt. on windows xp, you can find the "run..." command in the start menu's "all programs" submenu. on all newer versions of windows, you can hold down the windows key and press "r". type cmd and press enter, a new command prompt window with a black background will appear. copy and paste the following lines one at a time into the command prompt window. press the ente...
...nsport:5,nshostresolver:5,cookie:5 set moz_log_file=%temp%\log.txt "c:\program files (x86)\mozilla firefox\firefox.exe" (these instructions assume that you installed firefox to the default location, and that drive c: is your windows startup disk. make the appropriate adjustments if those aren't the case.) reproduce whatever problem it is that you're having. once you've reproduced the problem, exit firefox and look for the generated log files in your temporary directory. you can type "%temp%" directly into the windows explorer location bar to get there quickly. linux this section offers information on how to capture http logs for firefox running on linux. quit out of firefox if it's running. open a new shell. the commands listed here assume a bash-compatible shell. copy and paste th...
...isted here assume a bash-compatible shell. copy and paste the following commands into the shell one at a time. make sure to hit enter after each line. export moz_log=timestamp,rotate:200,nshttp:5,cache2:5,nssockettransport:5,nshostresolver:5,cookie:5 export moz_log_file=/tmp/log.txt cd /path/to/firefox ./firefox reproduce the problem you're debugging. when the problem has been reproduced, exit firefox and look for the generated log files, which you can find at /tmp/log.txt. mac os x these instructions show how to log http traffic in firefox on mac os x. quit firefox is if it's currently running, by using the quit option in the file menu. keep in mind that simply closing all windows does not quit firefox on mac os x (this is standard practice for mac applications). run the termin...
...And 2 more matches
NSS Sample Code Sample_1_Hashing
, "%02x:", data[i]); column += 3; } else { pr_fprintf(out, "%02x", data[i]); column += 2; break; } if (column > 76 || (i % 16 == limit)) { newline(out); column = level; limit = i % 16; } } if (column != level) { newline(out); } } /* * prints a usage message and exits */ static void usage(const char *progname) { int htype; int hash_algtotal = sizeof(hash_names) / sizeof(hash_names[0]); fprintf(stderr, "usage: %s -t type [ < input ] [ > output ]\n", progname); fprintf(stderr, "%-20s specify the digest method (must be one of\n", "-t type"); fprintf(stderr, "%-20s ", ""); for (htype = 0; htype < hash_algtotal; htype++) { ...
... * it writes out the digest as a hexadecimal strin...
... * it writes out the digest as a hexadecimal string. */ static int digestfile(prfiledesc *outfile, prfiledesc *infile, secoidta...
...And 2 more matches
Hashing - sample 1
"%02x:", data[i]); column += 3; } else { pr_fprintf(out, "%02x", data[i]); column += 2; break; } if (column > 76 || (i % 16 == limit)) { newline(out); column = level; limit = i % 16; } } if (column != level) { newline(out); } } /* * prints a usage message and exits */ static void usage(const char *progname) { int htype; int hash_algtotal = sizeof(hash_names) / sizeof(hash_names[0]); fprintf(stderr, "usage: %s -t type [ < input ] [ > output ]\n", progname); fprintf(stderr, "%-20s specify the digest method (must be one of\n", "-t type"); fprintf(stderr, "%-20s ", ""); for (htype = 0; htype < hash_algtotal; htype++) { ...
... * it writes out the digest as a hexadecimal strin...
... * it writes out the digest as a hexadecimal string. */ static int digestfile(prfiledesc *outfile, prfiledesc *infile, secoidta...
...And 2 more matches
sample1
i]); column += 3; } else { pr_fprintf(out, "%02x", data[i]); column += 2; break; } if (column > 76 || (i % 16 == limit)) { newline(out); column = level; limit = i % 16; } } if (column != level) { newline(out); } } /* prints a usage message and exits */ static void usage(const char *progname) { int htype; int hash_algtotal = sizeof(hash_names) / sizeof(hash_names[0]); fprintf(stderr, "usage: %s -t type [ < input ] [ > output ]\n", progname); fprintf(stderr, "%-20s specify the digest method (must be one of\n", "-t type"); fprintf(stderr, "%-20s ", ""); for (htype = 0; htype < hash_algtotal; hty...
... * it writes out the digest as a hexadeci...
... * it writes out the digest as a hexadecimal string. */ static int digestfile(prfiledesc *outfile, prfiledesc *infile,...
...And 2 more matches
How to embed the JavaScript engine
argv[]) { jsruntime *rt = js_newruntime(8l * 1024 * 1024, js_use_helper_threads); if (!rt) return 1; jscontext *cx = js_newcontext(rt, 8192); if (!cx) return 1; { // scope for our various stack objects (jsautorequest, rootedobject), so they all go // out of scope before we js_destroycontext. ...
..._init(); jsruntime *rt = js_newruntime(8l * 1024 * 1024, js_use_helper_threads); if (!rt) return 1; jscontext *cx = js_newcontext(rt, 8192); if (!cx) return 1; { // scope for our various stack objects (jsautorequest, rootedobject), so they all go // out of scope before we js_destroycontext. ...
... char *argv[]) { js_init(); jsruntime *rt = js_newruntime(8l * 1024 * 1024); if (!rt) return 1; jscontext *cx = js_newcontext(rt, 8192); if (!cx) return 1; { // scope for our various stack objects (jsautorequest, rootedobject), so they all go // out of scope before we js_destroycontext. ...
...And 2 more matches
Secure Development Guidelines
51615 int vuln_funct(int size) { char buf[1024]; if (size > sizeof(buf) - 1) return -1; } signedness issues: don’t mix signed and unsigned integers use unsigned integers for sizes, offsets, and indexes casting and truncation example: void vuln_funct() { u_int32_t size1 = 0xffffffff; u_int16_t size2 = size1; void *ptr = malloc(size2); if (!ptr) exit(exit_failure); memcpy(ptr, user_data, size1); } casting issues: sign extension example: int main() { int32_t new_size = 0; int8_t size = 0xff; new_size = size; printf("0x%08x\r\n", new_size); } casting issues: sign extension prevention be careful with signed integers use unsigned integers for sizes, offsets, and indexes denial of service: divide by zero...
...do stuff ... free(ptr); ptr = null; } race conditions previous example is vulnerable to a signal race condition what would happen if the application received a signal in the middle of free(ptr)? it would lead to a double free race conditions: pre...
...do stuff ... ...
...And 2 more matches
nsIProcess
read only. isrunning boolean true if the process is running, otherwise false. only accurate if the process was run with blocking disabled. read only. location nsifile the location of the executable file on disk. read only. gecko 1.9.1 note thi...
...read only. ...
...read only. isrunning boolean true if the process is running, otherwise false. ...
...And 2 more matches
GlobalEventHandlers.ondragend - Web APIs
function dragleave_handler(ev) { console.log("dragleave"); // change the source element's border back to white ev.currenttarget.style.background = "white"; } function dragend_handler(ev) { console.log("dragend"); // change the target element's background color to visually indicate // the drag ended. ...
...onsole.log("dragleave"); // change the source element's border back to white ev.currenttarget.style.background = "white"; } function dragend_handler(ev) { console.log("dragend"); // change the target element's background color to visually indicate // the drag ended. ...
... ev.currenttarget.style.background = "white"; } function dragend_handler(ev) { console.log("dragend"); // change the target element's background color to visually indicate // the drag ended. ...
...And 2 more matches
GlobalEventHandlers.ondragenter - Web APIs
function dragleave_handler(ev) { console.log("dragleave"); // change the source element's border back to white ev.currenttarget.style.background = "white"; } function dragend_handler(ev) { console.log("dragend"); // change the target element's background color to visually indicate // the drag ended. ...
...onsole.log("dragleave"); // change the source element's border back to white ev.currenttarget.style.background = "white"; } function dragend_handler(ev) { console.log("dragend"); // change the target element's background color to visually indicate // the drag ended. ...
... ev.currenttarget.style.background = "white"; } function dragend_handler(ev) { console.log("dragend"); // change the target element's background color to visually indicate // the drag ended. ...
...And 2 more matches
GlobalEventHandlers.ondragleave - Web APIs
dragleave_handler(ev) { console.log("dragleave"); // change the source element's background color back to white ev.currenttarget.style.background = "white"; } function dragend_handler(ev) { console.log("dragend"); // change the target element's background color to visually indicate // the drag ended. ...
...("dragleave"); // change the source element's background color back to white ev.currenttarget.style.background = "white"; } function dragend_handler(ev) { console.log("dragend"); // change the target element's background color to visually indicate // the drag ended. ...
...ttarget.style.background = "white"; } function dragend_handler(ev) { console.log("dragend"); // change the target element's background color to visually indicate // the drag ended. ...
...And 2 more matches
Supporting per-window private browsing - Archive of obsolete content
of a real privacy context. however, this can lead to privacy leaks (such as cache and download entries) if not used carefully. clearing any temporarily-stored private data it is permissable to store private data in non-persistent ways for the duration of a private browsing session. ...
...of a private browsing session. to be notified when such a session ends (i.e., when the last private window is closed), observe the last-pb-context-exited notification. ...
...rfaces.nsiobserverservice); os.addobserver(pbobserver, "last-pb-context-exited", false); preventing a private session from ending if there are unfinished transactions involving private data, where the transactions will be terminated by the ending of a private session, an add-on can vote to prevent the session from ending (prompting the user is recommended). to do this, observe the last-pb-context-exiting notification and set the data field of the nsisupportsprbool subject to true. var os = components.classes["@mozilla.org/observer-service;1"] .getservice(components.interfaces.nsiobserverservice); os.addobserver(function (asubject, atopic, adata) { asubject.queryinterface(components.interfaces.nsisupportsprbool); // if another extension has not already canceled enteri...
...however, sometimes you need to adjust the privacy status on a channel manually, for example, if you have created the channel directly yourself. you can use the nsiprivatebrowsingchannel interface for this p...
Supporting private browsing mode - Archive of obsolete content
{ // ignore exceptions in older versions of firefox } }, observe : function (asubject, atopic, adata) { if (atopic == "private-browsing") { if (adata == "enter") { this._inprivatebrowsing = true; if (this.watcher && "onenterprivatebrowsing" in this._watcher) { this.watcher.onenterprivatebrowsing(); } } else if (adata == "exit") { this._inprivatebrowsing = false; if (this.watcher && "onexitprivatebrowsing" in this._watcher) { this.watcher.onexitprivatebrowsing(); } } } else if (atopic == "quit-application") { this._os.removeobserver(this, "quit-application"); this._os.removeobserver(this, "private-browsing"); } }, get inprivatebrowsing() { ...
...ivate browsing mode! } in addition, you can install watcher functions to be called when private browsing turns on and off, as shown in the following example. this lets you passively monitor for changes in private browsing status. var listener = new privatebrowsinglistener(); listener.watcher = { onenterprivatebrowsing : function() { // we have just entered private browsing mode! }, onexitprivatebrowsing : function() { // we have just left private browsing mode! } }; canceling shutting off private browsing mode extensions can prevent private browsing mode from being shut off. an extension might wish to do this if it's currently in the middle of an operation that prevents safely turning off private browsing (such as a database update operation, for example). to do this, sim...
...g shutting off private browsing mode extensions can prevent private browsing mode from being shut off. an extension might wish to do this if it's currently in the middle of an operation that prevents safely turning off private browsing (such as a database update operation, for example). ...
...ion, like this: var os = components.classes["@mozilla.org/observer-service;1"] .getservice(components.interfaces.nsiobserverservice); os.addobserver(function (asubject, atopic, adata) { asubject.queryinterface(components.interfaces.nsisupportsprbool); // if another extension has not already canceled entering the private mode if (!asubject.data) { if (adata == "exit") { // if we are leaving the private mode /* you should display some user interface here */ asubject.data = true; // cancel the operation } } }, "private-browsing-cancel-vote", false); note: a well-mannered extension should display some sort of user interface to indicate that private browsing mode will be kept on, and possibly offer the option to cancel whatever opera...
Componentizing our Svelte app - Learn web development
can save or cancel the changes. when it's not in editing mode, the user can delete the todo, edit it, or toggle its status between completed and active. ...
...ive. ...
...remove the markup in the {:else} part of the dom and replace it with the markup in the {#if...} section. the <input>'s value property will be bound to the name variable, and the buttons to cancel and save the changes call oncancel() and onsave() respectively (we added those functions earlier): when oncancel() is invoked, name is restored to its original value (when passed in as a prop) and we exit editing mode (by setting editing to false). when onsave() in invoked, we run the update() function — passing it the modified name — and exit editing mode. we also disable the save button when the <input> is empty, using the disabled={!name} attribute, and allow the user to cancel the edit using the escape key, like this: on:keydown={e => e.key === 'escape' && oncancel()}. we also use tod...
...> </button> <button type="button" class="btn btn__danger" on:click={onremove}> delete<span class="visually-hidden"> {todo.name}</span> </button> </div> {/if} </div> note: we could further split this into two different components, one for editing the todo and the other for displaying it. in the end, it boils down to how comfortable you feel dealing with this level of complexity in a single component. you should also consider whether splitting it further would enable reusing this component in a different context. to get the update functionality working, we have to handle the update event from the todos component. in its <script> section, add this handler: function updatetodo(todo) { const i = todos.findindex(t => t.id === todo.id) todos[i] = { ...todos[i...
JSAPI User Guide
global object. a minimal example each of the three key elements described in the previous section requires a few jsapi calls: the runtime: use js_newruntime to create it and js_destroyruntime to clean it up when you're done. when your application is done with spidermonkey altogether, use js_shutdown to free any remaining cached resources. (this is a mere nicety if the process is about to exit anyway. but as that is not always the case, calling js_shutdown is a good habit to get into.) the context: use js_newcontext and js_destroycontext. for maximum ecmascript standard compliance, applications should also use js_setoptions to enable jsoption_varobjfix. to get the latest javascript language features, applications may use js_setversion. error reporting is also per-context and is e...
... application callback, the callback must not throw a c++ exception. throwing and catching exceptions we have already seen one example of how to throw an exception from a jsnative function. simply call js_reporterror, with printf-style arguments, and return false. rc = system(cmd); if (rc != 0) { /* throw a javascript exception. */ js_reporterror(cx, "command failed with exit code %d", rc); return false; } this is very much like the javascript statement throw new error("command failed with exit code " + rc);. again, note that calling js_reporterror does not cause a c++ exception to be thrown. it only creates a new javascript error object and stores it in the context as the current pending exception. the application must also return false. once the c++ f...
...function to be called whenever a javascript function is about to be called, or has finished executing: void functransition(const jsfunction *func, const jsscript *scr, const jscontext *const_cx, jsbool entering) { jscontext *cx = const_cast<jscontext*>(const_cx); jsstring *name = js_getfunctionid((jsfunction*)func); const char *entexit; const char *namestr; /* build a c string for the function's name */ if (!name) { namestr = "unnamed function"; } else { namestr = js_encodestring(cx, name); } /* build a string for whether we're entering or exiting */ if (entering) { entexit = "entering"; } else { entexit = "exiting"; } /* output information about the trace */ printf("%s javascript fun...
.../* build a c string for the function's name */ if (!name) { namestr = "unnamed function"; } else { namestr = js_encodestring(cx, name); } /* build a string for whether we're entering or exiting */ if (entering) { entexit = "entering"; } else { entexit = "exiting"; } /* output information about the trace */ printf("%s javascript function: %s at time: %ld", entexit, namestr, clock()); } void enabletracing(jscontext *cx) { js_setfunctioncallback(cx, functransition); } void disabletracing(jscontext *cx) { js_setfunctioncallback(cx, nullptr); } ...
JS_SetFunctionCallback
this lets you trace the execution of code, and is particularly useful for javascript tracers and profilers since it works across all run modes (interpreter, method jit, trace jit). using this function may have a significant performance impact. see function tracing for an example. ...
...id js_setfunctioncallback(jscontext *cx, jsfunctioncallback fcb); name type description cx jscontext * pointer to a js context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. fcb jsfunctioncallback the callback to execute when javascript functions are invoked and exited. specify null to stop calling the current callback. the callback must not modify the current state of execution. the call stack cannot be relied upon, because this callback may be invoked from the jit code when the stack frame and context are in an indeterminate state. description js_setfunctioncallback sets a c function to be called each time a javascript function is invoked or exits. ...
... see also mxr id search for js_setfunctioncallback function tracing js_getfunctioncal...
... type description fun const jsfunction * the javascript function being invoked or exited. scr const jsscript * the script being executed. cx jscontext * the javascript context in which the script is being run. entering int true if the callback is being called because the specified function is being invoked or false if the function is exiting. see also mxr id search for js_setfunctioncallback function tracing js_getfunctioncallback bug 1103269 ...
nsIAppStartup
upstate(in long awindowwidth, in long awindowheight); obsolete since gecko 1.9.1 void destroyhiddenwindow(); void doprofilestartup(in nsicmdlineservice acmdlineservice, in boolean caninteract); obsolete since gecko 1.9.1 void ensure1window(in nsicmdlineservice acmdlineservice); obsolete since gecko 1.9.1 void enterlastwindowclosingsurvivalarea(); void exitlastwindowclosingsurvivalarea(); void getstartupinfo(); void hidesplashscreen(); obsolete since gecko 1.9.1 void initialize(in nsisupports nativeappsupportorsplashscreen); obsolete since gecko 1.9.1 void quit(in pruint32 amode); void restartinsafemode(in pruint32 aquitmode); void run(); attributes attribute type descript...
...service ); parameters acmdlineservice the command line from which startup args can be read. enterlastwindowclosingsurvivalarea() serves for situations when all application windows will be closed but we don't want to take this as a signal to quit the application. bracket the code where the last window could close with these. void enterlastwindowclosingsurvivalarea(); parameters none. exitlastwindowclosingsurvivalarea() this method serves for situations when all application windows will be closed but we don't want to take this as a signal to quit the application. bracket the code where the last window could close with these. void exitlastwindowclosingsurvivalarea(); parameters none. getstartupinfo() returns a javascript object with events from startup and the timestamps indi...
...alize() obsolete since gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) required initialization routine. void initialize( in nsisupports nativeappsupportorsplashscreen ); parameters nativeappsupportorsplashscreen is an object that can be qi'd to either an nsinativeappsupport or nsisplashscreen; this object will be used to implement hidesplashscreen. quit() exit the event loop, and shut down the application. void quit( in pruint32 amode ); parameters amode this parameter modifies how the application is shutdown, and it is constructed from the constants defined above. restartinsafemode() restart the application in safe mode. void quit( in pruint32 aquitmode ); parameters aquitmode this parameter modifies how the app is shutdown. run...
...startinsafemode() restart the application in safe mode. void quit( in pruint32 aquitmode ); parameters aquitmode this parameter modifies how the app is shutdown. run() runs an application event loop: normally the main event pump which defines the lifetime of the application. if there are no windows open and no outstanding calls to enterlastwindowclosingsurvivalarea() this method will exit immediately. void run(); parameters none. return value returns ns_success_restart_app code. this return code indicates that the application should be restarted because quit was called with the erestart flag. see also nsicmdlineservice nsiappstartup_mozilla_2_0 ...
In depth: Microtasks and the JavaScript runtime environment - Web APIs
tion. each function is run within its own execution context. this is frequently referred to as a "local context." using the ill-advised eval() function also creates a new execution context. each context is, in essence, a level of scope within your code. as one of these code segments begins execution, a new context is constructed in which to run it; that context is then destroyed when the code exits. consider the javascript program below: let outputelem = document.getelementbyid("output"); let userlanguages = { "mike": "en", "teresa": "es" }; function greetuser(user) { function localgreeting(user) { let greeting; let language = userlanguages[user]; switch(language) { case "es": greeting = `¡hola, ${user}!`; break; case "en": default: ...
... break; } return greeting; } outputelem.innerhtml += localgreeting(user) + "<br>\r"; } greetuser("mike"); greetuser("teresa"); greetuser("veronica"); this short program contains three execution contexts, some of which are created and destroyed several times over the course of the program's execution. as each context is created, it is placed on the execution context stack. when it exits, the context is removed from the context stack. upon starting the program, the global context is created. when greetuser("mike") is reached, a context is created for the greetuser() function; this execution context is pushed onto the execution context stack. when greetuser() calls localgreeting(), another context is created to run that function. when this function returns, th...
...eached, a context is created for it and pushed onto the stack. when greetuser() calls localgreeting(), another context is created to run that function. when this function returns, the context for localgreeting() is removed from the execution stack and destroyed. the greetuser() function returns and its context is removed from the stack and destroyed. the main program exits and its execution context is removed from the execution stack; as there are no contexts remaining on the stack, program execution ends. using execution contexts in this manner, each program and function is able to have its own set of variables and other objects. each context additionally tracks the next line in the program that should be run and other information critical to that context's ope...
...task by using settimeout() or setinterval(). the difference between the task queue and the microtask queue is simple but very important: when executing tasks from the task queue, the runtime executes each task that is in the queue at the moment a new iteration of the event loop begins. tasks added to the queue after the iteration begins will not run until the next iteration. each time a task exits, and the execution context stack is empty, each microtask in the microtask queue is executed, one after another. the difference is that execution of microtasks continues until the queue is empty—even if new ones are scheduled in the interim. in other words, microtasks can enqueue new microtasks and those new microtasks will execute before the next task begins to run, and before the end of the ...
Key Values - Web APIs
cancel key. gdk_key_cancel (0xff69) "contextmenu" [3] shows the context menu. typically found between the windows (or os) key and the control key on the right side of the keyboard. vk_apps (0x5d) kvk_pc_contextmenu (0x6e) gdk_key_menu (0xff67) qt::key_menu (0x01000055) keycode_menu (82) "escape" [2] the esc (escape) key. typically used as an exit, cancel, or "escape this operation" button. historically, the escape character was used to signal the start of a special control sequence of characters called an "escape sequence." vk_escape (0x1b) kvk_escape (0x35) gdk_key_escape (0xff1b) qt::key_escape (0x01000000) keycode_escape (111) "execute" the execute key. vk_execute (0x2b) qt::key_execute (0x01020003...
... keycode_notification (83) "mannermode" a button which cycles among the notification modes: silent, vibrate, ring, and so forth. keycode_manner_mode (205) "voicedial" the voice dial key. initiates voice dialing. qt::key_voicedial (0x01100008) keycode_voice_assist (231) [1] prior to firefox 37, the home button generated a key code of "exit". starting in firefox 37, the button generates the key code "mozhomescreen". multimedia keys the multimedia keys are extra buttons or keys for controlling media devices, found on some keyboards. keyboardevent.key value description virtual keycode windows mac linux android "channeldown" switches to the previous channel. appcommand_media_channel_do...
... adjusts the brightness of the device by toggling between two brightness levels or by cycling among multiple brightness levels. vk_dimmer gdk_key_brightnessadjust (0x1008ff3b) "displayswap" cycles among video sources. vk_display_swap "dvr" switches the input source to the digital video recorder (dvr). keycode_dvr (173) "exit" the exit button, which exits the curreent application or menu. vk_exit qt::key_exit (0x0102000a) "favoriteclear0" clears the program or content stored in the first favorites list slot. vk_clear_favorite_0 "favoriteclear1" clears the program or content stored in the second favorites list slot. vk_clear_favorite_1 "fav...
...fied" on firefox. document keys these keys control documents. in the specification, they're included in other sets of keys (such as the media keys), but they are more sensibly considered to be their own category. keyboardevent.key value description virtual keycode windows mac linux android "close" [1] closes the current document or message. must not exit the application. appcommand_close gdk_key_close (0x1008ff56) qt::key_close (0x010000ce) keycode_media_close (128) "new" [1] creates a new document or message. appcommand_new gdk_key_new (0x1008ff68) qt::key_new (0x01000120) "open" [1] opens an existing document or message. appcommand_open gdk_key_open (0x1008ff6b) qt::key_op...
MouseEvent.relatedTarget - Web APIs
the mouseevent.relatedtarget read-only property is the secondary target for the mouse event, if there is one. ...
... the mouseevent.relatedtarget read-only property is the secondary target for the mouse event, if there is one. ...
...arget for the mouse event, if there is one. ...
... the eventtarget the pointing device exited from mouseleave the eventtarget the pointing device exited from the eventtarget the pointing device entered to mouseout the eventtarget the pointing device exited from the eventtarget the pointing device entered to mouseover the eventtarget the pointing device entered to the eventtarget the pointing device exited from dragenter the eventtarget the pointing device entered to the eventtarget the pointing device exited from dragexit the eventtarget the pointing device exited from the eventtarget the pointing device entered to for events with no secondary target, relatedtarget returns null. focusevent.relatedtarget is a similar property for focus events. syntax var ta...
Movement, orientation, and motion: A WebXR example - Web APIs
of the key matrices for informational purposes while our scene is running. then we look to see if navigator.xr is defined. if it isn't—and/or the enableforcepolyfill configuration constant is set to true—we install the webxr polyfill by instantiating the webxrpolyfill class. handling the startup and shutdown ui then we call the setupxrbutton() function, which handles configuring the "enter/exit webxr" button to enable or disable it as necessary depending on the availability of webxr support for the session type specified in the session_type constant. function setupxrbutton() { if (navigator.xr.issessionsupported) { navigator.xr.issessionsupported(session_type) .then((supported) => { xrbutton.disabled = !supported; }); } else { navigator.xr.supportssession(sess...
...(() => { xrbutton.disabled = false; }) .catch(() => { xrbutton.disabled = true; }); } } the label of the button gets adjusted in the code that handles actuallys ttarting and stopping the webxr session; we'll see that below. the webxr session is toggled on and off by the handler for click events on the button, whose label is appropriately set to either "enter webxr" or "exit webxr". this is done by the onxrbuttonclick() event handler. async function onxrbuttonclick(event) { if (!xrsession) { navigator.xr.requestsession(session_type) .then(sessionstarted); } else { await xrsession.end(); if (xrsession) { sessionended(); } } } this begins by looking at the value of xrsession to see if we already have a xrsession object representing an...
...arting the session, by setting up event handlers, compiling and installing the glsl code for the vertex and fragment shaders, and attaching the webgl layer to the webxr session before kicking off the rendering loop. it gets called as the handler for the promise returned by issessionsupported(). ...
... then we get a reference to the <canvas> found in our html—as well as its webgl rendering context—which will be used as the drawing surface for the scene. the xrcompatible property is requested when calling getcontext() on the element to gain ...
MCD, Mission Control Desktop, AKA AutoConfig - Archive of obsolete content
ail & cn), this will finally call processldapvalues, "3)" just above. // go through the ldap replicas list for(i = 0; i < ldap_servers.length; i ++) { // search for attribute mail & cn through ldap servers where uid = $user|$username getldapattributes(ldap_servers[i], "ou=people,dc=int-evry,dc=fr", "uid=" + env_user, "uid,cn,mail"); // if we catch a running ldap server, exit the loop, if(ldap_values) { running_ldap_server = ldap_servers[i]; // if $mozilla_debug=1 display in a popup the running server if (env_mozdebug) { displayerror("getldapattributes: debug 2 running_ldap_server: " + running_ldap_server); } break; } } unique script for windows and linux an if... else test permits us to check whether we use a lin...
...ail & cn), this will finally call processldapvalues, "3)" just above. ...
...tion to redirect // netscape.cfg to read the plain-text "config-file-unix.jsc" file. // any changes // from now on can be made here w/o re-encoding the netscape.jsc file to // netscape.cfg. config( "autoadmin.global_config_url", \ "http://lugdunum.int-evry.fr/browser/config-file-unix.jsc" ); // how often (in minutes) to update // every 6 hours seems a good interval to keep hosts who don't ever // exit netscape updated on current changes. config( "autoadmin.refresh_interval", 360 ); // since we use a file, if it's not accessible, something is // terribly wrong anyway config( "autoadmin.failover_to_cached", false ); // don't use ?useremail=email-addr to cgi url request config( "autoadmin.append_emailaddr", false ); lockpref configuration file this file (on the web server: http://www/browser/c...
Drag and Drop JavaScript Wrapper - Archive of obsolete content
eate soon. in this case we only do anything special when the button drag is started. if we wanted to handle the other cases also, we can call the other functions, as in the following example: <description value="click and drag this text." ondraggesture="nsdraganddrop.startdrag(event,textobserver)" ondragover="nsdraganddrop.dragover(event,textobserver)" ondragexit="nsdraganddrop.dragexit(event,textobserver)" ondragdrop="nsdraganddrop.drop(event,textobserver)" /> as mentioned earlier, there is nothing special that happens during a dragenter event, so you can just write that yourself. the functions are implemented by the nsdraganddrop object, which is declared in the file nsdraganddrop.js, which was included in one of the script tags. they hand...
...event, flavor, session) this function should be defined when you want something to happen when an element is dragged over. the first argument is the event object, the second is the flavor of the data and the third is a drag session object which provides more details about the drag that is occurring. you should define this function for elements that allow dragged data to be dropped on them. ondragexit(event, session) this function should be defined when something should happen on a drag exit. it has two arguments, the event object and the drag session. ondrop(event, dropdata, session) this function should be defined when you want something to happen when an object is dropped. the first argument is the event object and the second is the data being dragged. the third argument is the drag sessi...
... function takes no arguments. this function is necessary so that the wrapper can determine the best flavour to pass to the other functions. for an observer that is observing an element that can start a drag, you should define at least the ondragstart function. for elements that can have objects dropped on them, you should define ondragover, ondrop and getsupportedflavours (and, if desired, ondragexit). the type of data being dragged is stored as a set of flavors. often, a dragged object will be available in a number of flavors. that way, a drop target can accept the flavor it finds most suitable. for example, a file may come in two flavors, the file itself and the text name of the file. if the file is dragged and dropped onto a directory, the file flavor will be used. if the file is dropped o...
Layout System Overview - Archive of obsolete content
tation to a printer, or even an aural presentation to a speech-synthesizer. to date the only real use of this multiple presentation ability is seen in printing, where multiple presentations are managed, all connected to the same content model. (note: it is unclear if this is really a benefit - it may have been better to use a copy of the content model for each presentation, and to remove the complexity of managing separate presentations - analysis is needed here). the idea of supporting a non-visual presentation is interesting. layout's support for aural presentations is undeveloped, though conceptually, it is possible and supported by the architecture. how layout does its job: frames and reflow so, layout is concerned with providing a presentation, in galley or paged mode. given a content mod...
...y the geometry of the elements that precede it, or in any case, is influenced more locally. the in-flow case is considered the 'normal' case, and corresponds to normal html formatting. the later case, called 'out of flow' puts the document author in control of the layout, and the author must specify the locations and sizes of all of the elements that are positioned. there is, of course, some complexity involved with managing these two models simultaneously... so far the general flow of layout looks like this: obtain a document's content model utilize the style system to resolve the style of each element in the content model construct the frames that correspond to the content model, according to the resolved style data. perform the initial layout, or initial reflow, on the newly constructed fr...
... presentational elements from other layout systems, it can be adapted using a frame-based adapter, ala xul. core classes at the highest level, the layout system is a group of classes that manages the presentation within a fixed width and either unlimited height (galley presentation) or discrete page heights (paged presentation). digging just a tiny bit deeper into the system we find that the complexity (and interest) mushrooms very rapidly. the idea of formatting text and graphics to fit within a given screen area sounds simple, but the interaction of in-flow and out-of-flow elements, the considerations of incremental page rendering, and the performance concerns of dynamic content changes makes for a system that has a lot of work to do, and a lot of data to manage. here are the high-level clas...
Actionscript Acceptance Tests - Archive of obsolete content
e http://docs.python.org/library/time.html for details) # e.g.: eastern standard time/eastern daylight time = ('est','edt') # write timezones as tuples, one to each line. ('est', 'edt') ('cst', 'cdt') ('mst', 'mdt') ('pst', 'pdt') testname.err this file is used when the test throws an uncatchable error. the first line must contain the expected error (without the extra debugger information). ...
... daylight time = ('est','edt') # write timezones as tuples, one to each line. ('est', 'edt') ('cst', 'cdt') ('mst', 'mdt') ('pst', 'pdt') testname.err this file is used when the test throws an uncatchable error. the first line must contain the expected error (without the extra debugger information). the exitcode is optional, but must be defined in this file if non-zero. verifyerror: error #1021 exitcode: 1 testname.exitcode file that specifies the expected exitcode. should just be an integer with nothing else. (note that if a .err file is defined, the .exitcode file will be ignored). in this example the .as test runs out of memory and so the expected exitcode is: 128 testname.out file that specifies expected output. this should only be used when it is not possible to generate the test ...
...testname.abc_ for special cases where the .as source is not available (e.g. fuzzed files) it is possible to check in a .abc_ which will let the test harness run compiled files without source. ...
Running Tamarin performance tests - Archive of obsolete content
enable additional output -e --avm avmplus command to use -a --asc compiler to use -g --globalabc deprecated but still works - use builtin.abc (used to be location of global.abc) -b --builtinabc location of builtin.abc -s --shellabc location of shell_toplevel.abc -x --exclude comma separated list of directories to skip -h --help display help and exit -t --notime do not generate timestamps (cleaner diffs) -f --forcerebuild force rebuild all test files -c --config sets the config string [default os-tvm] -q --quiet display minimum output during testrun -l --log also log all output to given logfile --summaryonly only display final summary --rebuildtests rebuild the tests only - do not run against vm ...
...just type the following commands after making sure you've set the environment variables correctly. $ cd /test/performance $ ./runtes...
...just type the following commands after making sure you've set the environment variables correctly. $ cd /test/performance $ ./runtests.py note on using an emulator: the emulator does seem to support hardware ...
Using IO Timeout And Interrupt On NT - Archive of obsolete content
ble runtime's (nspr) io timeout and interrupt on windows nt 3.51 and 4.0. due to a limitation of the present implementation of nspr io on nt, programs must follow the following guideline: if a thread calls an nspr io function on a file descriptor and the io function fails with <tt>pr_io_timeout_error</tt> or <tt>pr_pending_interrupt_error</tt>, the file descriptor must be closed before the thread exits. in this memo we explain the problem this guideline is trying to work around and discuss its limitations. nspr io on nt the io model of nspr 2.0 is synchronous and blocking. a thread calling an io function is blocked until the io operation finishes, either due to a successful io completion or an error. if the io operation cannot complete before the specified timeout, the io function returns w...
... a pointer to the overlapped buffer in the thread's <tt>prthread</tt> structure. if the thread subsequently exists and its <tt>prthread</tt> structure gets deleted, the pointer to the overlapped buffer will be pointing to freed memory. this is problematic. canceling overlapped io by closing the file descriptor therefore, we need to cancel the outstanding overlapped io request before the thread exits. nt's <tt>cancelio()</tt> function would be ideal for this purpose. unfortunately, <tt>cancelio()</tt> is not available on nt 3.51. so we can't go this route as long as we are supporting nt 3.51. the only reliable way to cancel outstanding overlapped io request that works on both nt 3.51 and 4.0 is to close the file descriptor, hence the rule of thumb stated at the beginning of this memo. limi...
... accessing such file descriptors. a related known bug is that timeout and interrupt don't work for <tt>pr_connect()</tt> on nt. this bug is due to a different limitation in our nt implementation. conclusions as long as we need to support nt 3.51, we need to program under the guideline that after an io timeout or interrupt error, the thread must make sure the file descriptor is closed before it exits. programs should also take care in sharing file descriptors and using io timeout or interrupt on files that need to stay open throughout the process. when we stop supporting nt 3.51, we can look into using nt 4's <tt>cancelio()</tt> function to cancel outstanding overlapped io requests when we get io timeout or interrupt errors. if <tt>cancelio()</tt> really works as advertised, that should fund...
Using SSH to connect to CVS - Archive of obsolete content
repeated passphrase requests by using ssh-agent. if you don't already run ssh-agent on your computer, it's probably easiest to start it up whenever you set up your environment to checkout and build mozilla. assuming you use a shell script or batch file to set things up, just add the commands below to the end of your file. posix shell eval `ssh-agent -s` ssh-add ~/.ssh/id_dsa $shell ssh-agent -k exit x windows in "~/.xinitrc" add "ssh-add". this will bring up a graphic box just after login, and before the desktop loads, asking for your passphrase. the passphrase will be held for the length of the x session, and be passed on to all child shells. ms-dos command prompt cygwin for /f "tokens=1,2,3* delims=; " %%a in ('ssh-agent -c') do if "%%a"=="setenv" set %%b=%%c set home=/cygdrive/c/pat...
...ogin, and before the desktop loads, asking for your passphrase. the passphrase will be held for the length of the x session, and be passed on to all child shells. ms-dos command prompt cygwin for /f "tokens=1,2,3* delims=; " %%a in ('ssh-agent -c') do if "%%a"=="setenv" set %%b=%%c set home=/cygdrive/c/path/to/your/cygwin/home/directory ssh-add ~/.ssh/id_dsa start /b /wait cmd.exe ssh-agent -k exit essentially both sets of commands do the same thing. first ssh-agent is called and its output is evaluated in the current environment. this sets environment variables that let cvs know how to find and use the agent. your private key is then added to ssh-agent using ssh-add at which point you will be prompted for the key's passphrase. since it's important that you kill the agent when you're fini...
...is called and its output is evaluated in the current environment. this sets environment variables that let cvs know how to find and use the agent. your private key is then added to ssh-agent using ssh-add at which point you will be prompted for the key's passphrase. since it's important that you kill the agent when you're finished with it, the last three lines start a child environment that, when exited, will result in the agent's process being killed. the environment you will actually use to build is the child environment. there are a few things to note about the commands for the ms-dos command prompt. first of all they will only work in versions of windows based on nt (nt/2000/xp). if you're building on win9x/winme you'll need to find an alternative solution. if you're typing the commands d...
Introducing a complete toolchain - Learn web development
parcel to build and minify our code, and to write a bunch of configuration file content automatically for us. github to manage our source code control. netlify to automate our deployment process. you may not be familiar with all the above features and tools or what they are doing, but don't panic — we'll explain each part as we move through this article. toolchains and their inherent complexity as with any chain, the more links you have in your toolchain, the more complex and potentially brittle it is — for example it might be more complex to configure, and easier to break. conversely, the fewer links, the more resilient the toolchain is likely to be. all web projects will be different, and you need to consider what parts of your toolchain are necessary and consider each part caref...
... before you deploy to your production server to ensure your software works as intended — this already sounds like a necessary toolchain. for our sample project, we'll be using a toolchain specifically designed to aid our software development and support the technical choices made during the software design phase. we will however be avoiding any superfluous tooling, with the aim of keeping complexity to a minimum. for example, we could have included a tool to minimize our svg file sizes during build. however, this project has only 4 svg images, which were manually minified using svgo before adding them to the project. a couple of prerequisites besides the tools we're going to install that contribute to our toolchain, we mentioned two web services in the above list of tools. let's take th...
...modules are correctly imported, nested css is correctly transformed to "regular css", and our development is unimpeded by the build process. now our software is ready to be written! running the transformation to start working with our project, we’ll run the parcel server on the command line. in its default mode it will...
Package management basics - Learn web development
n one more time to accept these settings. go into your parcel-experiment directory and you should now find you've got a package.json file. open it up and it should look something like this: { "name": "parcel-experiment", "version": "1.0.0", "description": "a simple npm package to learn about using npm", "main": "index.js", "scripts": { "test": "echo \"error: no test specified\" && exit 1" }, "author": "chris mills", "license": "isc" } so this is the config file that defines your package. this is good for now, so let's move on. installing parcel run the following command to install parcel locally: npm install parcel-bundler once that's done all the things, we're now ready for some "modern client-side development" (which really means using build tools to make the devel...
...nt ways. although the list grows by the month, there are three main offerings for tools that generate bundles from our source code: webpack, rollup, and parcel. there will be more available than this, but these are popular ones: the rollup tool offers tree shaking and code splitting as it’s core features. webpack requires some configuration (though “some” might be understating the complexity of some developers’ webpack configurations). in the case of parcel (prior to parcel version 2), there's a special flag required — --experimental-scope-hoisting — which will tree shake while building. let’s stick with parcel for now, given that we’ve already got it installed. try running the following command: parcel build index.html --experimental-scope-hoisting you’ll see that ...
... filename.html, and we’d like to use that often during our development. so let’s create a custom shorthand command — “dev” — in our package.json. if you followed the tutorial from earlier, you should have a package.json file inside your parcel-experiment directory. open it up, and its scripts member should look like this: "scripts": { "test": "echo \"error: no test specified\" && exit 1", }, update it so that it looks like this, and save the file: "scripts": { "test": "echo \"error: no test specified\" && exit 1", "dev": "parcel serve index.html" }, we’ve added a custom dev command as an npm script. now try running the following in your terminal, making sure you are inside the parcel-experiment directory: npm run dev this should start parcel and serve up your inde...
mach
r repo! many pkgbuild options to choose from and most work like a charm - while "mach" may not necessarily work like a charm for everyone. why even bother with a competing build system in arch when octopi does what you want and even has a gui? those makepkg scripts named pkgbuild are (typically) simple bash scripts that are easy to maintain and modify. python based mach tends to involve more complexity and potential for breakage. another possible reason: mach gives you an error, while running, say bootstrap.py directly (that is to type in a bash shell: python2 ./bootstrap.py enter-key ) in an otherwise empty ..../subdir/ may work for you! less may be better! and mach's error messages tend to be cryptic and not utterly helpful. that above bootstrap.py will download and setup everything so yo...
...er of bugs and numerous areas for improvement. some larger known issues include: mintty (alternative terminal emulator on windows) doesn't work. text encoding issues (especially on windows where latin-1 is not the default system encoding). failed commands spew lots of extra error output, e.g. you will see a big mach error message when all that happened was an invoked command returned a non-0 exit code - possibly expectedly so in mozilla! generally, mach is known to work pretty well without issues for most people and works terribly for others with even the "basics" being quite unsatisfactory. how do i report bugs? bugs against the mach core can be filed in bugzilla in the firefox build system::mach core. most mach bugs are bugs in individual commands, not bugs in the core mach code. ...
...ing the current directory, a handle on the logging manager, the settings object, and information about available mach commands. the arguments registered with @commandargument are passed to your method as keyword arguments using the **kwargs calling convention. so, you should define default values for all of your method's arguments. the return value from the @command method should be the integer exit code from the process. if not defined or none, 0 will be used. registering mach command providers once you've written a python module providing a mach command, you'll need to register it with mach. there are two ways to do this. if you have a single file, the easiest solution is probably to register it as a one-off inside build/mach_bootstrap.py. there should be a python list of paths named ma...
HTTP Cache
onsumer reference ++ (dropped back after an opener is removed from the fifo) state == notloaded: state = loading when open_truncate flag was used: cachefile is created as 'new', state = empty otherwise: cachefile is created and load on it started cacheentry::onfileready notification is now expected state == loading: just do nothing and exit call to cacheentry::invokecallbacks cacheentry::invokecallbacks (entry atomic): called on: a new opener has been added to the fifo via an asyncopen call asynchronous result of cachefile open the writer throws the entry away the output stream of the entry has been opened or closed metadataready or setvalid on the entry has been called the entry has been doomed stat...
...dropped back when the consumer releases the entry) oncacheentryavailable is invoked on the opener with anew = false and the entry opener is removed from the fifo result == entry_not_wanted: oncacheentryavailable is invoked on the opener with null for the entry opener is removed from the fifo state == writing or revalidating: do nothing and exit any other value of state is unexpected here (assertion failure) loop this process while there are openers in the fifo cacheentry::onfileready (entry atomic): load result == failure or the file has not been found on disk (is new): state = empty otherwise: state = ready since the cache file has been found and is usable containing meta data and data of the entry call to cacheentry::inv...
...t == failure or the file has not been found on disk (is new): state = empty otherwise: state = ready since the cache file has been found and is usable containing meta data and data of the entry call to cacheentry::invokecallbacks cacheentry::onhandleclosed (entry atomic): called when any consumer throws the cache entry away if the handle is not the handle given to the current writer, then exit state == writing: the writer failed to call metadataready on the entry - state = empty state == revalidating: the writer failed the re-validation process and failed to call setvalid on the entry - state = ready call to cacheentry::invokecallbacks all consumers release the reference: the entry may now be purged (removed) from memory when found expired or least used on overrun of the memory...
Monitors
in addition to the mutex type prlock, nspr provides a special type, prmonitor, for use in java programming. this chapter describes the nspr api for creation and manipulation of a mutex of type prmonitor. monitor type monitor functions with a mutex of type prlock, a single thread may enter the monitor only once before it exits, and the mutex can have multiple associated condition variables. ...
...ssociated condition variables. with a mutex of type prmonitor, a single thread may re-enter a monitor as many times as it sees fit. the first time the thread enters a monitor, it acquires the monitor's lock and the thread's entry count is incremented to 1. each subsequent time the thread successfully enters the same monitor, the thread's entry count is incremented again, and each time the thread exits the monitor, the thread's entry count is decremented. when the entry count for a thread reaches zero, the thread releases the monitor's lock, and other threads that were blocked while trying to enter the monitor will be rescheduled. a call to pr_wait temporarily returns the entry count to zero. when the calling thread resumes, it has the same entry count it had before the wait operation. unlik...
... monitor object, all monitor functions require a pointer to an opaque object of type prmonitor. monitor functions all monitor functions are thread-safe. however, this safety does not extend to protecting the monitor object from deletion. pr_newmonitor creates a new monitor. pr_destroymonitor destroys a monitor object. pr_entermonitor enters the lock associated with a specified monitor. pr_exitmonitor decrements the entry count associated with a specified monitor. pr_wait waits for a notify on a specified monitor's condition variable. pr_notify notifies a thread waiting on a specified monitor's condition variable. pr_notifyall notifies all threads waiting on a specified monitor's condition variable. ...
NSS Sample Code Sample_2_Initialization of NSS
nss sample code 2: initializing nss this example program demonstrates how to initialize the nss database. this program illustrates password handling. ...
...%s -d <dbdirpath> [-p <plainpasswc>]" " [-f <passwdffile>]\n\n", progname); fprintf(stderr, "%-15s specify a db directory path\n\n", "-d <dbdirpath>"); fprintf(stderr, "%-15s specify a plaintext password\n\n", "-p <plainpasswc>"); fprintf(stderr, "%-15s specify a password file\n\n", "-f <plainpasswc>"); exit(-1); } /* initialize the slot password */ char *initslotpassword(pk11slotinfo *slot, prbool retry, void *arg) { file *input; file *output; char *p0 = null; char *p1 = null; secupwdata *pwdata = (secupwdata *) arg; if (pwdata->source == pw_fromfile) { return filepasswd(slot, retry, pwdata->data); } if (pwdata->so...
... */ rv = changepw(slot, plainpass, 0, pwfile, 0); if (rv != secsuccess) { pr_fprintf(pr_stderr, "failed to change password\n"); } if (slot) { pk11_freeslot(slot); } rvshutdown = nss_shutdown(); ...
Initialize NSS database - sample 2
nss sample code 2: initialize the nss database. the nss sample code below demonstrates how to initialize the nss database. ...
... static void usage(const char *progname) { fprintf(stderr, "\nusage: %s -d [-p ]" " [-f ]\n\n", progname); fprintf(stderr, "%-15s specify a db directory path\n\n", "-d "); fprintf(stderr, "%-15s specify a plaintext password\n\n", "-p "); fprintf(stderr, "%-15s specify a password file\n\n", "-f "); exit(-1); } /* * initslotpassword */ char * initslotpassword(pk11slotinfo *slot, prbool retry, void *arg) { file *input; file *output; char *p0 = null; char *p1 = null; secupwdata *pwdata = (secupwdata *) arg; if (pwdata->source == pw_fromfile) { return filepasswd(slot, retry, pwdata->data); } if (pwdata->source ==...
... */ rv = changepw(slot, plainpass, 0, pwfile, 0); if (rv != secsuccess) { pr_fprintf(pr_stderr, "failed to change password\n"); } if (slot) { pk11_freeslot(slot); } rvshutdown = nss_shutdown(); ...
Rhino shell
t given. readurl(url [, charactercoding]) open an input connection to the given string url, read all its bytes and convert them to a string using the specified character coding or default character coding if explicit coding argument is not given. runcommand(commandname, [arg, ...] [options]) execute the specified command with the given argument and options as a separate process and return the exit status of the process. usage: runcommand(command) runcommand(command, arg1, ..., argn) runcommand(command, arg1, ..., argn, options) all except the last arguments to runcommand are converted to strings and denote command name and its arguments. if the last argument is a javascript object, it is an option object. otherwise it is converted to string denoting the last argument and options object...
... a; } js> var a = 34; js> f() 34 js> quit() $ cat echo.js for (i in arguments) { print(arguments[i]) } $ java org.mozilla.javascript.tools.shell.main echo.js foo bar foo bar $ spawn and sync the following example creates 2 threads via spawn and uses sync to create a synchronized version of the function test. js> function test(x) { print("entry"); java.lang.thread.sleep(x*1000); print("exit"); } js> var o = { f : sync(test) }; js> spawn(function() {o.f(5);}); thread[thread-0,5,main] entry js> spawn(function() {o.f(5);}); thread[thread-1,5,main] js> exit entry exit runcommand here are a few examples of invoking runcommand under linux. js> runcommand('date') thu jan 23 16:49:36 cet 2003 0 // using input option to provide process input js> runcommand("sort", {input: "c\na\nb"}) a b...
..._array = [1, 2, 3, 4]; js> runcommand("echo", { args: arg_array}) 1 2 3 4 0 examples for windows are similar: js> // invoke shell command js> runcommand("cmd", "/c", "date /t") 27.08.2005 0 js> // run sort collectiong the output js> var opt={input: "c\na\nb", output: 'sort output:\n'} js> runcommand("sort", opt) 0 js> print(opt.output) sort output: a b c js> // invoke notepad and wait until it exits js> runcommand("notepad") 0 ...
Detailed XPCOM hashtable guide
. hashtables should not be used for sets that need to be sorted; very small datasets (less than 12-16 items); data that does not need random access. in these situations, an array, a linked-list, or various tree data structures are more efficient. mozilla's hashtable implementations mozilla has several hashtable implementations, which have been tested and, tuned, and hide the inner complexities of hashtable implementations: pldhash - low-level c api; stores keys and data in one large memory structure; uses the heap efficiently; client must declare an "entry class" and may not hold onto entry pointers. plhashtable - low-level c api; entry class pointers are constant; more efficient for large entry structures; often wastes memory making many small heap allocations. nsthashtable - ...
...ble, because plhashtable makes many heap allocations. there are two situations where plhashtable may be preferable to pldhash: you need entry-pointers to remain constant. the entries stored in the table are very large (larger than 12 words). pldhash does not handle large entry structures efficiently. nsthashtable nsthashtable is a c++ template that wraps pldhash. it hides many of the complexities of pldhash (callback functions, the ops structure, etc). you should read xpcom/glue/nsthashtable.h. to use nsthashtable, you must declare an entry-class in a pre-defined format. this entry class contains the key and the data that you are hashing (just like pldhash, above). it also declares functions that manipulate the key. in most cases, the functions of this entry class can be entirely inli...
...and relatives will work for you. they are much easier to use, because you do not have to declare an entry class. if you are hashing a simple key type to a simple data type, they are generally a better choice. nsbasehashtable and friends: nsdatahashtable, nsinterfacehashtable, and nsclasshashtable these c++ templates provide a high-level interface for using hashtables that hides most of the complexities of pldhash. they provide the following features: hashtable operations can be completed without using an entry class, making code easier to read; optional thread-safety: the hashtable can manage a read-write lock around the table; predefined key classes provide automatic cleanup of strings/interfaces nsinterfacehashtable and nsclasshashtable automatically release/delete objects to avoid l...
nsIAppShell
e native event system layer. this interface is designed to be used on the main application thread only. ...
...in on the command line. argv a direct reference to the parameter array. dispatchnativeevent() obsolete since gecko 1.9 (firefox 3) after event dispatch execute app specific code. void dispatchnativeevent( in prbool arealevent, in voidptr aevent ); parameters arealevent event is real or a null placeholder (macintosh). aevent void pointer to native event structure. exit() exit the handle event loop. void exit(); parameters none. favorperformancehint() give hint to native event queue notification mechanism. if the native platform needs to tradeoff performance vs. native event starvation this hint tells the native dispatch code which to favor. the default is to prevent native event starvation. calls to this function may be nested. when the number of calls that pa...
...en pr_true for a new queue wanting hooking up. pr_false for a queue wanting to be unhooked. resumenative() resumes the use of additional platform-specific methods to run() gecko events on the main application thread. calls to suspendnative() and resumenative may be nested. on some platforms this will be a no-op. void resumenative(); parameters none. run() enter an event loop. do not leave until exit() is called. void run(); parameters none. runinstablestate() allows running of a "synchronous section", in the form of an nsirunnable once the event loop has reached a "stable state". a stable state is reached when the currently executing task/event has finished, (see: webappapis.html#synchronous-section). in practice this runs arunnable once the currently executing event finishes. if called mul...
nsIAppShellService
void hidesplashscreen(); obsolete since gecko 1.8 void initialize(in nsicmdlineservice acmdlineservice, in nsisupports nativeappsupportorsplashscreen); obsolete since gecko 1.8 void quit(in pru...
... during application startup (and at other times!) we may temporarily encounter a situation where all application windows will be closed but we do not want to take this as a signal to quit the application. bracket the code where the last window could close with these. (and at application startup, on platforms that do not normally quit when the last window has closed, call enter once, but not exit) void enterlastwindowclosingsurvivalarea(); parameters none. exitlastwindowclosingsurvivalarea() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) void exitlastwindowclosingsurvivalarea(); parameters none. native code only!gethiddenwindowandjscontext return the (singleton) application hidden window as an nsidomwindow, and, the correspond...
...n ); parameters acmdlineservice is stored and passed to appshell components as they are initialized. nativeappsupportorsplashscreen is an object that can be queryinterface'd to either an nsinativeappsupport or nsisplashscreen; this object will be used to implement hidesplashscreen. quit() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) exit the event loop, shut down the app. void quit( in pruint32 aferocity ); parameters aferocity one of the e* constants. createwindowlessbrowser() this method creates a browser that does not have a window. if the browser is exited, this windowless browser will not prevent firefox from exiting. e10s notes: the browser is created in process. to get an out of process element you want to co...
nsIWebBrowserChrome
embedding/browser/webbrowser/nsiwebbrowserchrome.idlscriptable corresponds to the top-level, outermost window containing an embedded gecko web browser. inherits from: nsisupports last changed in gecko 0.9.6 method overview void destroybrowserwindow(); void exitmodaleventloop(in nsresult astatus); boolean iswindowmodal(); void setstatus(in unsigned long statustype, in wstring 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 nsiwebb...
... chrome_openas_chrome 2147483648 represent special cases. chrome_all 4094 represent special cases. chrome_remote_window 1048576 whether this window should use remote (out-of-process) tabs. methods destroybrowserwindow() asks the implementer to destroy the window associated with this webbrowser object. void destroybrowserwindow(); parameters none. exitmodaleventloop() exit a modal event loop if we're in one. the implementation should also exit out of the loop if the window is destroyed. void exitmodaleventloop( in nsresult astatus ); parameters astatus the result code to return from showasmodal(). iswindowmodal() is the window modal (that is, currently executing a modal loop)? boolean iswindowmodal(); parameters none. return value...
...tatus( in unsigned long statustype, in wstring status ); parameters statustype indicates what is setting the text. status status string. null is an acceptable value meaning no status. showasmodal() shows the window as a modal window. void showasmodal(); parameters none. return value note: the function error code returned by this corresponds to the status value specified in exitmodaleventloop. sizebrowserto() tells the chrome to size itself such that the browser will be the specified size. void sizebrowserto( in long acx, in long acy ); parameters acx new width of the browser. acy new height of the browser. ...
Document - Web APIs
Web › API › Document
ent is raised. globaleventhandlers.ondrag is an eventhandler representing the code to be called when the drag event is raised. globaleventhandlers.ondragend is an eventhandler representing the code to be called when the dragend event is raised. globaleventhandlers.ondragenter is an eventhandler representing the code to be called when the dragenter event is raised. globaleventhandlers.ondragexit is an eventhandler representing the code to be called when the dragexit event is raised. globaleventhandlers.ondragleave is an eventhandler representing the code to be called when the dragleave event is raised. globaleventhandlers.ondragover is an eventhandler representing the code to be called when the dragover event is raised. globaleventhandlers.ondragstart is an eventhandler representi...
...ocessinginstruction object. document.createrange() creates a range object. document.createtextnode() creates a text node. document.createtouch() creates a touch object. document.createtouchlist() creates a touchlist object. document.createtreewalker() creates a treewalker object. document.enablestylesheetsforset() enables the style sheets for the specified style sheet set. document.exitpointerlock() release the pointer lock. document.getanimations() returns an array of all animation objects currently in effect, whose target elements are descendants of the document. document.getelementsbyclassname() returns a list of elements with the given class name. document.getelementsbytagname() returns a list of elements with the given tag name. document.getelementsbytagnamens()...
...onds as an element or text selection is being dragged by the user. also available via the ondrag property. dragend fired when a drag operation is being ended (by releasing a mouse button or hitting the escape key). also available via the ondragend property. dragenter fired when a dragged element or text selection enters a valid drop target. also available via the ondragenter property. dragexit fired when an element is no longer the drag operation's immediate selection target. also available via the ondragexit property. dragleave fired when a dragged element or text selection leaves a valid drop target. also available via the ondragleave property. dragover fired when an element or text selection is being dragged over a valid drop target (every few hundred milliseconds). also ava...
Element: fullscreenchange event - Web APIs
creenchange this event is sent to the element which is transitioning into or out of full-screen mode. examples in this example, a handler for the fullscreenchange event is added to the element whose id is fullscreen-div. if the user clicks on the "toggle fullscreen mode" button, the click handler will toggle full-screen mode for the div. if document.fullscreenelement has a value it will exit full-screen mode. if not, the div will be placed into full-screen mode. remember that by the time the fullscreenchange event is handled, the status of the element has already changed. so if the change is to full-screen mode, document.fullscreenelement will point to the element that is now in full-screen mode. on the other hand, if document.fullscreenelement is null, full-screen mode has been can...
...in fullscreen mode if there is one. if not, the value // of the property is null. ...
...erty is null. ...
Element.requestFullscreen() - Web APIs
uestfullscreen(), as seen in the example below. to learn when other code has toggled full-screen mode on and off, you should establish listeners for the fullscreenchange event on the document. it's also important to listen for fullscreenchange to be aware when, for example, the user manually toggles full-screen mode, or when the user switches applications, causing your application to temporarily exit full-screen mode. examples this function toggles the first <video> element found in the document into and out of full-screen mode. function togglefullscreen() { let elem = document.queryselector("video"); if (!document.fullscreenelement) { elem.requestfullscreen().catch(err => { alert(`error attempting to enable full-screen mode: ${err.message} (${err.name})`); }); } else ...
...de. examples this function toggles the first <video> element found in the document into and out of full-screen mode. function togglefullscreen() { let elem = document.queryselector("video"); if (!document.fullscreenelement) { elem.requestfullscreen().catch(err => { alert(`error attempting to enable full-screen mode: ${err.message} (${err.name})`); }); } else { document.exitfullscreen(); } } if the document isn't already in full-screen mode—detected by looking to see if document.fullscreenelement has a value—we call the video's requestfullscreen() method. we don't need to do anything special if successful, but if the request fails, our promise's catch() handler presents an alert with an appropriate error message. if, on the other hand, full-screen mode is alr...
...ent isn't already in full-screen mode—detected by looking to see if document.fullscreenelement has a value—we call the video's requestfullscreen() method. we don't need to do anything special if successful, but if the request fails, our promise's catch() handler presents an alert with an appropriate error message. if, on the other hand, full-screen mode is already in effect, we call document.exitfullscreen() to disable full-screen mode. you can see this example in action or view or remix the code on glitch. specifications specification status comment fullscreen apithe definition of 'element.requestfullscreen()' in that specification. living standard initial definition ...
Using IndexedDB - Web APIs
h the new options. (note that this will delete the information in the object store! if you need to save that information, you should read it out and save it somewhere else before upgrading the database.) trying to create an object store with a name that already exists (or trying to delete an object store with a name that does not already exist) will throw an error. if the onupgradeneeded event exits successfully, the onsuccess handler of the open database request will then be triggered. blink/webkit supports the current version of the spec, as shipped in chrome 23+ and opera 17+; ie10+ does too. other and older implementations don't implement the current version of the spec, and thus do not support the indexeddb.open(name, version).onupgradeneeded signature yet. for more information on ho...
... the store to the origin of the site that creates it (typically, this is the site domain or subdomain), so it cannot be accessed by any other origin. third party window content (e.g. <iframe> content) cannot access indexeddb if the browser is set to never accept third party cookies (see bug 1147821.) warning about browser shutdown when the browser shuts down (because the user chose the quit or exit option), the disk containing the database is removed unexpectedly, or permissions are lost to the database store, the following things happen: each transaction on every affected database (or all open databases, in the case of browser shutdown) is aborted with an aborterror. the effect is the same as if idbtransaction.abort() is called on each transaction. once all of the transactions have com...
... these events, so that you know when a database is unexpectedly closed. the behavior described above is new, and is only available as of the following browser releases: firefox 50, google chrome 31 (approximately). prior to these browser versions, the transactions are aborted silently, and no close event is fired, so there is no way to detect an unexpected database closure. since the user can exit the browser at any time, this means that you cannot rely upon any particular transaction to complete, and on older browsers, you don't even get told when they don't complete. there are several implications of this behavior. first, you should take care to always leave your database in a consistent state at the end of every transaction. for example, suppose that you are using indexeddb to store a ...
Creating a cross-browser video player - Developer guides
naturally the fullscreen button needs to actually do something, so, like the other buttons, a click event handler is attached in which we call a user defined function handlefullscreen: fullscreen.addeventlistener('click', function(e) { handlefullscreen(); }); the handlefullscreen function is defined as follows: var handlefullscreen = function() { if (isfullscreen()) { if (document.exitfullscreen) document.exitfullscreen(); else if (document.mozcancelfullscreen) document.mozcancelfullscreen(); else if (document.webkitcancelfullscreen) document.webkitcancelfullscreen(); else if (document.msexitfullscreen) document.msexitfullscreen(); setfullscreendata(false); } else { if (videocontainer.requestfullscreen) videocontainer.requestfullscreen(); ...
... calling another function isfullscreen: var isfullscreen = function() { return !!(document.fullscreen || document.webkitisfullscreen || document.mozfullscreen || document.msfullscreenelement || document.fullscreenelement); } this function checks all the various browser prefixed versions to try and determine the correct result. if the browser is currently in fullscreen mode, then it must be exited and vice versa. support for the different prefixed versions of the relevant action are checked in order to call the correct one. interestingly document must be used for exiting/cancelling fullscreen mode, whereas any html element can request fullscreen mode, here the videocontainer is used as it also contains the custom controls which should also appear with the video in fullscreen mode. the e...
...data-states). var setfullscreendata = function(state) { videocontainer.setattribute('data-fullscreen', !!state); } this is used simply to set some basic css to improve the styling of the custom controls when they are in fullscreen (see the sample code for further details). ...
An overview of HTTP - HTTP
Web › HTTP › Overview
http is extensible introduced in http/1.0, http headers make this protocol easy to extend and experiment with. new functionality can even be introduced by a simple agreement between a client and a ser...
... http is extensible introduced in http/1.0, http headers make this protocol easy to extend and experiment with. ...
...ent handlers that have been registered for the events' type if known, or to the onmessage event handler if no type-specific event handler was established. conclusion http is an extensible protocol that is easy to use. the client-server structure, combined with the ability to simply add headers, allows http to advance along with the extended capabilities of the web. though http/2 adds some complexity, by embedding http messages in frames to improve performance, the basic structure of messages has stayed the same since http/1.0. session flow remains simple, allowing it to be investigated, and debugged with a simple http message monitor. ...
InternalError: too much recursion - JavaScript
elf. this is called a base case. in some ways, recursion is analogous to a loop. both execute the same code multiple times, and both require a condition (to avoid an infinite loop, or rather, infinite recursion in this case). when there are too many function calls, or a function is missing a base case, javascript will throw this error. ...
...to a loop. both execute the same code multiple times, and both require a condition (to avoid an infinite loop, or rather, infinite recursion in this case). when there are too many function calls, or a function is missing a base case, javascript will throw this error. examples this recursive function runs 10 times, as per the exit condition. ...
...n loop(x) { if (x >= 10) // "x >= 10" is the exit condition return; // do stuff loop(x + 1); // the recursive call } loop(0); setting this condition to an extremely high value, won't work: function loop(x) { if (x >= 1000000000000) return; // do stuff loop(x + 1); } loop(0); // internalerror: too much recursion this recursive function is missing a base case. as there is no exit condition, the function will call itself infinitely. function loop(x) { // the base case is missing loop(x + 1); // recursive call } loop(0); // internalerror: too much recursion class error: too much recursion class person{ constructor(){} set name(name){ this.name = name; // recursive call } } const tony = new person(); tony.name = "tonisha"; // internalerror: too much recursion ...
Compiling a New C/C++ Module to WebAssembly - WebAssembly
html_template/shell_minimal.html into this new directory too, just for convenience (you'd obviously put this in a central place in your real dev environment). now let's run the compilation step again. from inside your latest directory (and while inside your emscripten compiler environment terminal window), compile your c code with the following command. ...
...oo, just for convenience (you'd obviously put this in a central place in your real dev environment). now let's run the compilation step again. from inside your latest directory (and while inside your emscripten compiler environment terminal window), compile your c code with the following command. ...
...dev environment). now let's run the compilation step again. from inside your latest directory (and while inside your emscripten compiler environment terminal window), compile your c code with the following command. (note that we need to compile with no_exit_runtime, which is necessary as otherwise when main() exits the runtime would be shut down — necessary for proper c emulation, e.g., atexits are called — and it wouldn't be valid to call compiled code.) emcc -o hello3.html hello3.c -o3 -s wasm=1 --shell-file html_template/shell_minimal.html -s no_exit_runtime=1 -s "extra_exported_runtime_methods=['ccall']" if you load the example in your browser again, you'll see the same thing as before! now we need to run our new myfunction() function from javascript. first of all...
private-browsing - Archive of obsolete content
for example, the "downloads" window might want to display all downloads while there are still some private windows open, then clean out all the private data when all private windows have closed. to do this with the sdk, you ca...
... private windows while they are open, as long as you don't store it after the private browsing windows have been closed. for example, the "downloads" window might want to display all downloads while there are still some private windows open, then clean out all the private data when all private windows have closed. to do this with the sdk, you can listen to the system event named "last-pb-context-exited": var events = require("sdk/system/events"); function listener(event) { console.log("last private window closed"); } events.on("last-pb-context-exited", listener); globals functions isprivate(object) function to check whether the given object is private. it takes an object as an argument, and returns true only if the object is: a private browserwindow or a tab belonging to a privat...
system - Archive of obsolete content
pathfor(i...
....log("name = " + system.name); // host application version console.log("version = " + system.version); // host application vendor console.log("vendor = " + system.vendor); // host application profile directory console.log("profile directory = " + system.pathfor("profd")); quit the host application to quit the host application, use the exit() function. var system = require("sdk/system"); system.exit(); globals functions exit(code) quits the host application with the specified code. if code is omitted, exit() uses the success code 0. to exit with failure use 1. var system = require("sdk/system"); system.exit(); parameters code : integer to exit with failure, set this to 1. to exit with success, omit this argument. pathfor(id) firefox enables you to get the path to certain "special" ...
Automated testing tips and tricks - Archive of obsolete content
in test scripts, <code>sleep 5 after the above command should ensure the profile is created before the next command in the test script is run how to enable dump in a new profile add user_pref("browser.dom.window.dump.enabled", true); to profiledir/user.js how to execute test code with chrome privileges using a chrome doc -...
...le dump in a new profile add user_pref("browser.dom.window.dump.enabled", true); to profiledir/user.js how to execute test code with chrome privileges using a chrome doc - see sbtests.xul in http://people.mozilla.com/~davel/scripts/ for an example firefox-bin -p sbtestprofile -chrome chrome://sbtests/content/ above code calls the quit function in quit.js to exit after test is finished how to detect content onload event from chrome use the domcontentloaded event chromewindow.addeventlistener('domcontentloaded',callbackfunction,false); ...
Nanojit - Archive of obsolete content
ut.ins0(lir_start); lins *two = out.insimm(2); lins *firstparam = out.insparam(0, 0); lins *result = out.ins2(lir_add, firstparam, two); out.ins1(lir_ret, result); // emit a lir_loop instruction. it won't be reached, but there's // an assertion in nanojit that trips if a fragment doesn't end with // a guard (a bug in nanojit). lins *rec_ins = out.insskip(sizeof(guardrecord) + sizeof(sideexit)); guardrecord *guard = (guardrecord *) rec_ins->payload(); memset(guard, 0, sizeof(*guard)); sideexit *exit = (sideexit *)(guard + 1); guard->exit = exit; guard->exit->target = f; f->lastins = out.insguard(lir_loop, out.insimm(1), rec_ins); // compile the fragment. compile(assm, f, *alloc verbose_only(, fragmento->labels)); if (assm->error() != none) { fprintf(stderr, "error compilin...
.... the jit code would have a guard checking this condition(an xt guard), and would return to the interpreter if the condition turns out to be true. the interpreter is then equipped to handle the overflow. hence, guards are needed to prevent certain erroneous behaviour that might result from the assumptions that are generally made while jit is generated. todo: explain guards, guard records, vmsideexit, fragmento, verbosewriter::formatguard... ...
Running Tamarin acceptance tests - Archive of obsolete content
you should set environment variables as described above except for avm, which should be: $ export avm=$tamarin_build_top/platform/android/android_shell.py where $tamarin_build_top is your main tamarin repo folder. note that avm need...
...h avmshell /data/local/tamarin/avmshell $ adb shell 'chmod 777 /data/local/tamarin/avmshell' copy android_runner.sh, if it doesn't already exist on the phone in /data/local/tamarin $ adb push tamarin-redux/platform/android/android_runner.sh /data/local/tamarin/android_runner.sh $ adb shell 'chmod 777 /data/loca/android_runner.sh' test it out with a simple .abc or no args for usage (should return exitcode=0) $ tamarin-redux/platform/android/android_shell.py hello.abc hello exitcode=0 test it out by retrieving the version information of the shell on the android device $ $avm -dversion shell 1.4 debug build 6299:455bca954565 features avmsystem_32bit;avmsystem_unaligned_int_access;avmsystem_little_endian;avmsystem_arm;avmsystem_unix; avmfeature_jit;avmfeature_abc_interp;avmfeature_selftest;avmfea...
Anonymous Content - Archive of obsolete content
cus pseudo-element is hierarchical. style rules can be written with the assumption that they will match (in the above example) both the file control and the element focused inside the file control. in other words, an arbitrary chain of elements can be in the :focus state at the same time. mouseover and mouseout events mouseover and mouseout events are retargeted if the mouse genuinely enters or exits the bound element (in addition to entering or exiting some anonymous content). if, however, the user has simply moved the mouse from one anonymous element to another, without entering or exiting the bound element itself, then the event is stopped. for example, if the user enters the html file upload control from the left, a mouseover event is generated for the anonymous textfield. because this ...
...he button, a mouseout is generated for the textfield, followed by a mouseover of the button. since neither of these events constitutes a mouseover or mouseout of the file control itself, the events are not allowed to flow to the file control. if the user continues moving to the right and leaves the button, then the mouseout generated will be retargeted, since the file control will also have been exited. anonymous content and css selectors and scopes bindings can interleave anonymous elements between the bound element and its explicit children. see insertion points for more information. in this situation, a new tree emerges that is different from the explicit content node tree. in addition to having a single explicit parent (the bound element) the explicit children also have an arbitrary se...
XUL Events - Archive of obsolete content
he drag is finished. attribute: ondragend dragenter the dragenter event is sent when the mouse pointer first moves over an element during a drag. it is similar to the mouseover event but occurs while dragging. ...
...o the mouseover event but occurs while dragging. attribute: ondragenter dragexit this event is sent when the mouse pointer moves away from an element during a drag. it is also called after a drop on an element. it is similar to the mouseout event but occurs during a drag. attribute: ondragexit draggesture this event is sent when the user starts dragging the element, usually by holding down the mouse button and moving the mouse. attribute: ondraggesture dragover related to the mousemove event, this event i...
Special per-platform menu considerations - Archive of obsolete content
nu commands, convention dictates where these items will be placed. for instance, the edit menu always starts with the undo command if such a feature is available in the application, followed by redo, cut, copy, paste, and so forth. some menu items have specific common labels or locations where certain menu items would go that differ on each platform. for instance, on windows, the menu item which exits the application is labeled "exit" and is normally placed at the end of the file menu. the mac application menu on the macintosh, an extra menu exists beside the file menu; its name is the same as the name of the application. this menu contains a number of items that pertain to the application. for instance, this is the proper place to put the menu items which open the application preferences a...
...ems that need to be placed on the application menu. on the mac, these menu items will be moved onto the application menu, but on other platforms, they will be left in their original locations. this makes it easier to write the same xul code for all platforms. here is a list of the menu item ids which are automatically handled. menu_filequitseparator the separator just before the quit/exit item. menu_filequititem the item which exits the application. menu_prefsseparator the separator just before the preferences/options item. menu_preferences the item which opens the application preferences. aboutseparator the separator just before the about item. aboutname the item which opens the about dialog for the application. ...
Anatomy of a video game - Game development
evelopment could also benefit, too. present, accept, interpret, calculate, repeat the goal of every video game is to present the user(s) with a situation, accept their input, interpret those signals into actions, and calculate a new situation resulting from those acts. games are constantly looping through these stages, over and over, until some end condition occurs (such as winning, losing, or exiting to go to bed). not surprisingly, this pattern corresponds to how a game engine is programmed. the specifics depend on the game. some games drive this cycle by user input. imagine that you are developing a "find the differences between these two similar pictures"-type game. these games present two images to the user; they accept their click (or touch); they interpret the input as a success, f...
...er to cancel the request that corresponds to our token. window.cancelanimationframe( mygame.stopmain ); the key to programming a main loop, in javascript, is to attach it to whatever event should be driving your action and pay attention to how the different systems involved interplay. you may have multiple components driven by multiple different types of events. this feels like unnecessary complexity but it might just be good optimization (not necessarily, of course). the problem is that you are not programming a typical main loop. in javascript, you are using the browser's main loop and you are trying to do so effectively. building a more optimized main loop in javascript ultimately, in javascript, the browser is running its own main loop and your code exists in some of its stages. the ab...
Algorithm - MDN Web Docs Glossary: Definitions of Web-related terms
for example: a cooking recipe is a simple algorithm for humans. ...
...ar regression, logistic regression, decision tree, random forest, support vector machine, recurrent neural network (rnn), long short term memory (lstm) neural network, convolutional neural network (cnn), deep convolutional neural network and so on. learn more general knowledge algorithm on wikipedia technical reference explanations of sorting algorithms explanations of algorithmic complexity ...
Solve common problems in your JavaScript code - Learn web development
t: myfunction(); function scope remember that functions have their own scope — you can't access a variable value set inside a function from outside the function, unless you declared the variable globally (i.e. not inside any functions), or return the value from the function. running code after a return statement remember also that when you return from a function, the javascript interpreter exits the function — no code after the return statement will run. in fact, some browsers (like firefox) will give you an error message in the developer console if you have code after a return statement. firefox gives you "unreachable code after return statement". object notation versus normal assignment when you assign something normally in javascript, you use a single equals sign, e.g.: const m...
...while loops? how do you iterate over the elements in an array? how do you iterate over the elements in a multidimensional array? how do you iterate over the members in an object? how do you iterate over the members of an object n...
Handling common accessibility problems - Learn web development
ated dynamic content can be a problem because screenreader users might miss it, especially if it updates unexpectedly. if you have a single-page app with a main content panel that is regularly updated using xmlhttprequest or fetch, a screenreader user might miss those updates. wai-aria do you need to use such complex functionality, or will plain old semantic html do instead? if you do need complexity, you should consider using wai-aria (accessible rich internet applications), a specification that provides semantics (in the form of new html attributes) for items such as complex form controls and updating panels that can be understood by most browsers and screen readers. to deal with complex form widgets, you need to use aria attributes like roles to state what role different elements have in...
...tion. vo + u use the rotor, which displays lists of headings, links, form controls, etc. for easy navigation. vo + left cursor, vo + right cursor (when inside rotor) move between different lists available in the rotor. vo + up cursor, vo + down cursor (when inside rotor) move between different items in the current rotor list. esc (when inside rotor) exit rotor. ctrl (when vo is speaking) pause/resume speech. vo + z restart the last bit of speech. vo + d go into the mac's dock, so you can select apps to run inside it. this seems like a lot of commands, but it isn't so bad when you get used to it, and vo regularly gives you reminders of what commands to use in certain places. have a play with vo now; you c...
Deploying our app - Learn web development
sts are outside of parcel's view of our system — since parcel never sees nor runs any of the test code, we're left to install the dependency ourselves. now to manually run the test, from the command line we can run: npm run test the result, if successful, is … nothing. this is considered a success. in general we only want tests to be noisy if there's something wrong. the test also exited with a special signal that tells the command line that it was successful — an exit signal of 0. if there's a failure the test fails with an exit code of 1 — this is a system-level value that says "something failed". the npm run test command will use node to run all the files that are in the tests directory that end with .js. in our build script, npm run test is called, then you see th...
...so this translates into: if the tests pass, then build the code. you'll have to upload your new code to github, using similar commands to what you used before: git add . ...
CustomizableUI.jsm
fter customize mode drag handling system tries to determine the width and height of widget awidgetid when dragged to a different area. aarea will be the area the item is dragged to, or undefined after the measurements have been done and the node has been moved back to its 'regular' area. oncustomizestart(awindow) fired when opening customize mode in awindow. oncustomizeend(awindow) fired when exiting customize mode in awindow. onwidgetoverflow(anode, acontainer) fired when a widget's dom node is overflowing its container, a toolbar, and will be displayed in the overflow panel. onwidgetunderflow(anode, acontainer) fired when a widget's dom node is not overflowing its container, a toolbar, anymore. onwindowopened(awindow) fired when a new customizable (ie browser) window is opened. on...
...ers awidgetid the id of the widget that is being dragged to an area. aarea the id of the area to which the widget is being dragged. notifystartcustomizing() notify listeners that a window is entering customize mode. for use from customize mode only, do not use otherwise. parameters awindow the window entering customize mode notifyendcustomizing() notify listeners that a window is exiting customize mode. for use from customize mode only, do not use otherwise. parameters awindow the window exiting customize mode dispatchtoolboxevent() notify toolbox(es) of a particular event. if you don't pass awindow, all toolboxes will be notified. for use from customize mode only, do not use otherwise. parameters aevent the name of the event to send. adetails optional, the deta...
Activity Monitor, Battery Status Menu and top
ocesses with parent processes, which is useful, so it's the best one to use. the following screenshot shows a customized "energy" tab. the power-related columns are as follows. energy impact / avg energy impact: see the separate section below. % cpu: cpu usage percentage. this can exceed 100% if multiple cores are being used. idle wake ups: in mac os 10.9 this measured "package idle exit" wakeups. this is the same value as powermetrics' "pkg idle" measurement (i.e. task_power_info::task_platform_idle_wakeups obtained from the task_info function.) in mac os 10.10 it appears to have been changed to measure interrupt-level wakeups (a superset of idle wakeups), which are less interesting. this is the same value as powermetrics' "intr" measurement (i.e. task_power_info::task_interr...
... the power column's value is computed by the same formula as the one used for "energy impact" by activity monitor in mac os 10.9, and should also be avoided. top is unlikely to be much use for power profiling. ...
Profiling with the Firefox Profiler
function stack that you know from your debugger. it's only collected if the "stack walk" checkbox in the gecko profiler add-on's settings is checked. javascript stack the javascript stack is collected by the js engine. this is controlled by the "javascript" checkbox in the gecko profiler add-on's settings panel. label stack the label stack (formerly called "pseudo stack") uses function entry/exit tags added by hand to important points in the code base. the stacks you see in the ui are chains of these tags. this is good for highlighting particularly interesting parts of the code, but they miss out on un-annotated areas of the code base, and give no visibility into system libraries or drivers. tagging is done by adding macros of the form auto_profiler_label("namespace", "name"). these ad...
...tacks you see in the ui are chains of these tags. this is good for highlighting particularly interesting parts of the code, but they miss out on un-annotated areas of the code base, and give no visibility into system libraries or drivers. tagging is done by adding macros of the form auto_profiler_label("namespace", "name"). these add raii helpers, which are used by the profiler to track entries/exits of the annotated functions. for this to be effective, you need to liberally use auto_profiler_label throughout the code. see geckoprofiler.h for more variations like auto_profiler_label_dynamic. because of the non-zero overhead of the instrumentation, the sample label shouldn't be placed inside hot loops. a profile reporting that a large portion is spent in "unknown" code indicates that the a...
powermetrics
high frequency timers, which typically have short time-to-deadlines, can cause high power consumption and should be avoided if possible. wakeups (intr, pkg idle): these two columns count how many wakeups occurred, per second, during the sample period. the first column counts interrupt-level wakeups that resulted in a thread being dispatched in the process. the second column counts "package idle exit" wakeups, which wake up the entire package as opposed to just a single core; such wakeups are particularly expensive, and this count is a subset of the first column's count. gpu ms/s: gpu time used by the coalition/process, per second, during the sample period. other things to note. smaller is better — i.e. results in lower power consumption — for all of these measurements. there is so...
...irst column's count. gpu ms/s: gpu time used by the coalition/process, per second, during the sample period. other things to note. smaller is better — i.e. results in lower power consumption — for all of these measurements. there is some overlap between the two "deadlines" columns and the two "wakeups" columns. for example, firing a single sub-2ms deadline can also cause a package idle exit wakeup. many of these measurements are also obtainable by passing the task_power_info flag and a task_power_info struct to the task_info function. by default, the coalitions/processes are sorted by a composite value computed from several factors, though this can be changed via command-line options. other measurements powermetrics can also report measurements of backlight usage, network activ...
PR_Wait
d is being resumed from the pr_wait call either because it was explicitly notified or because the time specified by the parameter ticks has expired. pr_failure means pr_wait encountered a system error (such as an invalid monitor reference) or the thread was interrupted by another thread. description a call to pr_wait causes the thread to release the monitor's lock, just as if it had called pr_exitmonitor as many times as it had called pr_entermonitor. this has the effect of making the monitor available to other threads. when the wait is over, the thread regains control of the monitor's lock with the same entry count it had before the wait began. a thread waiting on the monitor resumes when the monitor is notified or when the timeout specified by the ticks parameter elapses. the resumption...
...ing a boolean expression involving the monitored data. while the boolean expression is false, the thread should wait. the thread should act on the data only when the expression is true. the boolean expression must be evaluated while in the monitor and within a loop. in pseudo-code, the sequence is as follows: pr_entermonitor(&ml); while (!expression) wait; ... act on the state change ... pr_exitmonitor(&ml); a thread can be resumed from a wait for a variety of reasons. the most obvious is that it was notified by another thread. if the value of timeout is not pr_interval_no_timeout, pr_wait resumes execution after the specified interval has expired. if a timeout value is used, the boolean expression must include elapsed time as part of the monitored data. resuming from the wait is merel...
Encrypt Decrypt MAC Keys As Session Objects
ac_header "-----begin mac-----" #define mac_trailer "-----end mac-----" #define pad_header "-----begin pad-----" #define pad_trailer "-----end pad-----" typedef enum { encrypt, decrypt, unknown } commandtype; typedef enum { symkey = 0, mackey = 1, iv = 2, mac = 3, pad = 4 } headertype; /* * print usage message and exit */ static void usage(const char *progname) { fprintf(stderr, "\nusage: %s -c -d [-z ] " "[-p | -f ] -i -o \n\n", progname); fprintf(stderr, "%-20s specify 'a' for encrypt operation\n\n", "-c "); fprintf(stderr, "%-20s specify 'b' for decrypt operation\n\n", " "); fprintf(stderr, "%-20s specify db directory path\n\n", ...
...; fprintf(stderr, "%-7s for encrypt, it takes as an input file and produces\n", "note :"); fprintf(stderr, "%-7s .enc and .header as intermediate output files.\n\n", ""); fprintf(stderr, "%-7s for decrypt, it takes .enc and .header\n", ""); fprintf(stderr, "%-7s as input files and produces as a final output file.\n\n", ""); exit(-1); } /* * gather a cka_id */ secstatus gathercka_id(pk11symkey* key, secitem* buf) { secstatus rv = pk11_readrawattribute(pk11_typesymkey, key, cka_id, buf); if (rv != secsuccess) { pr_fprintf(pr_stderr, "pk11_readrawattribute returned (%d)\n", rv); pr_fprintf(pr_stderr, "could not read symkey cka_id attribute\n"); return rv; } return rv; } /* * gene...
Encrypt and decrypt MAC using token
ac_header "-----begin mac-----" #define mac_trailer "-----end mac-----" #define pad_header "-----begin pad-----" #define pad_trailer "-----end pad-----" typedef enum { encrypt, decrypt, unknown } commandtype; typedef enum { symkey = 0, mackey = 1, iv = 2, mac = 3, pad = 4 } headertype; /* * print usage message and exit */ static void usage(const char *progname) { fprintf(stderr, "\nusage: %s -c -d [-z ] " "[-p | -f ] -i -o \n\n", progname); fprintf(stderr, "%-20s specify 'a' for encrypt operation\n\n", "-c "); fprintf(stderr, "%-20s specify 'b' for decrypt operation\n\n", " "); fprintf(stderr, "%-20s specify db directory path\n\n", ...
...; fprintf(stderr, "%-7s for encrypt, it takes as an input file and produces\n", "note :"); fprintf(stderr, "%-7s .enc and .header as intermediate output files.\n\n", ""); fprintf(stderr, "%-7s for decrypt, it takes .enc and .header\n", ""); fprintf(stderr, "%-7s as input files and produces as a final output file.\n\n", ""); exit(-1); } /* * gather a cka_id */ secstatus gathercka_id(pk11symkey* key, secitem* buf) { secstatus rv = pk11_readrawattribute(pk11_typesymkey, key, cka_id, buf); if (rv != secsuccess) { pr_fprintf(pr_stderr, "pk11_readrawattribute returned (%d)\n", rv); pr_fprintf(pr_stderr, "could not read symkey cka_id attribute\n"); return rv; } return rv; } /* * gene...
Enc Dec MAC Output Public Key as CSR
ng was available, support for it in nss wasn't. * fixme: samples should determine the version of nss that's available and refuse * to run if not 3.13 or higher. ...
...; fprintf(stderr, "%-7s for encrypt, it takes as an input file and produces\n", "note :"); fprintf(stderr, "%-7s .enc and .header as intermediate output files.\n\n", ""); fprintf(stderr, "%-7s for decrypt, it takes .enc and .header\n", ""); fprintf(stderr, "%-7s as input files and produces as a final output file.\n\n", ""); exit(-1); } /* map option letter enumerated commad type */ static commandtype option2command(const char* c) { switch (*c) { case 'g': return gen_csr; case 'e': return encrypt; case 'd': return decrypt; default: return unknown; } } /* * wrap the symkey using public key */ secstatus wrapkey(pk11symkey* key, seckeypublickey *pubkey, secitem **wrappedkey) { secstatus rv; ...
Encrypt Decrypt_MAC_Using Token
ac_header "-----begin mac-----" #define mac_trailer "-----end mac-----" #define pad_header "-----begin pad-----" #define pad_trailer "-----end pad-----" typedef enum { encrypt, decrypt, unknown } commandtype; typedef enum { symkey = 0, mackey = 1, iv = 2, mac = 3, pad = 4 } headertype; /* * print usage message and exit. */ static void usage(const char *progname) { fprintf(stderr, "\nusage: %s -c -d [-z ] " "[-p | -f ] -i -o \n\n", progname); fprintf(stderr, "%-20s specify 'a' for encrypt operation\n\n", "-c "); fprintf(stderr, "%-20s specify 'b' for decrypt operation\n\n", " "); fprintf(stderr, "%-20s specify db directory path\n\n", ...
... */ secstatus gathercka_id(pk11symkey* key, secitem* buf) { secstatus rv = pk11_readrawattribute(pk11_typesymkey, key, cka_id, buf); if (rv != secsuccess) { pr_fprintf(pr_stderr, "pk11_readrawattribute returned (%d)\n", rv); pr_fprintf(pr_stderr, "could not read symkey cka_id attribute\n"); return rv; } return rv; } /* * gen...
NSS Sample Code Sample_3_Basic Encryption and MACing
mac_header "-----begin mac-----" #define mac_trailer "-----end mac-----" #define pad_header "-----begin pad-----" #define pad_trailer "-----end pad-----" typedef enum { encrypt, decrypt, unknown } commandtype; typedef enum { symkey = 0, mackey = 1, iv = 2, mac = 3, pad = 4 } headertype; /* print a usage message and exit */ static void usage(const char *progname) { fprintf(stderr, "\nusage: %s -c <a|b> -d <dbdirpath> [-z <noisefilename>] " "[-p <dbpwd> | -f <dbpwdfile>] -i <ipfilename> -o <opfilename>\n\n", progname); fprintf(stderr, "%-20s specify 'a' for encrypt operation\n\n", "-c <a|b>"); fprintf(stderr, "%-20s specify 'b' for decrypt operation\n\n", ...
...2.0. if a copy of the mpl was not distributed with this * file, you can obtain one at http://mozilla.org/mpl/2.0/. */ /* nspr headers */ #include <prthread.h> #include <plgetopt.h> #include <prerror.h> #include <prinit.h> #include <prlog.h> #include <prtypes.h> #include <plstr.h> /* * gather a cka_id...
EncDecMAC using token object - sample 3
efine iv_header "-----begin iv-----" #define iv_trailer "-----end iv-----" #define mac_header "-----begin mac-----" #define mac_trailer "-----end mac-----" #define pad_header "-----begin pad-----" #define pad_trailer "-----end pad-----" typedef enum { encrypt, decrypt, unknown } commandtype; typedef enum { symkey = 0, mackey = 1, iv = 2, mac = 3, pad = 4 } headertype; /* * print usage message and exit */ static void usage(const char *progname) { fprintf(stderr, "\nusage: %s -c -d [-z ] " "[-p | -f ] -i -o \n\n", progname); fprintf(stderr, "%-20s specify 'a' for encrypt operation\n\n", "-c "); fprintf(stderr, "%-20s specify 'b' for decrypt operation\n\n", " "); fprintf(stderr, "%-20s specify db directory path\n\n", "-d "); fprintf(stderr, "%-20s specify db password [optional]\n\n", "-p "); fpri...
...", "-i "); fprintf(stderr, "%-21s specify an output file name\n\n", "-o "); fprintf(stderr, "%-7s for encrypt, it takes as an input file and produces\n", "note :"); fprintf(stderr, "%-7s .enc and .header as intermediate output files.\n\n", ""); fprintf(stderr, "%-7s for decrypt, it takes .enc and .header\n", ""); fprintf(stderr, "%-7s as input files and produces as a final output file.\n\n", ""); exit(-1); } /* * gather a cka_id */ secstatus gathercka_id(pk11symkey* key, secitem* buf) { secstatus rv = pk11_readrawattribute(pk11_typesymkey, key, cka_id, buf); if (rv != secsuccess) { pr_fprintf(pr_stderr, "pk11_readrawattribute returned (%d)\n", rv); pr_fprintf(pr_stderr, "could not read symkey cka_id attribute\n"); return rv; } return rv; } /* * generate a symmetric key */ pk11symkey * generate...
Tutorial: Embedding Rhino
distribution and in mozilla/js/rhino/examples in cvs. this document will link to them using lxr. in this document, javascript code will be in green, java code will be in green, and shell logs will be in purple. ...
...ation of the script looks up variables in scope, and errors will be reported with the filename <cmd> and line number 1. printing the result the code system.out.println(cx.tostring(result)); prints the result of evaluating the script (contained in the variable result). result could be a string, javascript object, or other values. the tostring method converts any javascript value to a string. exiting the context the code } finally { context.exit(); } exits the context. this removes the association between the context and the current thread and is an essential cleanup action. there should be a call to exit for every call to enter. to make sure that it is called even if an exception is thrown, it is put into the finally block corresponding to the try block starting after context.ente...
Rhino scopes and contexts
described below. contexts the rhino context object is used to store thread-specific information about the execution environment. there should be one and only one context associated with each thread that will be executing javascript. to associate the current thread with a context, simply call the enter method of context: context cx = context.enter(); once you are done with execution, simply exit the context: context.exit(); these calls will work properly even if there is already a context associated with the current thread. that context will be returned and an internal counter incremented. only when the counter reaches zero will it be disassociated from the thread. remember to put the exit() call in a finally block if you're executing code that could throw an exception. scopes a sc...
...scopes a scope is a set of javascript objects. execution of scripts requires a scope for top-level script variable storage as well as a place to find standard objects like function and object. it's important to understand that a scope is independent of the context that created it. you can create a scope using one context and then evaluate a script using that scope and another context (either by exiting the current context and entering another, or by executing on a different thread). you can even execute scripts on multiple threads simultaneously in the same scope. rhino guarantees that accesses to properties of javascript objects are atomic across threads, but doesn't make any more guarantees for scripts executing in the same scope at the same time. if two scripts use the same scope simultan...
Index
t is the value that was passed to the nargs parameter of js_definefunction. otherwise fun is implemented in javascript, and the result is the number of identifiers in its formal parameter list (see ecma 262-3 §13). 296 js_getfunctioncallback jsapi reference, obsolete, spidermonkey returns the callback currently configured to be called when javascript functions are invoked or exited, as established by a prior call to js_setfunctioncallback. 297 js_getfunctionflags jsapi reference, obsolete, spidermonkey js_getfunctionflags retrieves the function flags of a given javascript function, fun. these flags are for the javascript engine’s internal use. most applications can’t do anything useful with them. 298 js_getfunctionid jsapi reference...
...report structure when an error occurs and has been parsed by js_reporterror. js_seterrorreporter 456 js_setextragcroots jsapi reference, spidermonkey register externally maintained gc roots. 457 js_setfunctioncallback jsapi reference, obsolete, spidermonkey js_setfunctioncallback sets a c function to be called each time a javascript function is invoked or exits. 458 js_setgccallback jsapi reference, spidermonkey js_setgccallback sets a callback function which the garbage collector calls at several points during garbage collection. rt is the runtime in which you specify the callback. cb is a pointer to the new callback function to use. 459 js_setgcparametersbasedonavailablememory jsapi reference, reference, référenc...
Redis Tips
ashes heartbeats zsets hit counters zsets message broadcast pubsub search reverse indexes (never use keys in production) documentation redis has fantastic documentation. yet redis is so easy to learn and use that you'll seldom feel you need to consult it. there are three reasons to look at the docs for every command you use. time complexity - each command's complexity is given in big-o notation. this is immensely helpful. related commands - an ever-growing list of related commands is given on the right-hand side of the page. recipes - at the bottom of many pages is a section that gives usage patterns or recipes for the command under discussion. there are many insightful ideas to be found here. getting started with redis befo...
...es. i haven't yet used bitstrings in production myself. i recommend reading this article on realtime metrics with bitstrings: https://blog.getspool.com/2011/11/29/fast-easy-realtime-metrics-using-redis-bitmaps/. extra data in zsets the score for a zset value is a float. you can be clever and sneak extra data in by encoding something else after the decimal. this adds processing time and complexity for your application, but could save you space in redis for large data sets. so the score would be <score_number>.<extra_data_number>. my most favorite flavor my most favorite flavor in redis is the zset. zsets are a large part of the answer to most of life's problems. and more than that, they are just fucking awesome. fast, efficient, versatile, simple, powerful. talk to your doctor tod...
Gecko events
ived mouse capture. is supported: no event_capture_end a window has lost mouse capture. is supported: no event_movesize_start a window is being moved or resized. ...
...esize_end the movement or resizing of a window has finished is supported: no event_contexthelp_start a window has entered context-sensitive help mode is supported: no event_contexthelp_end a window has exited context-sensitive help mode is supported: no event_dragdrop_start an application is about to enter drag-and-drop mode is supported: yes event_dragdrop_end an application is about to exit drag-and-drop mode is supported: no event_dialog_start a dialog box has been displayed is supported: no event_dialog_end a dialog box has been closed is supported: no event_scrolling_start scrolling has started on a scroll bar is supported: yes event_scrolling_end scrolling has ended on a scroll bar is supported: yes event_minimize_start a window object is about to be minimized or maxim...
places.sqlite Database Troubleshooting
le into the work folder. open a terminal window and navigate to the work folder. then open an sqlite shell: my_work_folder> sqlite3 places.sqlite-corrupt sqlite> pragma integrity_check; if the result is ok, this guide won't help; stop here and please file a bug. sqlite> .clone places.sqlite sqlite> pragma user_version; note the version number returned by the last pragma query. sqlite> .exit open a new shell for the new database: my_work_folder> sqlite3 places.sqlite sqlite> pragma integrity_check; if the result is not ok, the file cannot be recovered; stop here and please file a bug. let's fix the schema version. nn must be replaced with the number we had noted previously: sqlite> pragma user_version = nn; let's update the page_size value: sqlite> pragma journal_mode = tr...
...ity_check; if the result is not ok, the file cannot be recovered; stop here and please file a bug. let's fix the schema version. nn must be replaced with the number we had noted previously: sqlite> pragma user_version = nn; let's update the page_size value: sqlite> pragma journal_mode = truncate; sqlite> pragma page_size = 32768; sqlite> vacuum; sqlite> pragma journal_mode = wal; sqlite> .exit copy the new places.sqlite to the profile folder, overwriting the existing one. remove the places.sqlite-corrupt file. launch firefox. if the database is still broken (missing history, creating -corrupt file, ...), please file a bug. ...
HOWTO
solution 1. ...
...anager;1"] .getservice(ci.nsithreadmanager); var mainthread = gthreadmanager.currentthread; while (!gscriptdone) mainthread.processnextevent(true); while (mainthread.haspendingevents()) mainthread.processnextevent(true); 2. in all callbacks where your script is finished, i.e. both success and error callbacks, put: gscriptdone = true; if you forget some condition where your script should exit but you don't add this statement, your script will hang (busy wait). this is of course a massive, ugly hack prone to error, but this is what the xpcshell test harness does. there should really be a better solution in xpcshell. using js modules and non-ui javascript chrome files problem you want to write a javascript file, and run it in xpcshell. the file uses js modules. maybe it even uses javasc...
nsIAnnotationObserver
id onpageannotationremoved(in nsiuri auri, in autf8string aname); void onpageannotationset(in nsiuri apage, in autf8string aname); methods onitemannotationremoved() this method is called when an annotation is deleted for an item. if aname is empty, then all annotations for the given item have been deleted. this is not called when annotations are expired (normally happens when the application exits). void onitemannotationremoved( in long long aitemid, in autf8string aname ); parameters aitemid the item whose annotation is to be deleted. aname the annotation name. onitemannotationset() this method is called when an annotation value is set for an item. it could be a new annotation, or it could be a new value for an existing annotation. void onitemannotationset( in long long aitemid,...
...mannotationset( in long long aitemid, in autf8string aname ); parameters aitemid the item on which the annotation is to be set. aname the annotation name. onpageannotationremoved() called when an annotation is deleted for a uri. if aname is empty, then all annotations for the given uri have been deleted. this is not called when annotations are expired (normally happens when the application exits). void onpageannotationremoved( in nsiuri auri, in autf8string aname ); parameters auri the uri whose annotation is to be deleted. aname the annotation name. onpageannotationset() this method is called when an annotation value is set for a uri. it could be a new annotation, or it could be a new value for an existing annotation. void onpageannotationset( in nsiuri apage, in autf8string...
nsIAnnotationService
expire_weeks 2 for general page settings, things the user is interested in seeing if they come back to this page some time in the near future. removed at 30 days. expire_months 3 something that the user will be interested in seeing in their history like favicons. if they haven't visited a page in a couple of months, they probably aren't...
...lean aoverwritedest); void addobserver(in nsiannotationobserver aobserver); void removeobserver(in nsiannotationobserver aobserver); nsiuri getannotationuri(in nsiuri auri, in autf8string aname); constants constant value description expire_session 0 for temporary data that can be discarded when the user exits. removed at application exit. expire_weeks 2 for general page settings, things the user is interested in seeing if they come back to this page some time in the near future. removed at 30 days. expire_months 3 something that the user will be interested in seeing in their history like favicons. if they haven't visited a page in a couple of months, they probably aren't interested in many other anno...
nsIMsgIncomingServer
ribute type description accountmanagerchrome astring read only. biffminutes long biffstate unsigned long canbedefaultserver boolean read only. cancompactfoldersonserver boolean read only. cancreatefoldersonserver boolean candelete boolean can this server be removed from the account manager? for instance, local mail is not removable, but an imported folder is. canemptytrashonexit boolean read only. canfilemessagesonserver boolean canhavefilters boolean read only. cansearchmessages boolean read only. canundodeleteonserver boolean read only. constructedprettyname astring helper function to construct the pretty name in a server type specific way - for example, mail for foo@test.com, news on news.mozilla.org. read only. defaultcopiesandfoldersprefstoserver boole...
... for nntp, the value is overridden to be false. if isps want to modify this value, they should do that in their rdf file by using this attribute. please look at mozilla/mailnews/base/ispdata/aol.rdf for usage example. displaystartuppage boolean dobiff boolean downloadmessagesatstartup boolean read only. downloadonbiff boolean downloadsettings nsimsgdownloadsettings emptytrashonexit boolean filterscope nsmsgsearchscopevalue read only. hostname acstring hostname of the server. incomingduplicateaction long isdeferredto boolean read only. issecure boolean issecureserver boolean read only. key acstring internal pref key - guaranteed to be unique across all servers. limitofflinemessagesize boolean localpath nsilocalfile localstoretype acstring the sc...
Using the Multiple Accounts API
h to store messages and folder indexes preference: mail.server.server.name - user-visible name of server the following are specific to imap: preference: mail.server.server.admin_url - administration url for server preference: mail.server.server.using_subscription - boolean, should we use subscriptions? (i.e. ...
...l for server preference: mail.server.server.using_subscription - boolean, should we use subscriptions? (i.e. ...
Web Console remoting - Firefox Developer Tools
nse). the prefs argument is an array of preferences you want to get their values for, by name. private browsing the browser console can be used while the user has private windows open. each page error, console api message and network request is annotated with a private flag. private messages are cleared whenever the last private window is closed. the console actor provides the lastprivatecontextexited notification: { "from": "conn0.console19", "type": "lastprivatecontextexited" } this notification is sent only when your client is attached to the global console actor, it does not make sense for tab console actors. this notification has been introduced in firefox 24. send http requests starting with firefox 25 you can send an http request using the console actor: { "to": "conn0.
...ket and updated the tabnavigated packet for tab actors. firefox 23: bug 783499 - removed the webconsoleobjectactor. now the web console uses the javascript debugger api and the objectactor. firefox 23: added the bindobjectactor and frameactor options to the evaluatejs request packet. firefox 24: new private flags for the console actor notifications, bug 874061. also added the lastprivatecontextexited notification for the global console actor. firefox 24: new isxhr flag for the networkevent notification, bug 859046. firefox 24: removed the message property from the pageerror packet notification, bug 877773. the linetext and errormessage properties can be long string actors now. firefox 25: added the url option to the evaluatejs request packet. firefox 25: added the getpreferences and sen...
Using the CSS Painting API - Web APIs
units from the left and 15 units from the top of the content box. we can use the css background-size and background-position properties to re-size or relocate this background image, but this is the default size and placement of the yellow box we created in our paint worklet. we tried to keep the example simple. for more options, look at the canvas documentation. we also add a little bit of complexity later in this tutorial. using the paint worklet to use the paint worklet, we need to register it using addmodule() and include it in our css, ensuring the css selector matches a dom node in our html registering the worklet the setup and design of our paint worklet took place in the external script shown above. we need to register that worklet from our main script. css.paintworklet.addmodule...
...rties() method can return all properties affecting the element, not just custom properties. in our <script> we register the worklet: css.paintworklet.addmodule('https://mdn.github.io/houdini-examples/csspaint/intro/worklet/boxbg.js'); while you can't play with the worklet's script, you can alter the custom property values to change the colors and width of the background image. adding complexity the above examples might not seem very exciting, as you could recreate them in a few different ways with existing css properties, e.g. by positioning some decorative generated content with ::before, or including background: linear-gradient(yellow, yellow) 0 15px / 200px 20px no-repeat; what makes the css painting api so interesting and powerful is that you can create complex images, passing var...
console - Web APIs
Web › API › Console
ew inline group, indenting all following output by another level. to move back out a level, call groupend(). console.groupcollapsed() creates a new inline group, indenting all following output by another level. however, unlike group() this starts with the inline group collapsed requiring the use of a disclosure button to expand it. to move back out a level, call groupend(). console.groupend() exits the current inline group. console.info() informative logging of information. you may use string substitution and additional arguments with this method. console.log() for general output of logging information. you may use string substitution and additional arguments with this method. console.profile() starts the browser's built-in profiler (for example, the firefox performance tool). you ...
...margin, etc. you should set it to for example display: inline-block. using groups in the console you can use nested groups to help organize your output by visually combining related material. to create a new nested block, call console.group(). the console.groupcollapsed() method is similar but creates the new block collapsed, requiring the use of a disclosure button to open it for reading. to exit the current group, simply call console.groupend(). for example, given this code: console.log("this is the outer level"); console.group("first group"); console.log("in the first group"); console.group("second group"); console.log("in the second group"); console.warn("still in the second group"); console.groupend(); console.log("back to the first group"); console.groupend(); console.debug("back to...
DragEvent - Web APIs
Web › API › DragEvent
ag-and-drops. dragevent() creates a synthetic and untrusted dragevent. event types drag this event is fired when an element or text selection is being dragged. dragend this event is fired when a drag operation is being ended (by releasing a mouse button or hitting the escape key). dragenter this event is fired when a dragged element or text selection enters a valid drop target. dragexit this event is fired when an element is no longer the drag operation's immediate selection target. dragleave this event is fired when a dragged element or text selection leaves a valid drop target. dragover this event is fired continuously when an element or text selection is being dragged and the mouse pointer is over a valid drop target (every 50 ms when mouse is not moving else much faster...
...t or text selection. drop this event is fired when an element or text selection is dropped on a valid drop target. globaleventhandlers globaleventhandlers.ondrag a global event handler for the drag event. globaleventhandlers.ondragend a global event handler for the dragend event. globaleventhandlers.ondragenter a global event handler for the dragenter event. globaleventhandlers.ondragexit a global event handler for the dragexit event. globaleventhandlers.ondragleave a global event handler for the dragleave event. globaleventhandlers.ondragover a global event handler for the dragover event. globaleventhandlers.ondragstart a global event handler for the dragstart event. globaleventhandlers.ondrop a global event handler for the drop event. example an example of each prope...
TextTrack.mode - Web APIs
Web › API › TextTrack › mode
r navigating the named chapters, where each cue in the list represents a chapter in the media. the user can then navigate to the desired chapter, which begins at the cue's start position and ends at the cue's end position. example in this example, we configure the text track's cues so that every time a cue is finished, the video automatically pauses playback. ...
...setting the pauseonexit property on each cue to true. however, to ensure that the track's cues are available, we first set mode to showing. window.addeventlistener("load", event => { let trackelem = document.queryselector("track"); let track = trackelem.track; track.mode = "showing"; for (let index=0; index < track.cues.length; index++) { let cue = track.cues[index]; cue.pauseonexit = true; }; }); specifications specification status comment html living standardthe definition of 'mode' in that specification. living standard ...
Using bounded reference spaces - Web APIs
in and boundary, it may initialize any uninitialized values to match that predefined information; this is not unexpected behavior for users of these platforms. the space inside the boundary is then the user's safe movement area, within which they are tracked and their movements replicated into the virtual world. although the user's xr system may provide automated detection and protection against exiting the safe area, it is always good practice to handle this yourself, watching for collisions between the user's position and the boundary of the world, and providing guidance to move back toward the origin point, or at least to stay inside the safe zone. xr hardware that does not have an inherent boundary defined may or may not support the bounded reference space. if it does, it likely has a sy...
...the options specified when requesting the session indicate that at a minimum, the session must be compatible with the local-floor reference space, but that it would be nice if the bounded-floor space were supported as well. once the session has been created, our startsessionanimation() function ca...
Lighting a WebXR setting - Web APIs
ng some intricate math that factors in things like: the color of the texture element (the pixel within the texture mapped onto the object; also known as a texel) corresponding to the screen pixel, given the object geometry, the viewer position and orientation relative to each polygon, and so forth. the viewer position and distance. the surface material and reflectivity. the concavity or convexity of the surface at the target location. the position, color, directionality, and brightness of each light source in the scene. the color and brightness of any ambient light in the scene; this is light which is applied equally throughout the scene, with no source and thus no shadows or variation in brightness. the effect of light reflected off of other surfaces within the scene; the color, dire...
...; however, depending on factors such as whether or not the avatar can be seen and the materials, texturing, and other attributes of the its model—including, especially, its reflectivity—the avatar may also need to reflect light, as well as potentially affect the coloration of the light reflected off of it. realism in augmented reality augmented reality introduces an additional level of complexity to lighting your objects, since your virtual objects need to exist within a physical world that has its own light sources. as such, you should try to match your lighting to the real world's light sources as much as possible. this is done using a technique known as lighting estimation. conversely, you should try to avoid having virtual objects that are themselves light sources, unless you're pre...
WindowOrWorkerGlobalScope.setInterval() - Web APIs
<title>javascript typewriter - mdn example</title> <script> function typewriter (sselector, nrate) { function clean () { clearinterval(nintervid); btyping = false; bstart = true; ocurrent = null; asheets.length = nidx = 0; } function scroll (osheet, npos, beraseandstop) { if (!osheet.hasownproperty('parts') || amap.length < npos) { return true; } var orel, bexit = false; if (amap.length === npos) { amap.push(0); } while (amap[npos] < osheet.parts.length) { orel = osheet.parts[amap[npos]]; scroll(orel, npos + 1, beraseandstop) ? amap[npos]++ : bexit = true; if (beraseandstop && (orel.ref.nodetype - 1 | 1) === 3 && orel.ref.nodevalue) { bexit = true; ocurrent = orel.ref; spart = ocurrent.nodevalue; ...
...t.parts.length) { orel = osheet.parts[amap[npos]]; scroll(orel, npos + 1, beraseandstop) ? ...
A hybrid approach - Developer guides
top use cases are similar enough, this is definitely the preferred option for layout changes. however, it can be a pain to use client-side techniques to alter site content to fit the user’s context. luckily, we aren’t technically constrained to using client-side techniques here: another option is to use server-side user-agent detection to show the user the proper content. this keeps the complexity of altering content on the server side, but still allows our layouts to benefit from the flexibility and future-readiness of responsive design. using user-agent detection specifically for content and not layout also allows you to have a single url for each piece of content, so that the content can adapt its layout to the user’s browser. this is generally thought to be a good thing. instead of...
... a retrofit. similarly, because it uses user-agent detection, you will have to update your detection rules as time goes on. when it is right to choose this option combining server-side and client-side techniques is something that is always worth considering; there are so many options that one must just weigh the pros and cons of each individual technique employed. in many cases, the added complexity of the hybrid approach is not even necessary. for example, you may not even need to adjust your content based on what actual device a user is using — just knowing whether a feature is present on their browser is often good enough. this is something you might be able to discern on the client-side using javascript feature detection from modernizr or detect it. it can’t hurt to dig down and as...
A re-introduction to JavaScript (JS tutorial) - JavaScript
veral months after that, netscape submitted javascript to ecma international, a european standards organization, which resulted in the first edition of the ecmascript standard that year. the standard received a significant update as ecmascript edition 3 in 1999, and it has stayed pretty much stable ever since. the fourth edition was abandoned, due to political differences concerning language complexity. many parts of the fourth edition formed the basis for ecmascript edition 5, published in december of 2009, and for the 6th major edition of the standard, published in june of 2015. because it is more familiar, we will refer to ecmascript as "javascript" from this point on. unlike most programming languages, the javascript language has no concept of input or output. it is designed to run as ...
...is so widely used is a testament to its versatility. since everything (bar core types) in javascript is an object, any javascript program naturally involves a great deal of hash table lookups. it's a good thing they're so fast! the "name" part is a javascript string, while the value can be any javascript value — including more objects. this allows you to build data structures of arbitrary complexity. there are two basic ways to create an empty object: var obj = new object(); and: var obj = {}; these are semantically equivalent; the second is called object literal syntax and is more convenient. this syntax is also the core of json format and should be preferred at all times. object literal syntax can be used to initialize an object in its entirety: var obj = { name: 'carrot', fo...
Functions - JavaScript
code multiple times, and both require a condition (to avoid an infinite loop, or rather, infinite recursion in this case). for example, the following loop... var x = 0; while (x < 10) { // "x < 10" is the loop condition // do stuff x++; } ...can be converted into a recursive function declaration, followed by a call to that function: function loop(x) { if (x >= 10) // "x >= 10" is the exit condition (equivalent to "!(x < 10)") return; // do stuff loop(x + 1); // the recursive call } loop(0); however, some algorithms cannot be simple iterative loops. for example, getting all the nodes of a tree structure (such as the dom) is easier via recursion: function walktree(node) { if (node == null) // return; // do something with node for (var i = 0; i < node.childnodes.
...tion() { return apicode; }; })(); getcode(); // returns the apicode caution: there are a number of pitfalls to watch out for when using closures! if an enclosed function defines a variable with the same name as a variable in the outer scope, then there is no way to refer to the variable in the outer scope again. (the inner scope variable "overrides" the outer one, until the program exits the inner scope.) var createpet = function(name) { // the outer function defines a variable called "name". return { setname: function(name) { // the enclosed function also defines a variable called "name". name = name; // how do we access the "name" defined by the outer function? } } } using the arguments object the arguments of a function are maintained ...
InternalError - JavaScript
raised this error. inherited from error. internalerror.prototype.linenumber line number in file that raised this error. inherited from error. internalerror.prototype.columnnumber column number in line that raised this error. inherited from error. internalerror.prototype.stack stack trace. inherited from error. ...
...umber line number in file that raised this error. inherited from error. internalerror.prototype.columnnumber column number in line that raised this error. inherited from error. internalerror.prototype.stack stack trace. inherited from error. examples too much recursion this recursive function runs 10 times, as per the exit condition. function loop(x) { if (x >= 10) // "x >= 10" is the exit condition return; // do stuff loop(x + 1); // the recursive call } loop(0); setting this condition to an extremely high value, won't work: function loop(x) { if (x >= 1000000000000) return; // do stuff loop(x + 1); } loop(0); // internalerror: too much recursion for more information, see internalerror: too much recursion. specifications not part of any standard. ...
Web audio codec guide - Web media technologies
audio size, depending on contents and encoder settings. noise / hiss unwanted background noise or hiss tends to reduce audio quality both directly (by masking details of the foreground audio) and indirectly (by making the audio waveform more complicated and therefore difficult to reduce in size while maintaining precision). hiss, static, or background noise increases the audio complexity, which generally reduces the amount of compression which is possible. sample rate the more samples available per second, the higher the resulting encoded audio fidelity is likely to be. increasing the sample rate increases the encoded audio file's size. sample size the larger the samples, the more detail each sample can contain, resulting in more accurate representatio...
...refox version with mp3 support windows (vista and later) 22 android 20 linux (depends on gstreamer) 26 macos 35 opus the opus audio format was created by the xiph.org foundation as a fully open audio format; it has been standardized by ietf as rfc 6716. it's a good general-purpose audio codec that can efficiently handle both low-complexity audio such as speech as well as music and other high-complexity sounds. opus supports multiple compression algorithms, and can even use more than one algorithm in the same audio file, since the encoder can choose the bit rate, audio bandwidth, algorithm, and other details of the compression settings for each frame of audio. opus is a good all-around audio codec for use in your web applications...
Codecs used by WebRTC - Web media technologies
is, pixels with an aspect ratio of 1:1). other notes the network payload format for sharing vp8 using rtp (such as when using webrtc) is described in rfc 7741: rtp payload format for vp8 video. avc / h.264 support for avc's constrained baseline (cb) profile is required in all fully-compliant webrtc implementations. cb is a subset of the main profile, and is specifically designed for low-complexity, low-delay applications such as mobile video and videoconferencing, as well as for platforms with lower performing video processing capabilities. our overview of avc and its features can be found in the main video codec guide. special parameter support requirements avc offers a wide array of parameters for controlling optional values. in order to improve reliability of webrtc media sharing ac...
... payload format for opus is found in rfc 7587. you can find more general information about opus and its capabilities, and how other apis can support opus, in the corresponding section of our guide to audio codecs used on the web. both the speech and general audio modes should be supported. opus's scalability and flexibility are useful when dealing with audio that may have varying degrees of complexity. its support of in-band stereo signals allows support for stereo without complicating the demultiplexing process. the entire range of bit rates supported by opus (6 kbps to 510 kbps) is supported in webrtc, with the bit rate allowed to be dynamically changed. higher bit rates typically improve quality. bit rate recommendations given a 20 millisecond frame size, the following table shows the r...
The "codecs" parameter in common media types - Web media technologies
and in the case of the more common object ypes provides a list of the profiles supporting it, but you should refer to the specification for details if you need to know more about the inner workings of any given mpeg-4 audio type. ...
...tion coding) main, scalable, speech, ld 10 – 11 reserved 12 ttsi (text to speech interface) main, scalable, speech, synthetic, ld 13 main synthetic main, synthetic 14 wavetable synthesis 15 general midi 16 algorithmic synthesis and audio effects 17 er aac lc (error resilient aac low-complexity) hq, mobile internetworking 18 reserved 19 er aac ltp (error resilient aac long term prediction) hq 20 er aac scalable (error resilient aac scalable) mobile internetworking 21 er twinvq (error resilient twinvq) mobile internetworking 22 er bsac (error reslient bit-sliced arithmetic coding) mobile internetworking ...
Content Processes - Archive of obsolete content
lementing 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 chrome privileges simply by asking for them, whereas content scripts have the same privileges as the page it is running on. when two sandboxes have the same privileges, a wrapper in one sandbox provides transparent access to an object in the other sandbox. when the two sandboxes have d...
XUL Migration Guide - Archive of obsolete content
overlays xul overlays are used to modify existing windows such as the main browser window. in this way an extension can integrate its user interface into the browser: for example, adding menu items, buttons, and toolbars. because sdk-based extensions are restartless, they can't use xul overlays. to add user interface components to the browser, there are a few different options. in order of complexity, the main options are: the sdk includes modules that implement some basic user interface components including buttons, dialogs, and context menu items. there is a collection of community-developed modules that includes various user interface components. by using the sdk's low-level apis you can directly modify the browser chrome. xul windows xul windows are used to define ...
widget - Archive of obsolete content
, etc.) can be used here. optional. port object that allows you to: send events to the content script using the port.emit function receive events from the content script using the port.on see the guide to communicating using port for details. events detach the detach event is fired when the widget view is removed from its related window. this can occur if the window is closed, firefox exits, or the add-on is disabled. click this event is emitted when the widget view is clicked. message if you listen to this event you can receive message events from content scripts associated with this widget view. when a content script posts a message using self.postmessage(), the message is delivered to the add-on code in the widget view's message event. arguments value : listeners are passe...
system/child_process - Archive of obsolete content
const { emit } = require('sdk/event/core'); const { spawn } = require('sdk/system/child_process'); var proc = spawn("/bin/cat"); emit(proc.stdin, 'data', "hello from add-on code"); emit(proc.stdin, 'end'); using ...
cfx - Archive of obsolete content
package add-ons. cfx is is no longer supported as of firefox 44 and no longer accepted for add-on submission, jpm should now be used instead. cfx usage is: cfx [options] command [command-specific options] "options" are global options applicable to the tool itself or to all commands (for example --help). cfx supports the following global options: -h, --help - show a help message and exit -v, --verbose - enable lots of output "command-specific options" are documented alongside the commands. there are four supported cfx commands: cfx init create a skeleton add-on as a starting point for your own add-on. cfx run launch an instance of firefox with your add-on installed. cfx test runs your add-on's unit tests. cfx xpi package y...
jpm-mobile - Archive of obsolete content
you can use jpm and jpm-mobile for firefox 38 and onwards. this article is the reference for jpm-mobile. the node-based replacement for cfx --force-mobile. enables you to run and test add-ons for firefox mobile (aka fennec). jpm usage is: jpm-mobile [command] [options] jpm supports the following global options: -h, --help - show a help message and exit -v, --version - print the jpm version number installation jpm-mobile is distributed using the node package manager npm, so to get jpm-mobile you need to have npm installed, if you haven't already. npm is included in node.js, so to install npm, visit nodejs.org and click the install button. after that you can install jpm just as you would any other npm package: npm install jpm-mobile -g depending on your setup, you mig...
jpm - Archive of obsolete content
jpm is a command-line tool that enables you to test, run, and package add-ons. this is the reference page for jpm. see also jpm tutorial for getting started. jpm usage is: jpm [command] [options] jpm supports the following global options: -h, --help - show a help message and exit -v, --version - print the jpm version number --addon-dir - directory for your source code, defaulting to the current directory installation jpm is distributed with the node package manager npm. installing npm there are two ways to get npm. download and install node.js from nodejs.org. node.js includes npm. or, if you have a package manager like apt, install npm via that. for example, in an ubuntu or debian terminal window, enter sudo apt-get install node...
Storing annotations - Archive of obsolete content
lick the widget again, and check that the annotation is still there. until now we've always run cfx run rather than building an xpi and installing the add-on in firefox. if the annotation does not reappear when you restart firefox, double check you installed the add-on and didn't just use cfx run again. responding to overquota events add-ons have a limited quota of storage space. if the add-on exits while it is over quota, any data stored since the last time it was in quota will not be persisted. so we want to listen to the overquota event emitted by simple-storage and respond to it. add the following to your add-on's main function: simplestorage.on("overquota", function () { notifications.notify({ title: 'storage space exceeded', text: 'removing recent annotations'}); while (...
Using third-party modules (jpm) - Archive of obsolete content
add-on: jpm run -b nightly you should see a new menu item in the tools menu labeled "click me!". click the button, and the message "clicked" is logged. note: in more recent versions of firefox, the menu bar may not be visible by default. to show the menu bar, click on the open menu icon and select "customize". then, under show / hide toolbars, enable the menu bar. finally, click the green bar "exit customize" ...
Enhanced Extension Installation - Archive of obsolete content
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 storage format the rdf/xml datasource back end creates unneccessary and undesirable complexity when saving data. it also makes it more difficult to support multiple instances of a single extension at different install locations due to the singleton nature of rdf resources. extension metadata is structured and not relational in the sense encouraged by rdf, and so a simple text storage format is probably desirable. making the database file format human readable would also help developers de...
Appendix D: Loading Scripts - Archive of obsolete content
new window where they would be better loaded only once globally per session. because sandbox objects are evaluated in their own javascript compartment, they are separated by a membrane from other javascript code. this means that any and all javascript objects passed in our out of them are wrapped in inter-compartment proxy objects, which consume additional memory and add an extra layer of complexity to all property accesses and method calls. javascript compartments: as noted above, each sandbox executes in its own javascript compartment. in addition to the possible performance concerns, passing data between these compartments is not entirely transparent. some known issues include: e4x xml objects cannot be wrapped for passage between compartments: bug 613142 there are a numbe...
Getting Started with Firefox Extensions - Archive of obsolete content
ifferent forms: add-ons sdk extensions (also known as jetpacks), bootstrapped extensions and traditional extensions. if you're only getting started developing add-ons, the add-ons sdk provides a great way to quickly create simple ones and build on them. this tutorial focuses on traditional extensions, which are created differently. bootstrapped extensions are a step above traditional ones in complexity, so you should go through this tutorial before giving them a try. we'll begin the tutorial by analyzing a very simple extension. the hello world extension our sample extensions and this tutorial in general are meant for modern versions of firefox, but most of it works on older versions too. we'll now begin with a basic "hello world" extension. let's start by installing it. click on the link ...
Performance best practices in extensions - Archive of obsolete content
e synchronous xmlhttprequests. netutils.jsm provides helpers for asynchronous reading and copying of files. never access a sqlite database synchronously. use the asynchronous api instead. performing sequential, asynchronous operations can often be greatly simplified using promises. avoid mouse movement events avoid using mouse event listeners, including mouseover, mouseout, mouseenter, mouseexit, and especially mousemove. these events happen with high frequency, so their listeners can trivially create very high cpu overhead. when these events cannot be avoided, computation during the listeners should be kept to a minimum and real work throttled. the listeners should be added to the most specific element possible, and removed when not immediately necessary. avoid animated images animat...
Signing an XPI - Archive of obsolete content
re-enter password: create a test certificate create a test certificate, using the -p option to set a password for the new certificate c:\projects\codesigning\> signtool -g mytestcert -d . -p"password" using certificate directory: . warning: performing this operation while the browser is running could cause corruption of your security databases. if the browser is currently running, you should exit the browser before continuing this operation. enter "y" to continue, or anything else to abort: y enter certificate information. all fields are optional. acceptable characters are numbers, letters, spaces, and apostrophes. certificate common name: xpi test organization: tjworld organization unit: software state or province: nottingham country (must be exactly 2 characters): gb username: tj ema...
Promises - Archive of obsolete content
r reading, writing, and manipulating both text and binary files. it is also available for use off-main-thread in workers as a synchronous api. this interface replaces the previous, complicated xpcom nsifile and streams apis, and their related javascript helper modules. these older interfaces should be avoided, even in their asynchronous forms, due to their performance penalties and needless complexity. representative example usage components.utils.import("resource://gre/modules/osfile.jsm"); task.spawn(function* () { // retrieve file metadata to check modification time. let info = yield os.file.stat(configpath); if (info.lastmodificationdate <= timestamp) return; timestamp = info.lastmodificationdate; // read the file as a utf-8 string, parse as json. let ...
An Interview With Douglas Bowman of Wired News - Archive of obsolete content
le information from browsers that can't support css adequately enough. what are the browser percentages of your current user base, and what about your target user base (which may be different)? will the majority of your users be viewing your pages with a newer, standards-compliant browser? going through the initial conversion may take longer for some sites, depending on the organization and complexity of the data. pages which draw their content from a database will probably require less labor to convert than sorting through hundreds of flat html files that have mixed structures. whatever the situation, if the conversion is something deemed worthwhile, it's an excellent opportunity to restructure your data the right way, so it can ultimately be as flexible as you need it to be. original docu...
Index - Archive of obsolete content
rious reorganization. 3416 bypassing security restrictions and signing code security, web development early versions of firefox allowed web sites to segregate principals using signed scripts, and request extra permissions for scopes within signed scripts using a function called enableprivelege. these privilege manager feature was not used much (aside from abuse), and its complexity made performance improvements difficult. signed script segregation was removed in bug 726125, the enableprivilege prompt was removed in bug 750859, and enableprivilege itself was nerfed in bug 757046. 3417 creating a web based tone generator this example creates a simple tone generator, and plays the resulting tone. the function requestsounddata() produces the samples to be...
MMgc - Archive of obsolete content
can't find anything wrong with the code, it might just be a false positive. debugging aids mmgc has several debugging aids that can be useful in your development work. underwrite/overwrite detection mmgc can often detect when you write outside the boundaries of an object, and will throw an assert in debugging builds when this happens. leak detection (for unmanaged memory) when the application is exiting, mmgc will detect memory leaks in its unmanaged memory allocators and print out the addresses and sizes of the leaked objects, and stack traces if stack traces are enabled. stack traces are enabled via the mmgc_memory_profiler feature and setting the mmgc_profile environment variable to 1. the mmgc_memory_profiler feature is implied by the debugger feature and is always on in debug builds. de...
Bypassing Security Restrictions and Signing Code - Archive of obsolete content
early versions of firefox allowed web sites to segregate principals using signed scripts, and request extra permissions for scopes within signed scripts using a function called enableprivelege. these privilege manager feature was not used much (aside from abuse), and its complexity made performance improvements difficult. signed script segregation was removed in bug 726125, the enableprivilege prompt was removed in bug 750859, and enableprivilege itself was nerfed in bug 757046. the privilege manager has been deprecated in firefox 12 and disabled in firefox 17. sites that require additional permissions should now ask firefox users to install an extension, which can interact with non-privileged pages if needed. ...
Creating a Web based tone generator - Archive of obsolete content
ion() { var written; // check if some data was not written in previous attempts. if(tail) { written = audio.mozwriteaudio(tail); currentwriteposition += written; if(written < tail.length) { // not all the data was written, saving the tail... tail = tail.subarray(written); return; // ... and exit the function. } tail = null; } // check if we need add some data to the audio output. var currentposition = audio.mozcurrentsampleoffset(); var available = currentposition + prebuffersize - currentwriteposition; if(available > 0) { // request some sound data from the callback function. var sounddata...
Getting Started - Archive of obsolete content
install.rdf make a copy of install.rdf and place it in the my_theme directory, then open it up in your text editor. this file is a small xml database that describes the skin. <description about="urn:mozilla:install-manifest"> <em:id>{themes_uuid}</em:id> <em:version>themes_version</em:version> the first section requires that you establish a uuid for your theme and that you...
Getting Started - Archive of obsolete content
the jar file in the \myskin directory, you should now have the 5 sub-directories along with the contents.rdf and preview.png files. select them all and zip them up, making sure to include the paths (do not include the \myskin directory inside of the zip, just the files inside of \myskin). once the zip is created, rename it to myskin.jar contents of myskin.jar co...
Creating a Skin for Firefox/Getting Started - Archive of obsolete content
dify the blue text to point to match the name/version that you used in the sections before this. <rdf:li resource="urn:mozilla:skin:my_theme:communicator"/> <rdf:li resource="urn:mozilla:skin:my_theme:editor"/> <rdf:li resource="urn:mozilla:skin:my_theme:global"/> <rdf:li resource="urn:mozilla:skin:my_theme:messenger"/> <rdf:li resource="urn:mozilla:skin:my_theme:navigator"/> save the file and exit the text editor. install.rdf make a copy of install.rdf and place it in the my_theme directory, then open it up in your text editor. this file is a small xml database that describes the skin. <description about="urn:mozilla:install-manifest"> <em:id>{themes_uuid}</em:id> <em:version>themes_version</em:version> the first section requires that you establish a uuid for your theme and that...
Download Manager preferences - Archive of obsolete content
default value is true. browser.download.usedownloaddir a boolean value that indicates whether or not the user's preference is to automatically save files into the download directory. if this value is false, the user is asked what to do. in thunderbird and seamonkey the default is false. in other applications the default is true. browser.helperapps.deletetempfileonexit a boolean value that indicates whether or not to delete the temporary file used by the download manager after the download is complete. on mac the default value is false. on other oses the default value is true if a preference 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 f...
Drag and Drop - Archive of obsolete content
led for an element when something is being dragged over top of it. if the object can be dropped on the element, the drag session should be notified. ondragenter called for an element when the mouse pointer first moves over the element while something is being dragged. this might be used to change the appearance of the element to indicate to the user that the object can be dropped on it. ondragexit called for an element when the mouse pointer moves out of an element while something is being dragged. the is also called after a drop is complete so that an element has a chance to remove any highlighting or other indication. ondragdrop this event handler is called for an element when something is dropped on the element. at this point, the user has already released the mouse button. the ele...
Embedding Mozilla in a Java Application using JavaXPCOM - Archive of obsolete content
in order to communicate with xpcom after this point, you should use an nsiproxyobjectmanager. following on from the above example, to create a new window, we would do the following: // first, get the event queue service. this handles all event queues in xpcom. nsieventqueueservice eventqueueservive = (nsieventqueueservice)servicemanager.getservicebycontractid("@mozilla.org/event-queue-serv...
Makefile.mozextension.2 - Archive of obsolete content
ho = @ rm_rf=rm -f cp=/bin/cp -i .phony: all all :: make_structure make_files $(noecho) $(noop) package:: make_xpi $(noecho) $(noop) #install :: make_xpi make_install # $(noecho) $(noop) clean :: make_clean $(noecho) $(noop) make_structure: @$(mkdir) $(project) || { echo "creating directory failed; it probably exists. ...
Mozilla Application Framework in Detail - Archive of obsolete content
support for the first time makes it possible to implement powerful web applications with rich user interfaces without using proprietary or platform dependent code. because gecko has a cross-platform architecture, is easily embeddable and is open source, it and the rich web applications it supports will be usable on any supported platform or device. this will dramatically reduce the cost and complexity of developing and distributing rich web applications and full-functionality browsing devices that run them. by meeting the needs of developers and companies who are working to provide consumers with new interactive applications, solutions and services, gecko will become a key catalyst for new growth and innovation and for delivering anytime, anywhere access to millions of new users. as the heart...
Remote debugging - Archive of obsolete content
omputer. a good place to start is a detailed stack (in gdb, use bt followed by bt full). there give more information about the stack than a breakpad crash report: not only the names of the functions on the stack, but also the values they were passed. core dump a core dump includes all of the memory of a crashed program. it allows you to see the crash in a debugger even after the program has long exited. transferring a core dump is tricky, because it is large and can contain private information. core dumps on mac and linux to generate a core dump on mac, type "ulimit -c unlimited", run firefox from the command line, and make firefox crash. when firefox crashes, a core will be placed in /cores. you can then load the core file into gdb (gdb firefox-bin corefile), and it will be as if you caught ...
Table Cellmap - Archive of obsolete content
. a typical code segment to come from the table level down to the rowgroup level nscellmap* map = mfirstmap; while (map) { if (map->getrowcount() > rowindex) { // add your action here } rowindex -= map->getrowcount(); map = map->getnextsibling(); } data entry the usual way to populate the cellmap is via nstableframe::insertrows. enabling the debug code at the function entrance and exit gives a quite complete picture of the cellmap structure. below follows the dump for the 2x2 table. insertrowsbefore firstrow=0 ***start table dump*** mcolwidths= row(0)=02763344 cell(0)=02763528 cell(0)=0276381c row(0)=02763940 cell(0)=02763990 cell(0)=02763ab4 ***** start table cell map dump ***** 023566b0 cols array orig/span-> 023566b0 ***** start group cell map dump ***** 023565b0 maprow...
Tamarin build documentation - Archive of obsolete content
reate the necessary 'libcrypto.a' and 'libssl.a' static libraries. alternatively, run make, in which case the process will complete with errors when it tries to create the shared lib crt0.o: $ /android-public/android-ndk/toolchains/arm-eabi-4.4.0/prebuilt/darwin-x86/bin/../lib/gcc/arm-eabi/4.4.0/../../../../arm-eabi/bin/ld: crt0.o: no such file: no such file or directory collect2: ld returned 1 exit status make[2]: *** [link_app.] error 1 make[1]: *** [openssl] error 2 make: *** [build_apps] error 1 you can ignore these errors. the necessary static files 'libcrypto.a' and 'libssl.a' are made correctly and are present in the /openssl folder. more information on why this happens on mac os is here: http://developer.apple.com/library/mac/#qa/qa2001/qa1118.html - create a /frameworks/base/openg...
Venkman Introduction - Archive of obsolete content
giving you [boolean] false back. press step into to follow the steps until you have finished debugging the function, and the fishes have paused. in addition to step in, which will execute a single line of javascript and stop, step over can be used to step over a impending function call, and return control to the debugger when the call returns. step out executes until the current function call exits. click the "pause" link again on the fishcam page to resume the demo. this starts the dhtml down the other codepath in start() and makes the fishes start swimming again. as you can see, this is a very modest introduction to the functionality of the javascript debugger and the complexity that scripts can have. but the steps described here can give you a basic feel for the debugger if...
Creating XPI Installer Modules - Archive of obsolete content
o create a xpi, use your zip archiver[zip] again to archive the jar file and the installation script install.js. the archive, named barley.xpi, should contain the following two files: barley.jar install.js this zip file, when opened from mozilla using file -> open, will initialize its own installation and display a message like the following: when you click ok, mozilla installs the new package. exit mozilla and restart it with mozilla -chrome chrome://barley/content and the new package displays. the resources are installed in the mozilla/bin/chrome/ directory, and the xpi itself can be redistributed for installation on other machines. notes note: zip there exist a lot of zip archivers/unarchivers. for unix, you can either use the preinstalled zip tool, or e.g. 7-zip (free software). for ...
Using XPInstall to Install Plugins - Archive of obsolete content
cheme with an install.rdf manifest. in particular plugin developers should see how to package a plugin as an extension. xpinstall is a javascript-based installer technology that works across all the platforms that mozilla and netscape browsers based on mozilla (such as netscape 7) are deployed. it can be a way to ensure a smooth user-experience when obtaining plugins, without obliging the user to exit the browsing environment to launch a binary installer (the classic setup.exe experience on windows) or obliging the user to restart their browser. for plugin vendors who have already written a native code (e.g. exe) installer, xpinstall can wrap this native installer and run it so that the user never has to leave the browsing environment and click on the exe to run it. this article presents a gui...
Building accessible custom components in XUL - Archive of obsolete content
it's the previous sibling of the currently focused cell. similarly, navigating down one row simply requires finding the next sibling of the currently focused cell. but navigating left and right is more difficult, since the cells are laid out in columns. we need to find the nth child of the previous column. ...
Menus - Archive of obsolete content
but is equivalent to the menupopup tag. menu tag overview the following shows a simple menu example, containing a menubar with a single menu labeled 'file'. <menubar id="sample-menubar"> <menu id="file-menu" label="file"> <menupopup id="file-popup"> <menuitem label="new"/> <menuitem label="open"/> <menuitem label="save"/> <menuseparator/> <menuitem label="exit"/> </menupopup> </menu> </menubar> there are five tags used in this example, described briefly here: menubar a row of menus that appears along the top of the window or screen. it should contain menu elements. menu a label of a menu on a menubar, for instance 'file' or 'tools'. a menu can also be used as the label of a submenu. menupopup a popup containing items to appear on ...
The Joy of XUL - Archive of obsolete content
d cross platform applications, in contrast with dhtml which is intended for developing web pages. for this reason, xul is oriented toward application artifacts such as windows, labels, and buttons instead of pages, heading levels, and hypertext links. in fact, many developers invest a significant amount of effort to achieve these results in their dhtml web applications but at the cost of complexity and performance and without any supporting standards. based on existing standards xul is an xml language based on w3c standard xml 1.0. applications written in xul are based on additional w3c standard technologies featuring html 4.0; cascading style sheets (css) 1 and 2; document object model (dom) levels 1 and 2; javascript 1.5, including ecma-262 edition 3 (ecmascript); xml 1.0...
Code Samples - Archive of obsolete content
c chat const name = "irc:chatzilla" const uri = "chrome://chatzilla/content/" calendar const name = "calendarmainwindow" const uri = "chrome://calendar/content/" * at the time of writing, sunbird's passwords window is broken close the current window to close the window containing the button, possibly leaving other windows open: close() exit the application to exit the application, first closing all its windows: components .classes['@mozilla.org/toolkit/app-startup;1'] .getservice(components.interfaces.nsiappstartup) .quit(components.interfaces.nsiappstartup.eattemptquit) ...
Manifest Files - Archive of obsolete content
. if the 'chrome:extension' field is true, the application is a mozilla firefox extension and it will show up in the extensions window of the browser. if false, it will not appear. save the contents.rdf and make sure it is in the directory you created in step 1. open the file <mozilla-directory>/chrome/installed-chrome.txt, where <mozilla-directory> is the directory where mozilla is installed. exit mozilla before you do this. next, you are going to register the new application with mozilla so it will know where to find it. add a line at the end of installed-chrome.txt pointing to the new directory you created in step 1. change the highlighted text to the file url below of the directory. make sure that it url ends with a slash and that you press enter at the end of the line. if you aren't s...
More Menu Features - Archive of obsolete content
we'll just add a few simple commands to a file menu and an edit menu. this is similar to the example above. <toolbox> <menubar id="findfiles-menubar"> <menu id="file-menu" label="file" accesskey="f"> <menupopup id="file-popup"> <menuite...
Persistent Data - Archive of obsolete content
one possibility would be to write a script to collect information about what you would like to save and then save it to a file. ...
Simple Menu Bars - Archive of obsolete content
ay not be applied. you should keep this is mind when creating menus. example of a simple menu bar example 1 : source view <toolbox flex="1"> <menubar id="sample-menubar"> <menu id="file-menu" label="file"> <menupopup id="file-popup"> <menuitem label="new"/> <menuitem label="open"/> <menuitem label="save"/> <menuseparator/> <menuitem label="exit"/> </menupopup> </menu> <menu id="edit-menu" label="edit"> <menupopup id="edit-popup"> <menuitem label="undo"/> <menuitem label="redo"/> </menupopup> </menu> </menubar> </toolbox> here, a simple menu bar is created using the menubar element. it will create a row for menus to be placed on. two menus, file and edit have been created here. the menu e...
Using the Editor from XUL - Archive of obsolete content
hrough. nstexteditorkeylistener::keypress() gets the key press event. for normal character keys, that falls into nshtmleditor::editorkeypress(). nshtmleditor::editorkeypress() gets the character code from the key event, puts that into a string, and calls nshtmleditor::typedtext(), which simply calls nshtmleditor::inserttext(). nshtmleditor::inserttext() hides quite a bit of complexity in some stack-based classes. nsautoplaceholderbatch is a utility class that wraps text insertion with calls to turn off selection and layout updating (to avoid flicker), and the maintenance of a placeholder transaction. this placeholder transaction enables us to batch typing events together, so that an undo undoes the whole series of keystrokes. another stack-based class, nsautorules, ensu...
XUL accessibility tool - Archive of obsolete content
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: (aaronlev) warning: hardcoded color and pixel sizings (aaronlev) error: duplicate accesskey in a dialog (already have this for menus) (aaronlev) error: form control without accesskey (aaronlev) warning: accesskey...
menu - Archive of obsolete content
Archive › Mozilla › XUL › menu
if this value is set, ...
Building XULRunner with Python - Archive of obsolete content
that exist for python modules in the application or errors will occur on the target machine. it is possible to test for python in a batch file using something like rem check python 2.5 installed reg query "hklm\software\python\pythoncore\2.5" > nul 2>&1 || reg query "hkcu\software\python\pythoncore\2.5" > nul 2>&1 if errorlevel 1 ( echo python 2.5 was not found. please install it. echo exiting... pause exit /b 1 ) start "xulrunner with python" "%moz_bin%\xulrunner.exe" -app application.ini %opts% exit /b 0 see xulrunner:deploying_xulrunner_1.8 for general information. sample a sample xulrunner application with these python features is available. this includes the pyxpcom tests and a basic python console from alex badea ...
Windows and menus in XULRunner - Archive of obsolete content
ipt src="main.js"/> <toolbox> <menubar id="menubar"> <menu id="file-menu" label="&file;"> <menupopup id="file-popup"> <menuitem label="&file.new;" oncommand="dofilenew();"/> <menuitem label="&file.open;" oncommand="dofileopen();"/> <menuitem label="&file.save;" oncommand="dofilesave();"/> <menuseparator/> <menuitem label="&file.exit;" oncommand="dofileexit();"/> </menupopup> </menu> <menu id="edit-menu" label="&edit;"> <menupopup id="edit-popup"> <menuitem label="&edit.undo;" oncommand="doeditundo();"/> <menuitem label="&edit.redo;" oncommand="doeditredo();"/> </menupopup> </menu> </menubar> <toolbar id="main-toolbar"> <toolbarbutton id="open" label=...
xulauncher - Archive of obsolete content
ucture and # needed meta files in /tmp, copy the xul-file over and start it # usage: # xulauncher xulfile.xul [options] ############################################################################## # check if theres atleast one parameter ############################################################################## if [ $# -lt 1 ] then echo "you need to give the xul file as first parameter" exit fi # check if 1st parameter is a file ############################################################################## if [ ! -f "$1" ] then echo "\"$1\" is not a file" exit fi # define some variables ############################################################################## wd=/tmp ext=".xul" xulfile=`basename $1` xulname=${xulfile%$ext} xuldir="$wd/$xulname/chrome/$xulname/" xulprefdir...
Mozprocess - Archive of obsolete content
processhandler utilizes a contained subclass of subprocess.popen, process, which does the brunt of the process management. basic usage: process = processhandler(['command', '-line', 'arguments'], cwd=none, # working directory for cmd; defaults to none env={}, # environment to use for the process; defaults to os.environ ) exit_code = process.waitforfinish(timeout=60) # seconds see an example in https://github.com/mozilla/mozbase/b...profilepath.py processhandler may be subclassed to handle process timeouts (by overriding the ontimeout() method), process completion (by overriding onfinish()), and to process the command output (by overriding processoutputline()). todo document improvements over subprocess.popen.kill ...
2006-11-10 - Archive of obsolete content
with the following options: ./configure --enable-application=browser --prefix=$prefix --enable-extensions=default,spatialnavigation then he tried running "make" and received the following error: /usr/bin/ld: testtarray.o(.text+0x2237): unresolvable relocation against symbol `nstarray_base::semptyhdr' /usr/bin/ld: final link failed: nonrepresentable section on output collect2: ld returned 1 exit status gmake[3]: *** [testtarray] error 1 gmake[3]: leaving directory `/usr/mozilla2/src/mozilla/xpcom/tests' gmake[2]: *** [libs] error 2 gmake[2]: leaving directory `/usr/mozilla2/src/mozilla/xpcom' gmake[1]: *** [tier_2] error 2 gmake[1]: leaving directory `/usr/mozilla2/src/mozilla' make: *** [default] error 2 he is not sure what is wrong with his build, and is asking for help on how to res...
Extentsions FAQ - Archive of obsolete content
nstalled, your code can't run. right. and if you uninstall firefox, the profile data is left behind. it would be nice to give the option of clearing extension's data, but it should be implemented at application level, not by each extension individually. it might be an option to stick with it and perform stuff when it comes to application shutdown. the sanitize stuff does this (clean stuff on exit). http://lxr.mozilla.org/mozilla1.8/so...ents/nsbrowser... firefox will clean all those preferences which are still "default", that is not changed by the user or the application/extension. to provide those default preferences to your extension see: http://kb.mozillazine.org/dev_:_usin...lt_preferences btw: resetting prefences to default will clear them in case no default prefence is (still) ...
2006-11-17 - Archive of obsolete content
bug #360589 describes this ongoing issue. site not loading with seamonkey a user built seamonkey in debug mode and is currently receiving a "bad request" error on some websites. reflow branch testing wanted l. david baron would like users to test the reflow branch as it is coming close to being merged with the trunk. ...
Back to the Server: Server-Side JavaScript On The Rise - Archive of obsolete content
more comments ... </comments> now that we've created this simple xml feed, we can now also consume it using the code from listing 11. listing 11 - consuming the xml feed <script runat="server"> var r = jaxer.web.get("ser...
2D collision detection - Game development
stance = math.sqrt(dx * dx + dy * dy); if (distance < circle1.radius + circle2.radius) { // collision detected! } note: here is another example without canvas or external libraries. separating axis theorem this is a collision algorithm that can detect a collision between any two *convex* polygons. it's more complicated to implement than the above methods but is more powerful. the complexity of an algorithm like this means we will need to consider performance optimization, covered in the next section. implementing sat is out of scope for this page so see the recommended tutorials below: separating axis theorem (sat) explanation collision detection and response collision detection using the separating axis theorem sat (separating axis theorem) separating axis theorem collis...
2D maze game with device orientation - Game development
ole, phaser.physics.arcade); this.hole.anchor.set(0.5); this.hole.body.setsize(2, 2); the difference is that our hole’s body will not move when we hit it with the ball and will have the collision detection calculated (which will be discussed later on in this article). building the block labyrinth to make the game harder and more interesting we will add some obstacles between the ball and the exit. we could use a level editor, but for the sake of this tutorial let's create something on our own. to hold the block information we'll use a level data array: for each block we'll store the top and left absolute positions in pixels (x and y) and the type of the block — horizontal or vertical (t with the 'w' value meaning width and 'h' meaning height). then, to load the level we'll parse the da...
Abstraction - MDN Web Docs Glossary: Definitions of Web-related terms
advantages of data abstraction helps the user to avoid writing low level code. avoids code duplication and increases reusability. can change internal implementation of class independently without affecting the user. helps to increase security of an application or program as only important details are provided to the user. ...
Code splitting - MDN Web Docs Glossary: Definitions of Web-related terms
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. ...
First input delay - MDN Web Docs Glossary: Definitions of Web-related terms
e to respond to that interaction. it is the 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 ...
HTTP/2 - MDN Web Docs Glossary: Definitions of Web-related terms
est prioritization and server push. http/2 does not modify the application semantics of http in any way. all the core concepts found in http 1.1, such as http methods, status codes, uris, and header fields, remain in place. instead, http/2 modifies how the data is formatted (framed) and transported between the client and server, both of which manage the entire process, and hides application complexity within the new framing layer. as a result, all existing applications can be delivered without modification. ...
Index - MDN Web Docs Glossary: Definitions of Web-related terms
atag atag, accessibility, authoring tool accessibility guidelines, glossary atag (authoring tool accessibility guidelines) is a w3c recommendation for building accessible-authoring tools that produce accessible contents. 10 abstraction abstraction, coding, codingscripting, glossary, programming language abstraction in computer programming is a way to reduce complexity and allow efficient design and implementation in complex software systems. it hides the technical complexity of systems behind simpler apis. 11 accessibility accessibility, glossary web accessibility (a11y) refers to best practices for keeping a website usable despite physical and technical restrictions. web accessibility is formally defined and discussed at the w3c through ...
The box model - Learn web development
the rest of the lesson, we will concentrate on the outer display type. what is the css box model? the full css box model applies to block boxes, inline boxes only use some of the behavior defined in the box model. the model defines how the different parts of a box — margin, border, padding, and content — work together to create a box that you can see on the page. to add some additional complexity, there is a standard and an alternate box model. parts of a box making up a block box in css we have the: content box: the area where your content is displayed, which can be sized using properties like width and height. padding box: the padding sits around the content as white space; its size can be controlled using padding and related properties. border box: the border box wraps the cont...
HTML forms in legacy browsers - Learn web development
ected results that differ across browsers. you can declare appearance: none; to remove the browser styles, but that generally defeats the purpose: as you lose all styling, removing the default look and feel your visitors are used to. to summarize, when it comes to styling form control widgets, the side effects of styling them with css can be unpredictable. so don't. as you can see from the complexity of the property compatibility table for form widgets article, it's very difficult. even if it's still possible to do a few adjustments on text elements (such as sizing or font color), there are always side effects. the best approach remains to not style html form widgets at all. but you can still apply styles to all the surrounding items. and, if you must alter the default styles of your form wi...
CSS property compatibility table for form controls - Learn web development
however, they will give you good insight into what can and can't be done, which will help you learn how to do things. how to read the tables values for each property, there are four possible values: yes there's reasonably consistent support for the property across browsers. you may still face strange side effects in certain edge cases. partial while the property works, you may frequently face strange side effects or inconsistencies. ...
Front-end web developer - Learn web development
ur read/exercises) javascript building blocks (25–35 hour read/exercises) introducing javascript objects (25–35 hour read/exercises) client-side web apis (30–40 hour read/exercises) asynchronous javascript (25–35 hour read/exercises) web forms — working with user data time to complete: 40–50 hours prerequisites forms require html, css, and javascript knowledge. given the complexity of working with forms, it is a dedicated topic. how will i know i'm ready to move on? the assessments in each module are designed to test your knowledge of the subject matter. completing the assessments confirms that you are ready to move on to the next module. modules web forms (40–50 hours) making the web work for everyone time to complete: 60–75 hours prerequisites it is a goo...
Index - Learn web development
s of html that is well supported in all browsers. in the next section, we'll take a look at the newer values of the type attribute that were added in html5. 311 css property compatibility table for form controls advanced, css, forms, guide, html, junk, needsupdate, web the following compatibility tables try to summarize the state of css support for html forms. due to the complexity of css and html forms, these tables can't be considered a perfect reference. however, they will give you good insight into what can and can't be done, which will help you learn how to do things. 312 client-side form validation beginner, example, forms, guide, html, javascript, learn, web, regex client-side form validation sometimes requires javascript if you want to customiz...
Test your skills: Loops - Learn web development
s), which are appended to the provided list. download the starting point for this task to work in your own editor or in an online editor. loops 2 in this next task, we want you to write a simple program that, given a name, searches an array of objects containing names and phone numbers (phonebook) and, if it finds the name, outputs the name and phone number into the paragraph (para) and then exits the loop before it has run its course. you are given three variables to begin with: i — starts off with a value of 0; intended to be used as an iterator. name — contains a name to search for para — contains a reference to a paragraph, which will be used to report the results. you should use a type of loop that you've not used in the previous task. download the starting point for...
Drawing graphics - Learn web development
s a completely separate api from the 2d canvas api, even though they both render onto <canvas> elements. webgl is based on opengl (open graphics library), and allows you to communicate directly with the computer's gpu. as such, writing raw webgl is closer to low level languages such as c++ than regular javascript; it is quite complex but incredibly powerful. using a library because of its complexity, most people write 3d graphics code using a third party javascript library such as three.js, playcanvas, or babylon.js. most of these work in a similar way, providing functionality to create primitive and custom shapes, position viewing cameras and lighting, covering surfaces with textures, and more. they handle the webgl for you, letting you work on a higher level. yes, using one of these mean...
Introduction to web APIs - Learn web development
rrounding computer environment and do useful complex things with it. for example, the web audio api provides javascript constructs for manipulating audio in the browser — taking an audio track, altering its volume, applying effects to it, etc. in the background, the browser is actually using some complex lower-level code (e.g. c++ or rust) to do the actual audio processing. but again, this complexity is abstracted away from you by the api. third-party apis are not built into the browser by default, and you generally have to retrieve their code and information from somewhere on the web. for example, the twitter api allows you to do things like displaying your latest tweets on your website. it provides a special set of constructs you can use to query the twitter service and return specific in...
Object-oriented JavaScript for beginners - Learn web development
prototype instead, which we will look at later. creating our finished constructor the example we looked at above was only a simple example to get us started. let's now get on and create our final person() constructor function. remove the code you inserted so far, and add in this replacement constructor — this is exactly the same as the simple example in principle, with just a bit more complexity: function person(first, last, age, gender, interests) { this.name = { first : first, last : last }; this.age = age; this.gender = gender; this.interests = interests; this.bio = function() { alert(this.name.first + ' ' + this.name.last + ' is ' + this.age + ' years old. he likes ' + this.interests[0] + ' and ' + this.interests[1] + '.'); }; this.greeting = function...
Working with Svelte stores - Learn web development
in the subscribe() method we add the handler to the subs array and return...
Command line crash course - Learn web development
installer appropriate to your operating system. if prompted, make sure to include npm as part of the installation. although we'll look at a number of different tools in the next article onwards, we'll cut our teeth on prettier. prettier is an opinionated code formatter that has "few options". fewer options tends to mean simpler. given how tooling can sometimes get out of hand in terms of complexity, "few options" can be very appealing. where to install our cli tools? before we dive into installing prettier, there's a question to answer — "where should we install to?" with npm we have the choice of installing tools globally — so we can access them anywhere — or locally to the current project directory. there's pros and cons each way — and this list of pros and cons for globally ...
Client-side tooling overview - Learn web development
ypes apply in the development lifecycle, but rest assured that you don't have to have all of these in place to release a website. in fact, you don't need any of these. however, including some of these tools in your process will improve your own development experience and likely improve the overall quality of your code. it often takes some time for new developer tools to settle down in their complexity. one of the best known tools, webpack, has a reputation for being overly complicated to work with, but in the latest major release there was a huge push to simplify common usage so the configuration required is reduced down to an absolute minimum. there's definitely no silver bullet that will guarantee success with tools, but as your experience increases you'll find workflows that work for you ...
Accessible Toolkit Checklist
orting the basic msaa states on every item: unavailable, focused, readonly, offscreen, focusable to avoid extra work, utilize implementing an msaa server mnemonics ability to define in xml for any widget with a text label (via attribute or a preceding char in label) automatically define mnemonics for all standard common dialogs (like yes/no confirmations and retry/exit error dialogs) support mnemonics in dialogs created via method calls layout engine - drawing underline under correct letter events - making keystrokes do the right thing msaa support, via iaccessible's get_acckeyboardshortcut support for ms windows settings when high contrast checkbox is set (in accessibility control panel, spi_gethighcontrast), or whe...
Debugging Frame Reflow
os2 is very vulnerable to pixel alignment errors as text is drawn on pixel boundaries. gecko_display_reflow_indent_undisplayed_frames setting this option via set gecko_display_reflow_indent_undisplayed_frames = 1 will cause an advance of the indent even for frames which are blocked via the reflow rules file. original document informa...
Configuring Build Options
ly not use this option. localization mk_add_options moz_co_locales=isocode tbd. ac_add_options --enable-ui-locale=isocode tbd. ac_add_options --with-l10n-base=/path/to/base/dir tbd. other options mk_add_options autoclobber=1 if a clobber would be required before a build, this will cause mach to clobber and continue with the build instead of asking the user to manually clobber and exiting. ac_add_options --disable-crypto cryptography is enabled by default. in some countries, it may be illegal to use or export cryptographic software. you should become familiar with the cryptography laws in your country. on the 1.7 and aviary branches, cryptography was off by default. you need to specify --enable-crypto if you want ssl, s/mime, or other software features that require cryptogra...
Makefile - variables
s2, qt, windows moz_xpctools moz_xul moz_x11 test variable description enable_tests boolean value that should wrapper all unit tests to allow disabling on demand[1]. python_unit_tests list of python scripts to check exit status for make check xpc_shell_tests no_xpcshell_manifest_check inhibit validating manifest files when running xpcshell tests. compiler variable description gnu_cc defined if the gnu gcc compiler is available. module_optimize_flags additional flags for ena...
Eclipse CDT Manual Setup
dexes" the source.) static analysis involves parsing the source files, so naturally it can only produce good results if it has a sensible set of preprocessor defines, include paths and pre-include files for each source file. since eclipse doesn't initially have any of this information, the code assistance that it's able to provide out of the box is pretty broken. for projects the size and complexity of mozilla, it's impractical to manually configure eclipse when there is a valid set of defines and includes paths for each of the different parts of the source code. happily, eclipse makes manual configuration unnecessary. like some other ides, that are used with projects like mozilla that have their own build system. eclipse provides a tool that can collect the options that are passed to the c...
Inner and outer windows
s of inner and outer windows. consider that when the user is looking at a document in a browser window, not only can the document the user is currently viewing change, but the document's contents can change. then add to that the concept of frames, whereby a document in a window can itself contain other documents, which in turn can contain more documents. in order to represent these levels of complexity, two "types" of window need to be considered. these don't technically refer to windows as the user sees them, but rather a perspective on what the user is looking at. windows and the bfcache an outer window is a browsing context; that is, the actual environment in which a document is presented to the user. this may be a window or a tab, or it might be an <iframe> contained within another documen...
Multiple Firefox profiles
n by this firefox instance will include the bold text "this is the profile in use" for example, if you find that text beneath the entry for "profile: suzie", then you are running in a profile named suzie. launching firefox into a desired profile although it is possible in some cases to have multiple instances of firefox running in different profiles, to avoid confusion, you might want to first exit/quit/terminate all running instances of firefox, firefox developer edition or nightly. then follow the instructions below, applicable to your operating system. from profile manager inside firefox if you already have firefox instance running, you can open another profile from the integrated profile manager on any platform: type about:profiles into the browser url search bar. find the profile...
Performance best practices for Firefox front-end engineers
ng on a performance improvement, this should go without saying: ensure that what you care about is actually improving by measuring before and after. landing a speculative performance enhancement is the same thing as landing speculative bug fixes—these things need to be tested. even if that means instrumenting a function with a date.now() recording at the entrance, and another date.now() at the exit points in order to measure processing time changes. prove to yourself that you’ve actually improved something by measuring before and after. use the performance api the performance api is very useful for taking high-resolution measurements. this is usually much better than using your own hand-rolled timers to measure how long things take. you access the api through window.performance. also,...
Embedding Tips
owser object for the nsiwebbrowserprint interface. call the nsiwebbrowserprint::printpreview() method supplying a print settings object (e.g. that returned from nsiwebbrowserprint::getglobalprintsettings()) that you wish to preview the page with. the nsiwebbrowserprint::printpreviewnavigate() method can be used to step through the pages. when finished with preview mode, call nsiwebbrowserprint::exitprintpreview(). how do i get popup windows working? implement and register a nsiwindowcreator object with the window watcher service. the nsiwindowcreator::createchromewindow method will be called whenever gecko needs to open a new window. this method should create the new browser window in the specified style and hand back the nsiwebbrowserchrome interface to it. nscomptr<nsiwindowwatcher> wwa...
How to add a build-time test
the rules.mk file: cppsrcs, simple_programs, run_test_program. xpcshell tests here are the simple guidelines for adding an xpcshell test to the build system. for now, enclose your test-related code (in the makefile) with ifdef enable_tests run the test program from the "check" target in the makefile. (example to run the testcookie program) in the test program: if the test fails, exit with a non-zero status and/or print the string "fail" to stdout if the test passes, exit with a zero status and don't print the string "fail" (bonus points for printing "pass" :) ) write the test so that you expect it to pass on all platforms, since if the test fails, the tree will go orange (once we've set this up - see bug 352240 for status). for example, to add an xpcshell test...
How to get a stacktrace with WinDbg
0 eb ntdll!ldrpdodebuggerbreak+0x2c 0x90 make sure you enter them one at a time and press enter after each one. if you use the 64-bit version of windows, you need to replace "ntdll" in these commands with "ntdll32". q: the first four frames of my stack trace look like this: 0012fe20 7c90e89a ntdll!kifastsystemcallret 0012fe24 7c81cd96 ntdll!zwterminateprocess+0xc 0012ff20 7c81cdee kernel32!_exitprocess+0x62 0012ff34 6000179e kernel32!exitprocess+0x14 this looks wrong to me?! a: you ran the application without the "debug child processes also" check box being checked. you need to detach the debugger and open the application again, this time with the check box being checked. q: windbg tells me that it is unable to verify checksum for firefox.exe. is this normal? a: yes, this is normal...
Implementing QueryInterface
ace implementation, plus an addref and a release. calling an inherited queryinterface sometimes you are just adding one or two new interfaces to an implementation that already supports many other interfaces. in such cases, you'll probably want to call through to the underlying implementation, after you've tested for the particular iids that you care about. this saves code-space and reduces complexity. the differences are highlighted in the following code. class nsmyimplmentation : public nsbaseimplementation, public nsix, public nsiy { ... }; ns_imethodimp nsmyimplementation::queryinterface( refnsiid aiid, void** ainstanceptr ) /* i just add the interfaces |nsix| and |nsiy|. my base class |nsbaseimplementation| provides all the rest. */ { ns_assertion(ainstancep...
DownloadLastDir.jsm
e: // file is an nsifile var file = gdownloadlastdir.getfile(uri); console.log(file); private browsing mode when browsing normally, the browser uses the browser.download.lastdir preference to store the last download directory path. however, when private browsing mode is enabled, the last download directory path is instead maintained in memory, and the preference is not changed. when the user exits private browsing mode, the last download directory value is reverted to the preference's value. when history is cleared when the user's browsing history is cleared, the value of the last download directory path is restored to the platform's default download directory path. ...
Sqlite.jsm
simpler transactions. sqlite.jsm exposes a transaction api built on top of task.jsm that allows transactions to be written as procedural javascript functions (as opposed to a series of callback driven operations). if the function throws, the transaction is automatically rolled back. this makes code easy to write and read. javascript-y api. sqlite.jsm feels like a pure javascript module. the complexities of xpcom are mostly hidden from view. javascript programmers should feel right at home using sqlite.jsm. note: the sqlite.jsm javascript code module can only be used from chrome -- that is, from within the application itself or an add-on. before you can use this module, you need to import it into your scope: components.utils.import("resource://gre/modules/sqlite.jsm") obtaining a connecti...
Task.jsm
promise spawn(atask); properties attribute type description result read only constructor constructs a special exception that, when thrown inside a legacy generator function, allows the associated task to be resolved with a specific value. example: task.spawn( function() { yield ... ; throw new task.result("value"); } note: if you want to exit early from a generator function, without returning a value for the task, you can just use the return statement without any arguments. note: if you want to return a result from a non-legacy generator function, don't use this. return the value instead: task.spawn( function*() { yield ... ; return "value"; } methods async() create and return an "async function" that starts a ...
openLocationLastURL.jsm
bject it exports. this object lets you fetch and change the url that is placed in the "open location" dialog box when it opens. if the user is not in private browsing mode, this automatically updates the value of the general.open_location.last_url preference. note: this module automatically handles private browsing mode for you. the value preserved across accesses is not preserved when the user exits private browsing mode. using the openlocationlasturl object to get or set the value of the open location edit box, simply read the value of, or set the value of, the openlocationlasturl.value field: var url = openlocationlasturl.value; openlocationlasturl.value = "http://www.mozilla.org/"; to reset the value of the edit box to the default (which is an empty string), you can call the reset() m...
Localization content best practices
uns for titles, and verbs for actions (for example button labels). sometimes they coincide with english, but they rarely do in other languages. take bookmark: it can be both a noun and a verb in english. a developer could be tempted to reuse the same string "bookmark" in the button to add a bookmark, and in the header for the next dialog. this won't work in some languages. avoid unnecessary complexity in strings consider this string: privacy-link = <p>by proceeding you accept the <a href="https://www.mozilla.org/privacy" class="external">privacy terms</a>.</p> in this case, you shouldn't put the url inside the localization string, unless you need it to be localizable. if you change the url, you're going to need a new string id; the same goes for the anchor's attributes, or the paragraph ma...
mozilla::Monitor
wait() nsresult wait( in printervaltime interval = pr_interval_no_timeout ); wait on this monitor until it is notifyed. notify() nsresult notify(void); notify one thread waiting on this monitor. notifyall() nsresult notifyall(void); notify all threads waiting on this monitor. assertcurrentthreadin() assert that the current thread is in this monitor. does not incur a runtime penalty in optimized builds. ...
mozilla::MonitorAutoEnter
a::monitorautoenter is an raii helper for mozilla::monitor. it is designed to make using mozilla::monitor safer and easier. to use mozilla::monitorautoenter, declare and initialize it with a reference to a mozilla::monitor. the mozilla::monitorautoenter constructor will enter() the underlying mozilla::monitor automatically. when the mozilla::monitorautoenter goes out of scope, its destructor will exit() the underlying mozilla::monitorautoenter. important: when a mozilla::monitorautoenter is live on the stack, your code is guaranteed to own the underlying mozilla::monitor. constructors monitorautoenter( in mozilla::monitor& monitor; ); this parameter is a reference so as to guarantee that your code has already properly constructed the mozilla::monitor. methods wait() nsresult wait( in ...
BloatView
ol that shows information about cumulative memory usage and leaks. if it finds leaks, you can use refcount tracing and balancing to discover the root cause. how to build with bloatview build with --enable-debug or --enable-logrefcnt. how to run with bloatview the are two environment variables that can be used. xpcom_mem_bloat_log if set, this causes a bloat log to be printed on program exit, and each time nstracerefcnt::dumpstatistics is called. this log contains data on leaks and bloat (a.k.a. usage). xpcom_mem_leak_log this is similar to xpcom_mem_bloat_log, but restricts the log to only show data on leaks. you can set these environment variables to any of the following values. 1 - log to stdout. 2 - log to stderr. filename - write log to a file. reading individua...
Investigating leaks using DMD heap scan mode
start firefox. be aware that this may take multiple minutes if you have optimization disabled. once it has started, go through the steps you need to reproduce your leak. if your leak is a ghost window, it can be handy to get an about:memory report and write down the pid of the leaking process. you may want to wait 10 or so seconds after this to make sure as much as possible is cleaned up. next, exit the browser. this will cause a lot of logs to be written out, so it can take a while. analyzing the logs getting the pid and address of the leaking object the first step is to figure out the pid of the leaking process. the second step is to figure out the address of the leaking object, usually a window. conveniently, you can usually do both at once using the cycle collector log. if you are inv...
Leak Gauge
script to post-process the log file. getting a log file to get a log file, run the browser with the following environment variables set. nspr_log_modules=domleak:5,documentleak:5,nsdocshellleak:5,nodeinfomanagerleak:5 nspr_log_file=nspr.log # or any other filename of your choice this will overwrite any existing file called nspr.log. the browser will run with negligible slowdown. you must exit the browser before post-processing the log file or the results will be unreliable. post-processing a log file post-process the log file with tools/leak-gauge/leak-gauge.pl or tools/leak-gauge/leak-gauge.html. if there are no leaks, output will look like the following. results of processing log leak.log : summary: leaked 0 out of 11 dom windows leaked 0 out of 44 documents leaked 0 out of 3 do...
A brief guide to Mozilla preferences
if there is a configuration error in the installation. if the application encounters an error when loading user pref files, the application will issue a warning but will continue running. preferences saving usually when the user specifically commits a preference change via user interface such as the preferences dialog, the application saves the change by overwriting prefs.js . on application exit, all user-set preferences are saved to prefs.js . this also means that preferences initially set by user.js will also be saved to prefs.js. do not edit prefs.js directly. note the application never changes user.js, so on launch user.js overrides conflicting preferences from the previous application session. when prefs.js is written, it only saves user preferences which are different from the d...
nglayout.debug.disable_xul_cache
r 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/nglayout.debug.disable_xul_cache ...
MailNews automated testing
go beyond the limitations of xpcshell-tests (for example, access c++ code) and other testing options that don't test at the right level. testing frameworks the asynctestutils extended framework supports: asynchronous test operation: a reasonably convenient means of writing tests that involve asynchronous operations by using generators. in the long term we would like to lose this extra complexity in favor of the event-loop-spinning style of operation used by mozmill. message synthesis: create messages by specifying what properties the messages should have. message injection: inject synthesized messages via local or imap (using a fake server). message manipulation: mark messages as read, tag them, untag them, move them to other folders, trash them, etc. enhanced logging: supports gene...
Optimizing Applications For NSPR
errupt_error</tt>. the only thing you can do is to close the file descriptor. see the faq article for more info. there is no current workaround. you must write your program with this restriction in mind. pr_interrupt is implemented except for <tt>pr_connect()</tt>. irix the irix (classic) implementation has a known race condition in creating new threads. if the spawned thread establishes and exits before the parent thread is resumed, the parent will be left with an invalid pointer to the child. the problem has a solution that will be available soon. digital unix digital unix (aka, osf1) requires the latest patches for the pthreads library. the changes are not evident until one tries to do thread suspension (<tt>pr_suspendall()</tt>) which is in preparation for garbage collection. dig...
Cached Monitors
low the client to associate monitoring protection and state change synchronization in a lazy fashion. the monitoring capability is associated with the protected object only during the time it is required, allowing the monitor object to be reused. this additional flexibility comes at the cost of a small loss in performance. pr_centermonitor enters the lock associated with a cached monitor. pr_cexitmonitor decrements the entry count associated with a cached monitor. pr_cwait waits for a notification that a monitor's state has changed. pr_cnotify notifies a thread waiting for a change in the state of monitored data. pr_cnotifyall notifies all the threads waiting for a change in the state of monitored data. ...
PR_AttachThread
n it is no longer needed. you don't need to call pr_attachthread unless you create your own native thread. pr_init calls pr_attachthread automatically for the primordial thread. note: as of nspr release v3.0, pr_attachthread and pr_detachthread are obsolete. a native thread not created by nspr is automatically attached the first time it calls an nspr function, and automatically detached when it exits. in nspr release 19980529b and earlier, it is necessary for a native thread not created by nspr to call pr_attachthread before it calls any nspr functions, and call pr_detachthread when it is done calling nspr functions. ...
PR_CEnterMonitor
ented (so it has a value of one). if a match is found, then either the calling thread is already in the monitor (and this is a reentrant call) or another thread is holding the monitor's mutex. in the former case, the entry count is simply incremented and the function returns. in the latter case, the calling thread is likely to find the monitor locked by another thread and waits for that thread to exit before continuing. note: pr_centermonitor and pr_cexitmonitor must be paired--that is, there must be an exit for every entry--or the object will never become available for any other thread. ...
PR_CWait
ded. pr_failure indicates either that the monitor could not be located in the cache or that the monitor was located and the calling thread was not the thread that held the monitor's mutex. description using the value specified in the address parameter to find a monitor in the monitor cache, pr_cwait waits for a notification that the monitor's state has changed. while the thread is waiting, it exits the monitor (just as if it had called pr_cexitmonitor as many times as it had called pr_centermonitor). when the wait has finished, the thread regains control of the monitor's lock with the same entry count as before the wait began. the thread waiting on the monitor resumes execution when the monitor is notified (assuming the thread is the next in line to receive the notify) or when the interva...
PR_Cleanup
thread, pr_failure. description pr_cleanup must be called by the primordial thread near the end of the main function. pr_cleanup attempts to synchronize the natural termination of the process. it does so by blocking the caller, if and only if it is the primordial thread, until all user threads have terminated. when the primordial thread returns from main, the process immediately and silently exits. that is, the process (if necessary) forcibly terminates any existing threads and exits without significant blocking and without error messages or core files. ...
PR_CreateThread
following values: if successful, a pointer to the new thread. this pointer remains valid until the thread returns from its root function. if unsuccessful, (for example, if system resources are unavailable), null. description if you want the thread to start up waiting for the creator to do something, enter a lock before creating the thread and then have the thread's root function enter and exit the same lock. when you are ready for the thread to run, exit the lock. for more information on locks and thread synchronization, see introduction to nspr. if you want to detect the completion of the created thread, make it joinable. you can then use pr_jointhread to synchronize the termination of another thread. ...
PR_DetachThread
disassociates a prthread object from a native thread. syntax #include <pprthread.h> void pr_detachthread(void); parameters pr_detachthread has no parameters. returns the function returns nothing. description this function detaches the nspr thread from the currently executing native thread. the thread object and all related data attached to it are destroyed. the exit process is invoked. the call returns after the nspr thread object is destroyed. this call is needed only if you attached the thread using pr_attachthread. note: as of nspr release v3.0, pr_attachthread and pr_detachthread are obsolete. a native thread not created by nspr is automatically attached the first time it calls an nspr function, and automatically detached when it exits. in nspr release 19980529b and earlier...
PR_Initialize
syntax #include <prinit.h> printn pr_initialize( prprimordialfn prmain, printn argc, char **argv, pruintn maxptds); parameters pr_initialize has the following parameters: prmain the function that becomes the primordial thread's root function. returning from prmain leads to termination of the process. ...
PR_Lock
locks a specified lock object. syntax #include <prlock.h> void pr_lock(prlock *lock); parameter pr_lock has one parameter: lock a pointer to a lock object to be locked. description when pr_lock returns, the calling thread is "in the monitor," also called "holding the monitor's lock." any thread that attempts to acquire the same lock blocks until the holder of the lock exits the monitor. acquiring the lock is not an interruptible operation, nor is there any timeout mechanism. pr_lock is not reentrant. calling it twice on the same thread results in undefined behavior. see also pr_unlock ...
PR_NewThreadPrivateIndex
ate and pr_getthreadprivate to set and retrieve data associated with the index. when you allocate the index, you may also register a destructor function of type prthreadprivatedtor. if a destructor function is registered with a new index, it will be called at one of two times, as long as the private data is not null: when replacement private data is set with pr_setthreadprivate when a thread exits the index maintains independent data values for each binding thread. a thread can get access only to its own thread-specific data. there is no way to deallocate a private data index once it is allocated. ...
Process Initialization
uirements or needs to characterize the primordial thread. explicit initialization is rarely necessary. implicit initialization assumes that the initiator is the primordial thread and that the thread is a user thread of normal priority. pr_init pr_initialize pr_initialized pr_cleanup pr_disableclockinterrupts pr_blockclockinterrupts pr_unblockclockinterrupts pr_setconcurrency pr_processexit pr_abort module initialization initialization can be tricky in a threaded environment, especially initialization that must happen exactly once. pr_callonce ensures that such initialization code is called only once. this facility is recommended in situations where complicated global initialization is required. prcalloncetype prcalloncefn pr_callonce ...
NSS FAQ
Mozilla › Projects › NSS › FAQ
if my application protocol isn't http? yes, tls is independent of application protocols. it works with common internet standard application protocols (http, pop3, ftp, smtp, etc.) as well as custom application protocols using tcp/ip. how long does it take to integrate nss into my application? the integration effort depends on an number of factors, such as developer skill set, application complexity, and the level of security required for your application. nss includes detailed documentation of the ssl api and sample code that demonstrates basic ssl functionality (setting up an encrypted session, server authentication, and client authentication) to help jump start the integration process. however, there is little or no documentation currently available for the rest of the nss api. if your a...
Index
nt version of netscape signing tool, you must use the -d option with the -g option. with the unix version of netscape signing tool, omitting the -d option causes the tool to install the keys and certificate in the communicator key and certificate databases. if you are installing the keys and certificate in the communicator databases, you must exit communicator before using this option; otherwise, you risk corrupting the databases. in all cases, the certificate is also output to a file named x509.cacert, which has the mime-type application/x-x509-ca-cert. unlike certificates normally used to sign finished code to be distributed over a network, a test certificate created with -g is not s...
NSS_3.12_release_notes.html
nsigned long constant. ...
NSS 3.15.1 release notes
on windows, nss initialization fails if nss cannot call the rtlgenrandom function. bug 875601 - secmod_closeuserdb/secmod_openuserdb fails to reset the token delay, leading to spurious failures. bug 884072 - fix a typo in the header include guard macro of secmod.h. bug 876352 - certutil now warns if importing a pem file that contains a private key. bug 565296 - fix the bug that shlibsign exited with status 0 even though it failed. the nss_survive_double_bypass_failure build option is removed. bugs fixed in nss 3.15.1 https://bugzilla.mozilla.org/buglist.cgi?list_id=5689256;resolution=fixed;classification=components;query_format=advanced;target_milestone=3.15.1;product=nss compatibility nss 3.15.1 shared libraries are backward compatible with all older nss 3.x shared libraries. ...
NSS 3.46 release notes
sions in ssl_constructextensions bug 1415118 - nss build with ./build.sh --enable-libpkix fails bug 1539788 - add length checks for cryptographic primitives (cve-2019-17006) bug 1542077 - mp_set_ulong and mp_set_int should return errors on bad values bug 1572791 - read out-of-bounds in der_decodetimechoice_util from sslexp_delegatecredential bug 1560593 - cleanup.sh script does not set error exit code for tests that "failed with core" bug 1566601 - add wycheproof test vectors for aes-kw bug 1571316 - curve25519_32.c:280: undefined reference to `pr_assert' when building nss 3.45 on armhf-linux bug 1516593 - client to generate new random during renegotiation bug 1563258 - fips.sh fails due to non-existent "resp" directories bug 1561598 - remove -wmaybe-uninitialized warning in pqg.c b...
NSS Sample Code sample4
be in buf1 */ rv = pk11_pubdecryptraw(pvtkey, buf1, &outlen, modulus_len, buf2, modulus_len); if (rv != secsuccess) { fprintf(stderr, "decrypt with private key failed (err %d)\n", pr_geterror()); goto cleanup; } fprintf(stderr, "result of decryption, outlen = %d\n", outlen); fprintf(stderr, "result of decryption, buf = \n%s\n", buf1); exit(0); cleanup: if (cert) cert_destroycertificate(cert); if (pubkey) seckey_destroypublickey(pubkey); if (pvtkey) seckey_destroyprivatekey(pvtkey); if (buf1) free(buf1); if (buf2) free(buf2); exit(1); } char *passwdcb(pk11slotinfo *info, prbool retry, void *arg) { if (!retry) return pl_strdup("test"); else return null; } ...
NSS Sample Code sample5
utlen = %d\n", outlen); fprintf(stderr, "result of decryption, buf = \n%s\n", buf1); cleanup: if (cert) cert_destroycertificate(cert); if (pubkey) seckey_destroypublickey(pubkey); if (pvtkey) seckey_destroyprivatekey(pvtkey); if (spki) seckey_destroysubjectpublickeyinfo(spki); if (slot) pk11_freeslot(slot); if (buf1) free(buf1); if (buf2) free(buf2); exit(1); } ...
NSS Sample Code sample6
rv; /* initialize nss */ pk11_setpasswordfunc(passwdcb); /* the nss db must be initialized read-write since we'll be creating * keys in it. once keys are generated, it can be opened without read-write * subsequently (nss_init). */ rv = nss_initreadwrite("."); if (rv != secsuccess) { fprintf(stderr, "nss initialization failed (err %d)\n", pr_geterror()); exit(1); } /* generate a key with id 1. should succeed on first run on a fresh db, * should fail on successive runs because key with that id already exists */ genkey(1); /* generate a key with id 2. should succeed on first run on a fresh db, * should fail on successive runs because key with that id already exists */ genkey(2); /* generate a key with id 1 - this will fail because k...
NSS tools : signtool
nt version of netscape signing tool, you must use the -d option with the -g option. with the unix version of netscape signing tool, omitting the -d option causes the tool to install the keys and certificate in the communicator key and certificate databases. if you are installing the keys and certificate in the communicator databases, you must exit communicator before using this option; otherwise, you risk corrupting the databases. in all cases, the certificate is also output to a file named x509.cacert, which has the mime-type application/x-x509-ca-cert. unlike certificates normally used to sign finished code to be distributed over a network, a test certificate created with -g is not s...
Rhino Debugger
ak on exceptions checkbox from the menu bar. whenever a javascript exception is thrown by a script a message dialog will be displayed and control will be given to the debugger at the location the exception is raised. break on function enter selecting debug->break on function enter will give control to the debugger whenever the execution is entered into a function or script. break on function exit selecting debug->break on function return will give control to the debugger whenever the execution is about to return from a function or script. moving up and down the stack the lower-left (dockable) pane in the debugger main window contains a combo-box labeled "context:" which displays the current stack of the executing script. you may move up and down the stack by selecting an entry in the ...
Scripting Java
one method if all the methods have the same signature. when calling the function, rhino passes the method's name as the additional argument. function can use it to distinguish on behalf of which method it was called: js> var frame = new packages.javax.swing.jframe(); js> frame.addwindowlistener(function(event, methodname) { if (methodname == "windowclosing") { print("calling system.exit()..."); java.lang.system.exit(0); } }); js> frame.setsize(100, 100); js> frame.visible = true; true js> calling system.exit()... creating java arrays rhino provides no special syntax for creating java arrays. you must use the java.lang.reflect.array class for this purpose. to create an array of five java strings you would make the following call: js> a = java.lang.reflect.array.newinstan...
Rebranding SpiderMonkey (1.8.5)
install:: $brand.pc @echo pkg_config_file: $brand.pc note: while it is possible to automate the manual editing process, this has been discouraged due to the fact that these files are automatically generated and very little constant data can be depended upon. it also allows these instructions to apply to a wide range platforms without introducing more software dependencies. save the file and exit the editor. you may now perform the build and installation of your custom branded spidermonkey library: make note: depending on your system you may need administrative rights to perform the installation: make install the following information isn't technically needed for using your library but it will help other applications use your library. your rebranded library has been succesfully built an...
Creating JavaScript tests
nctionality is provided for you in shell.js files. you can read about them here. performance testing and general advice do not attempt to test the performance of engine features in the test suite. please keep in mind that the javascript test suite is run on a wide variety 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 perfor...
GC Rooting Guide
ers from functions. use js::rooted<t> fields when possible for aggregates, otherwise use an autorooter. ...
Hacking Tips
args=..., construct=js::no_construct) at js/src/vm/interpreter.cpp:476 #3 0x000000000069bdcf in js::jit::docallfallback(jscontext*, js::jit::baselineframe*, js::jit::iccall_fallback*, uint32_t, js::value*, js::mutablehandlevalue) (cx=0x14f2640, frame=0x7fffffff6ad8, stub_=0x1798838, argc=1, vp=0x7fffffff6a88, res=jsval_void) at js/src/jit/baselineic.cpp:6113 #4 0x00007ffff7f41395 in <<jitframe_exit>> () #5 0x00007ffff7f42223 in <<jitframe_baselinestub>> () #6 0x00007ffff7f4423d in <<jitframe_baselinejs>> () #7 0x00007ffff7f4222e in <<jitframe_baselinestub>> () #8 0x00007ffff7f4326a in <<jitframe_baselinejs>> () #9 0x00007ffff7f38d5f in <<jitframe_entry>> () #10 0x00000000006a86de in enterbaseline(jscontext*, js::jit::enterjitdata&) (cx=0x14f2640, data=...) at js/src/jit/baselinejit.cpp...
Functions
k the scope chain, its parent is the global object. this is the best case. barring with and eval, all outermost functions are null closures. null closures with upvars. a nested function is algol-like if it is only ever defined and called, and it isn't accessed in any other way (and it is not a generator-function). such a function is guaranteed never to be called again after the enclosing function exits. an algol-like function may read the local variables and arguments of its immediate enclosing function from the stack, as if by magic. (jscontext::display caches the enclosing function's stack frame.) if that function is also algol-like, its child can read locals and variables from the next enclosing function, and so on. the compiler detects these cases and makes such functions null closures too...
Invariants
er object property, due to with, or a variable that isn't in the source code at all but was injected into a local scope by eval. these cases can be detected statically by looking for with and eval "nearby" in the parse tree.) if a nested function contains a nameexpression that refers to a variable in an enclosing scope which the function can outlive (i.e. the function can be called after control exits that enclosing scope) then upvar instructions cannot be used for that nameexpression. (wrong results or a potentially exploitable crash. the upvar ops depend on a per-context display of currently active stack frames. once the enclosing stack frame is removed from the stack, and thus from the display, the upvar lookup will no longer work correctly and can crash or read off the end of a different ...
Introduction to the JavaScript shell
cified function. if you specify a program counter offset into the function, the line number of the line of code containing that offset is returned. print([expression ...]) evaluates the expression(s) and displays the result(s) on stdout, separated by spaces (" ") and terminated by a newline ("\n"). putstr(expression) evaluates the expression and displays the result on stdout. quit([status]) exits the shell. status defaults to 0 if omitted. read(filename[, type]) reads and returns the contents of file. if type is "binary" returns an uint8array, otherwise returns an utf-8 decoded string. readline() reads a single line of input from stdin, returning it to the caller. you can use this to create interactive shell programs in javascript. reflect.parse() see parser api. note: this functi...
JS_GetFunctionCallback
note: this method is only available if moz_trace_jscalls was defined at compile time using --enable-trace-jscalls. ...
JS_ThrowStopIteration
s the appropriate stopiteration object for the function currently executing in cx. in for…in and for each…in loops, the javascript engine can create an iterator object and call its .next method repeatedly, as described in new in javascript 1.7: iterators. the .next method may throw stopiteration when there are no more values left to iterate. the engine automatically catches the exception and exits the loop. jsclass.enumerate offers a simpler way to customize object iteration. see also mxr id search for js_throwstopiteration js_isstopiteration bug 390947 ...
Running Automated JavaScript Tests
en viewing treeherder after a push to the mozilla repositories, jit-tests are run by calling make check, and appear under b. creating new tests for jit-tests creating new tests for jit-tests is easy. just add a new js file to the tests/basic directory (or any appropriate directory under 'tests'). the test harness will automatically find the test and run it. the test is considered to pass if the exit code of the js shell is zero (i.e., js didn't crash and there were no js errors). use the asserteq function to verify values in your test. there are some advanced options for tests. see the readme (in js/src/jit-tests) for details. ...
Using RAII classes in Mozilla
secondly they will run locally, even if the developer did not choose to run static analysis locally. the static analys runtime assertions are often better at catching bugs in code that a developer is currently working on than static analysis, which he might not think to run. we have a set of macros that will cause a class to assert when it is instantiated at a temporary. they cause no extra complexity for users of the class, but they do slightly complicate the implementation of the class. these macros are provided in guardobjects.h. in the common case, using these macros involves these three additions to a class: class moz_raii nsautoscriptblocker { public: explicit nsautoscriptblocker(jscontext *cx moz_guard_object_notifier_param) { // note: no ',' before macro moz_guard_object_noti...
Using the Places annotation service
be explicitly stated when the annotation is created. if no expiration is specified, the annotation is expired when the number of visits to the url is set to zero. valid values for expiration are: expire_with_history : default. annotations live as long as the uri is in history (eg: has >0 visits). expire_never : never expire. must be explictly removed. expire_session : removed at application exit. expire_days : removed at 7 days. expire_weeks : removed at 30 days. expire_months : removed at 180 days. annotationservice.setpageannotation(uri, "my_extension/some_annotation", "this is the annotation value", 0, annotationservice.expire_never); annotation observers observers can also be added to the service to watch for changes to annotations. to add or remove an observer use the meth...
Bundling multiple binary components
. create small wrappers for calling the methods, as you may need to thunk parameters depending on how much has changed between gecko versions. this means using something like loadlibrary / getprocaddress / freelibrary on windows. actually, nspr 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 compone...
Component Internals
utdown process when the application is ready to shutdown xpcom, it calls ns_shutdownxpcom. when that method is called, the following sequence of events occurs: xpcom fires a shutdown notification to all registered observers. xpcom closes down the component manager, the service manager and associated services. xpcom frees all global services. ns_shutdownxpcom returns and the application may exit normally. the unstoppable shutdown note that shutdown observation is unstoppable. in other words, the event you observe cannot be used to implement something like a "are you sure you want to quit?" dialog. rather, the shutdown event gives the component or embedding application a last chance to clean up any leftovers before they are released. in order to support something like an "are you sure...
XPCOM Stream Guide
Mozilla › Tech › XPCOM › Guide › Streams
ble immediately. (this is particularly true of streams that reach out over a network connection, like http and ftp channels.) stream listeners implement three methods. from the nsistreamlistener interface, the .ondataavailable(request, context, inputstream, offset, count) method gives you the input stream and the number of bytes available. the stream listener must read exactly count bytes before exiting. from the nsirequestobserver interface, the .onstartrequest(request, context) method tells you when the request begins, while the .onstoprequest(request, context) method tells you when the request ends. a request will have one .onstartrequest(request, context) call, followed by at least one .ondataavailable(...) call, followed by one .onstoprequest(request, context) call. the context argument...
Index
Mozilla › Tech › XPCOM › Index
ppearance varies from platform to platform. 324 nsiannotationobserver developing mozilla, extensions, interfaces, places, xpcom, xpcom api reference this method is called when an annotation is deleted for an item. if aname is empty, then all annotations for the given item have been deleted. this is not called when annotations are expired (normally happens when the application exits). 325 nsiannotationservice developing mozilla, extensions, interface, interfaces, interfaces:scriptable, places, xpcom, xpcom api reference, xpcom interface reference, nsiannotationservice implemented by: "@mozilla.org/browser/annotation-service;1". to use this service, use: 326 nsiappshell interfaces, interfaces:scriptable, xpcom, xpcom api reference, xpcom i...
XPCShell Reference
this function dumps the xpconnect object. see the documentation on debugdump() for the nsixpconnect interface for more information. version(newversion) version() returns the javascript engine version number. if you pass a number to it, it will set the version number (and return the old version number). see the above documentation on the -v command-line argument for more information. quit(exitcode) quit() exits the shell. you can specify arguments that will get translated to an exit code. quit(5) will exit xpcshell with a result code of 5. original document information author: david bradley <dbradley@netscape.com> last updated date: 17 march 2003 copyright information: portions of this content are © 1998–2008 by individual mozilla.org contributors; content available under a...
Observer Notifications
onstore-state-write-complete sent immediately after the session store data is written to disk. sessionstore-state-purge-complete private browsing these topics indicate when actions related to private browsing occur. topic data description private-browsing enter sent when private browsing mode is activated. private-browsing exit sent when private browsing mode is deactivated. bookmarks these topics indicate when actions related to bookmarks occur. topic data description bookmarks-restore-begin json sent just before bookmarks are restored from json. bookmarks-restore-begin html sent just before bookmarks are restored from html. if bookmarks will be restored into a s...
mozIPlacesAutoComplete
earch the url of pages. behavior_typed 1 << 5 search for typed pages. behavior_javascript 1 << 6 search javascript: urls. behavior_openpage 1 << 7 search for pages that have been marked as being opened, such as a tab in a tabbrowser. methods registeropenpage() mark a page as being currently open. note: pages will not be automatically unregistered when private browsing mode is entered or exited. therefore, consumers must unregister or register themselves. void registeropenpage( in nsiuri auri ); parameters auri the uri to register as an open page. unregisteropenpage() mark a page as no longer being open (either by closing the window or tab, or by navigating away from that page). note: pages will not be automatically unregistered when private browsing mode is entered or exited. th...
nsIAccessibleEvent
eceived mouse capture. event_capture_end 0x001d 0x001a a window has lost mouse capture. event_movesize_start 0x001e 0x001b a window is being moved or resized. event_movesize_end 0x001f 0x001c the movement or resizing of a window has finished. event_contexthelp_start 0x0020 0x001d a window has entered context-sensitive help mode. event_contexthelp_end 0x0021 0x001e a window has exited context-sensitive help mode. event_dragdrop_start 0x0022 0x001f an application is about to enter drag-and-drop mode. event_dragdrop_end 0x0023 0x0020 an application is about to exit drag-and-drop mode. event_dialog_start 0x0024 0x0021 a dialog box has been displayed. event_dialog_end 0x0025 0x0022 a dialog box has been closed. event_scrolling_start 0x0026 0x0023 scrolling ha...
nsIDOMWindowUtils
ousemove, mouseover, mouseout, contextmenu. events are sent in coordinates offset by ax and ay from the window. note: that additional events may be fired as a result of this call. for instance, typically a click event will be fired as a result of a mousedown and mouseup in sequence. normally at this level of events, the mouseover and mouseout events are only fired when the window is entered or exited. for inter-element mouseover and mouseout events, a movemove event fired on the new element should be sufficient to generate the correct over and out events as well. cannot be accessed from unprivileged context (not content-accessible) will throw a dom security error if called without universalxpconnect privileges. the event is dispatched via the toplevel window, so it could go to any window ...
nsIProcess2
s, in unsigned long count, in nsiobserver observer, optional in boolean holdweak optional ); parameters args an array of arguments to pass into the process, using the native character set. this array must have count entries. count the number of arguments passed in the args array. observer optional an observer that will be notified when the process exits. the observer will receive this nsiprocess2 instance as the subject and "process-finished" or "process-failed" as the topic. the observer will be notified on the main thread. holdweak optional if true, a weak reference is used to hold the observer. see also nsiprocess nsiobserver ...
nsISupports proxies
oked on the destination thread. this is the normal and default case. proxy_async, on the other hand, is a "fire and forget" method call. calls on object created with this flag will return immediately and you will lose all return information. ns_ok will be returned to you. warning about proxy_async: you must take very special care when using this flag. as soon as the calling function or method exits, there is no guarantee about the data at the location that used to be part of that stack frame. accessing it might even cause a crash. for example: myfoo->bar(&x) ... stack frame goes away ... bar(print32 *x) { ... *x = 0; <----- you will blow up here. } so, given an event queue to execute methods on, and either an nsisupports object that has been created or cid, and a fl...
nsIXULWindow
esponding to the given id, if any. removechildwindow() tell this window that it has lost a child xul window. note that xul windows do not currently track child xul windows. void removechildwindow( in nsixulwindow achild ); parameters achild the child window being removed. showmodal() shows the window as a modal window. that is, ensures that it is visible and runs a local event loop, exiting only once the window has been closed. void showmodal(); parameters none. ...
Using the clipboard
ength of the string by 2, since it's stored in 2-byte utf-16 // format internally. trans.settransferdata("text/unicode", supportsstring(str), str.length * 2); the first line gets the transferring component which implements nsitransferable. next we need to initialize it with a "privacy context", which will ensure that source data from inside private browsing mode will be cleared when the mode is exited. please note: the sourcewindow variable is a placeholder for whatever window owns the data being copied -- from any dom element you can obtain it via element.ownerdocument.defaultview. if, and only if, you are placing data on the clipboard that is unrelated to web content the user is viewing, you can pass a null privacy context to the init method. the next step is to tell the transferable what...
Accessibility Inspector - Firefox Developer Tools
none — don't show the possible list of issues all issues — check for all types of issues contrast — check for issues with visual contrast keyboard — check for issues with navigating via a keyboard text labels — check for issues with missing text labels when you one of the menu items, firefox scans your document for the type of issues you selected. depending on the size and complexity of your document, this may take a few seconds. when the scan is complete, the left side of the accessibility inspector panel displays only the items that have that type of issue. in the right side of the panel, the checks subpanel lists the specific issue with the selected node. for each type of issue, there is a learn more link to further information on mdn web docs about the issue. the menu...
UI Tour - Firefox Developer Tools
of the script you're debugging. when it displays a "play" icon, that means the script is paused, either because you've paused it with this button or because you've hit a breakpoint. step over (f10): steps to the next line of javascript code. step in (f11): steps into the function call on the current line of javascript code. step out (shift-f11): runs the script until the current function exits. a button that deactivates all breakpoints. a settings menu that contains: disable javascript: disables javascript for this tab. this option enables you to see how your web page looks if the user has disabled javascript via an extension or a configuration setting. the setting is reset when the developer tools are closed (except in firefox 77, see bug 1640318). inline variable pre...
Debugger - Firefox Developer Tools
herwise,frame is popped, and the exception propagates toframe’s caller. when an exception’s propagation causes control to enter a finally block, the exception is temporarily set aside. if the finally block finishes normally, the exception resumes propagation, and the debugger’s onexceptionunwind handler is called again, in the same frame. (the other possibility is for the finally block to exit due to a return, continue, or break statement, or a new exception. in those cases the old exception does not continue to propagate; it is discarded.) this handler is not called when unwinding a frame due to an over-recursion or out-of-memory exception. sourcehandler(asuffusionofyellow) this method is never called. if it is ever called, a contradiction has been proven, and the debugger is fr...
Drawing shapes with canvas - Web APIs
his: screenshotlive sample we won't go over this in detail, since it's actually surprisingly simple. the most important things to note are the use of the fillstyle property on the drawing context, and the use of a utility function (in this case roundedrect()). using utility functions for bits of drawing you do often can be very helpful and reduce the amount of code you need, as well as its complexity. we'll take another look at fillstyle, in more detail, later in this tutorial. here, all we're doing is using it to change the fill color for paths from the default color of black to white, and then back again. path2d objects as we have seen in the last example, there can be a series of paths and drawing commands to draw objects onto your canvas. to simplify the code and to improve performanc...
Client.postMessage() - Web APIs
any structured-clonable type. transfer optional a sequence of objects that are transferred with the message. the ownership of these objects is given to the destination side and they are no longer usable on the sending side. return value undefined. examples sending a message from a service worker to a client: addeventlistener('fetch', event => { event.waituntil(async function() { // exit early if we don't have access to the client. // eg, if it's cross-origin. if (!event.clientid) return; // get the client. const client = await clients.get(event.clientid); // exit early if we don't get the client. // eg, if it closed. if (!client) return; // send a message to the client. client.postmessage({ msg: "hey i just got a fetch from you!", ...
Clipboard - Web APIs
Web › API › Clipboard
finished by resolving the returned promise. writetext() writes text to the system clipboard, returning a promise which is resolved once the text is fully copied into the clipboard. clipboard availability the asynchronous clipboard api is a relatively recent addition, and the process of implementing it in browsers is not yet complete. due to both potential security concerns and technical complexities, the process of integrating this api is happening gradually in most browsers. for example, firefox does not yet support the "clipboard-read" and "clipboard-write" permissions, so access to the methods that access and change the contents of the clipboard are restricted in other ways. for webextensions, you can request the clipboardread and clipboardwrite permissions to be able to use clipboar...
Console.group() - Web APIs
Web › API › Console › group
put by visually associating related messages. to create a new nested block, call console.group(). the console.groupcollapsed() method is similar, but the new block is collapsed and requires clicking a disclosure button to read it. note: from gecko 9 until gecko 51, the groupcollapsed() method was the same as group(). collapsed groups are fully supported starting in gecko 52. see bug 1088360. to exit the current group, call console.groupend(). for example, given this code: console.log("this is the outer level"); console.group(); console.log("level 2"); console.group(); console.log("level 3"); console.warn("more of level 3"); console.groupend(); console.log("back to level 2"); console.groupend(); console.log("back to the outer level"); the output looks like this: see using groups in the ...
Console.groupEnd() - Web APIs
Web › API › Console › groupEnd
see using groups in the console in the console documentation for details and examples. note: this feature is available in web workers. syntax console.groupend(); parameters none. specifications specification status comment console apithe definition of 'console.groupend()' in that specification. ...
ContentIndex - Web APIs
content index if (!registration.index) return; // unregister content from index await registration.index.delete(article.id); } all the above methods are available within the scope of the service worker. they are accessible from the workerglobalscope.self property: // service worker script self.registration.index.add(item); self.registration.index.delete(item.id); const contentindexitems = self.registration.index.getall(); specifications specification status comment unknownthe definition of 'contentindex' in that specification. unknown initial definition. ...
Content Index API - Web APIs
content index if (!registration.index) return; // unregister content from index await registration.index.delete(article.id); } all the above methods are available within the scope of the service worker. they are accessible from the workerglobalscope.self property: // service worker script self.registration.index.add(item); self.registration.index.delete(item.id); const contentindexitems = self.registration.index.getall(); contentdelete event when an item is removed from the user agent interface, a contentdelete event is received by the service worker. self.addeventlistener('contentdelete', (event) => { console.log(event.id); // logs content index id, which can then be used to determine what content to delete from your cache }); the contentdelete event is only fire...
Document: fullscreenchange event - Web APIs
red immediately after the browser switches into or out of full-screen mode. bubbles yes cancelable no interface event event handler property onfullscreenchange the event is sent to the element that is transitioning into or out of full-screen mode, and this event then bubbles up to the document. to find out whether the element is entering or exiting full-screen mode, check the value of documentorshadowroot.fullscreenelement: if this value is null then the element is exiting full-screen mode, otherwise it is entering full-screen mode. examples in this example, a handler for the fullscreenchange event is added to the document. document.addeventlistener('fullscreenchange', (event) => { // document.fullscreenelement will point to the ele...
Element: mouseenter event - Web APIs
o the deepest element of the dom tree, then it bubbles up the hierarchy until it is canceled by a handler or reaches the root. with deep hierarchies, the number of mouseenter events sent can be quite huge and cause significant performance problems. in such cases, it is better to listen for mouseover events. combined with the corresponding mouseleave (which is fired at the element when the mouse exits its content area), the mouseenter event acts in a very similar way to the css :hover pseudo-class. examples the mouseover documentation has an example illustrating the difference between mouseover and mouseenter. mouseenter the following trivial example uses the mouseenter event to change the border on the div when the mouse enters the space alloted to it. it then adds an item to the list wi...
Element: mouseleave event - Web APIs
event is fired at an element when the cursor of a pointing device (usually a mouse) is moved out of it. bubbles no cancelable no interface mouseevent event handler property onmouseleave mouseleave and mouseout are similar but differ in that mouseleave does not bubble and mouseout does. this means that mouseleave is fired when the pointer has exited the element and all of its descendants, whereas mouseout is fired when the pointer leaves the element or leaves one of the element's descendants (even if the pointer is still within the element). one mouseleave event is sent to each element of the hierarchy when leaving them. here four events are sent to the four elements of the hierarchy when the pointer moves from the text to an area outs...
Element: mouseout event - Web APIs
bubbles yes cancelable yes interface mouseevent event handler property onmouseout examples the following examples show the use of the mouseout event. mouseout and mouseleave the following example illustrates the difference between mouseout and mouseleave events. the mouseleave event is added to the <ul> to color the list purple whenever the mouse exits the <ul>. mouseout is added to the list to color the targeted element orange when the mouse exits it. when you try this out, you'll find that mouseout is delivered to the individual list items, while mouseleave goes to the overall list, courtesy of the hierarchy of the items and the fact that list items obscure the underlying <ul>. html <ul id="test"> <li>item 1</li> <li>item 2</li> <li...
Element.onfullscreenchange - Web APIs
s in full-screen mode versus being displayed in a window. function togglefullscreen() { let elem = document.queryselector("video"); elem.onfullscreenchange = handlefullscreenchange; if (!document.fullscreenelement) { elem.requestfullscreen().then({}).catch(err => { alert(`error attempting to enable full-screen mode: ${err.message} (${err.name})`); }); } else { document.exitfullscreen(); } } function handlefullscreenchange(event) { let elem = event.target; let isfullscreen = document.fullscreenelement === elem; adjustmycontrols(isfullscreen); } specifications specification status comment fullscreen apithe definition of 'onfullscreenchange' in that specification. living standard initial definition. ...
Element - Web APIs
Web › API › Element
firefox since version 48.0. properties included from slotable the element interface includes the following property, defined on the slotable mixin. slotable.assignedslotread only returns a htmlslotelement representing the <slot> the node is inserted in. event handlers element.onfullscreenchange an event handler for the fullscreenchange event, which is sent when the element enters or exits full-screen mode. this can be used to watch both for successful expected transitions, but also to watch for unexpected changes, such as when your app is running in the background. element.onfullscreenerror an event handler for the fullscreenerror event, which is sent when an error occurs while attempting to change into full-screen mode. methods inherits methods from its parents node, and it...
Comparison of Event Targets - Web APIs
pt> </body> </html> use of target and relatedtarget the relatedtarget property for the mouseover event holds the node that the mouse was previously over. for the mouseout event, it holds the node that the mouse moved to. event type event.target event.relatedtarget mouseover the eventtarget which the pointing device entered the eventtarget which the pointing device exited mouseout the eventtarget which the pointing device exited the eventtarget which the pointing device entered todo: also needs descriptions for dragenter and dragexit events. example <hbox id="outer"> <hbox id="inner" onmouseover="dump('mouseover ' + event.relatedtarget.id + ' > ' + event.target.id + '\n');" onmouseout="dump('mouseout ' + event.target.
Using files from web applications - Web APIs
prequest function send() is called to upload the file's content. asynchronously handling the file upload process this example, which uses php on the server side and javascript on the client side, demonstrates asynchronous uploading of a file. <?php if (isset($_files['myfile'])) { // example: move_uploaded_file($_files['myfile']['tmp_name'], "uploads/" . ...
FileException - Web APIs
in the file system api, a fileexception object represents error conditions that you might encounter while accessing the file system using the synchronous api. it extends the fileexception interface described in file writer and adds several new error codes. basic concepts synchronous apis do not have error callbacks, which makes it difficult to catch errors. the added complexity of using webworkers with this api makes debugging even more challenging. to simplify things a bit, wrap your worker code in a try/catch. when errors occur, forward them to the main app using postmessage() as in the following: function onerror(e) { postmessage('error:' + e.tostring()); } try { //error is thrown if "log.txt" already exists. var fileentry = fs.root.getfile('log.txt', {create: true, excl...
GlobalEventHandlers.onkeypress - Web APIs
urn event.charcode === 0 || /\d/.test(string.fromcharcode(event.charcode)); } const input = document.queryselector('input'); input.onkeypress = numbersonly; // prevent pasting (since pasted content might include non-number characters) input.onpaste = event => false; result capture the typing of a hidden word the following javascript function will do something after the user types the word "exit" in any point of a page. /* type the word "exit" in any point of your page... */ (function () { const ssecret = /* choose your hidden word...: */ "exit"; let noffset = 0; document.onkeypress = function(opevt) { let oevent = opevt || window.event, nchr = oevent.charcode, snodetype = oevent.target.nodename.touppercase(); if (nchr === 0 || oevent.target.cont...
GlobalEventHandlers.onpointerleave - Web APIs
this event is part of the pointer events api. syntax eventtarget.onpointerleave = leavehandler; var leavehandler = eventtarget.onpointerleave; value leavehandler the eventlistener which will be invoked to handle pointerleave events sent to the target. example this example shows two ways to use onpointerleave to set an element's pointerleave event handler. ...
GlobalEventHandlers - Web APIs
ent is raised. globaleventhandlers.ondrag is an eventhandler representing the code to be called when the drag event is raised. globaleventhandlers.ondragend is an eventhandler representing the code to be called when the dragend event is raised. globaleventhandlers.ondragenter is an eventhandler representing the code to be called when the dragenter event is raised. globaleventhandlers.ondragexit is an eventhandler representing the code to be called when the dragexit event is raised. globaleventhandlers.ondragleave is an eventhandler representing the code to be called when the dragleave event is raised. globaleventhandlers.ondragover is an eventhandler representing the code to be called when the dragover event is raised. globaleventhandlers.ondragstart is an eventhandler representi...
HTML Drag and Drop API - Web APIs
event on event handler fires when… drag ondrag …a dragged item (element or text selection) is dragged. dragend ondragend …a drag operation ends (such as releasing a mouse button or hitting the esc key; see finishing a drag.) dragenter ondragenter …a dragged item enters a valid drop target. (see specifying drop targets.) dragexit ondragexit …an element is no longer the drag operation's immediate selection target. dragleave ondragleave …a dragged item leaves a valid drop target. dragover ondragover …a dragged item is being dragged over a valid drop target, every few hundred milliseconds. dragstart ondragstart …the user starts dragging an item. (see starting a drag ...
HashChangeEvent - Web APIs
on.hash === '#somecoolfeature') { somecoolfeature(); } } window.addeventlistener('hashchange', locationhashchanged); polyfill there are several fallback scripts listed on the modernizr github page. basically, those scripts check the location.hash at a regular interval. here is a version that allows only one handler to be bound to the onhashchange property: ;(function(window) { // exit if the browser implements that event if ( "onhashchange" in window.document.body ) { return; } var location = window.location, oldurl = location.href, oldhash = location.hash; // check the location hash on a 100ms interval setinterval(function() { var newurl = location.href, newhash = location.hash; // if the hash has changed and a handler has been bound... ...
Checking when a deadline is due - Web APIs
l || minutes.value == null || day.value == '' || month.value == '' || year.value == null) { note.innerhtml += '<li>data not submitted — form incomplete.</li>'; return; } in this segment, we check to see if the form fields have all been filled in. if not, we drop a message into our developer notifications pane (see the bottom left of the app ui) to tell the user what is going on, and exit out of the function. this step is mainly for browsers that don't support html form validation (i have used the required attribute in my html to force validation, in those that do.) else { var newitem = [ { tasktitle: title.value, hours : hours.value, minutes : minutes.value, day : day.value, month : month.value, year : ...
Intersection Observer API - Web APIs
o libraries they are using. as the user scrolls the page, these intersection detection routines are firing constantly during the scroll handling code, resulting in an experience that leaves the user frustrated with the browser, the web site, and their computer. the intersection observer api lets code register a callback function that is executed whenever an element they wish to monitor enters or exits another element (or the viewport), or when the amount by which the two intersect changes by a requested amount. this way, sites no longer need to do anything on the main thread to watch for this kind of element intersection, and the browser is free to optimize the management of intersections as it sees fit. one thing the intersection observer api can't tell you: the exact number of pixels that ...
KeyboardEvent.charCode - Web APIs
and keyup events. in these cases, keycode is set instead. to get the code of the key regardless of whether it was stored in keycode or charcode, query the which property. characters entered through an ime do not register through keycode or charcode. actually with the chinese ime i'm using, entering the ime results in a keypress event with keycode = 229 and no other key events fire until the ime exits (which may happen after multiple characters are inputted). i'm not sure if other ime's work this way. for a list of the charcode values associated with particular keys, run example 7: displaying event object properties and view the resulting html table. specifications specification status comment document object model (dom) level 3 events specificationthe definiti...
MediaRecorder.mimeType - Web APIs
mimetype: 'video/mp4' } var mediarecorder = new mediarecorder(stream,options); m = mediarecorder; m.mimetype; // would return 'video/mp4' ... }) .catch(function(error) { console.log(error.message); }); changing line 14 to the following causes mediarecorder to try to use avc constrained baseline profile level 4 for video and aac-lc (low complexity) for audio, which is good for mobile and other possible resource-constrained situations. mimetype: 'video/mp4; codecs="avc1.424028, mp4a.40.2"' assuming this configuration is acceptable to the user agent, the value returned later by m.mimetype would then be video/mp4; codecs="avc1.424028, mp4a.40.2". specifications specification status comment mediastream recordingthe...
MediaStreamTrack: mute event - Web APIs
getelementbyid("timeline-widget").style.backgroundcolor = "#aaa"; }, false); musictrack.addeventlistener("unmute", event => { document.getelementbyid("timeline-widget").style.backgroundcolor = "#fff"; }, false); with these event handlers in place, when the track musictrack enters its muted state, the element with the id timeline-widget gets its background color changed to #aaa. when the track exits the muted state—detected by the arrival of an unmute event—the background color is restored to white. you can also use the onmute event handler property to set up a handler for this event; similarly, the onunmute event handler is available for setting up a handler for the unmute event. the following example shows this: musictrack.onmute = event => { document.getelementbyid("timeline-widg...
MediaStreamTrack: unmute event - Web APIs
getelementbyid("timeline-widget").style.backgroundcolor = "#aaa"; }, false); musictrack.addeventlistener("unmute", event => { document.getelementbyid("timeline-widget").style.backgroundcolor = "#fff"; }, false); with these event handlers in place, when the track musictrack enters its muted state, the element with the id timeline-widget gets its background color changed to #aaa. when the track exits the muted state—detected by the arrival of an unmuted event—the background color is restored to white. you can also use the onunmute event handler property to set up a handler for this event; similarly, the onmute event handler is available for setting up a handler for the mute event. the following example shows this: musictrack.onmute = event => { document.getelementbyid("timeline-widge...
PaymentResponse.retry() - Web APIs
essfully completed. the promise is rejected with an appropriate exception value if the payment fails again. typically you will use this by calling show(), then entering a loop or recursive function that checks the paymentresponse for errors or other reasons to retry the payment request. if a retry is needed, the loop calls retry(), then loops back to check the response when it comes in. the loop exits only when the user either cancels the payment request or the request is successful. see the example below for a thorough example, but the basic concept, in outline form, is: create a new paymentrequest (new paymentrequest()) display the payment request (paymentrequest.show() if show() resolves, the returned paymentresponse describes the requested payment and the options chosen by the user.
Multi-touch interaction - Web APIs
vent model for pointers can simplify creating web sites, applications and provide a good user experience regardless of the user's hardware. pointer events have many similarities to mouse events but they support multiple simultaneous pointers such as multiple fingers on a touch screen. this additional feature can be used to provide richer user interaction models but at the cost of additional complexity in the multi-touch interaction handling. this document demonstrates via example code, using pointer events with different multi-touch interactions. a live version of this application is available on github. the source code is available on github; pull requests and bug reports are welcome. example this example demonstrates using pointer events' various event types (pointerdown, pointermove, po...
RTCIceServers.urls - Web APIs
Web › API › RTCIceServer › urls
servers. syntax var iceserver = { urls = iceserverurl | [ url1, ..., urln ], username: "webrtc", // optional credential: "turnpassword" // optional }; iceservers.push(iceserver); the value of this property may be specified as a single url or as an array of multiple urls. examples let's look a few examples of varying complexity. a single ice server this example creates a new rtcpeerconnection which will use a stun server at stunserver.example.org to negotiate connections. mypeerconnection = new rtcpeerconnection({ iceservers: [ { urls: "stun:stunserver.example.org" } ] }); notice that only the urls property is provided; the stun server doesn't require authentication, so this is all that's needed. ...
TextTrack - Web APIs
Web › API › TextTrack
guese. texttrack.mode a domstring specifying the track's current mode. changing this property's value changes the track's current mode to match. permitted values are listed under text track mode constants. the default is disabled, unless the <track> element's default boolean attribute is specified, in which case the default mode is started. events cuechange fired when cues are entered and exited. a given text cue appears when the cue is entered and disappears when the cue is exited. also available via the oncuechange property. methods this interface also inherits methods from eventtarget. texttrack.addcue() adds a cue (specified as a texttrackcue object to the track's list of cues. texttrack.removecue() removes a cue (specified as a texttrackcue object from the track's list o...
TextTrackCue - Web APIs
k read only the texttrack that this cue belongs to, or null if it doesn't belong to any. texttrackcue.id a domstring that identifies the cue. texttrackcue.starttime a double that represents the video time that the cue will start being displayed, in seconds. texttrackcue.endtime a double that represents the video time that the cue will stop being displayed, in seconds. texttrackcue.pauseonexit a boolean for whether the video will pause when this cue stops being displayed. event handlers texttrackcue.onenter the event handler for the enter event. texttrackcue.onexit the event handler for the exit event. specifications specification status comment html living standardthe definition of 'texttrackcue' in that specification. living standard ...
Using Touch Events - Web APIs
t closely circumscribes a touch point's contact area with the touch surface. the touch point's rotation angle - the number of degrees of rotation to apply to the described ellipse to align with the contact area - is also be standardized as is the amount of pressure applied to a touch point. what about pointer events? the introduction of new input mechanisms results in increased application complexity to handle various input events, such as key events, mouse events, pen/stylus events, and touch events. to help address this problem, the pointer events standard defines events and related interfaces for handling hardware agnostic pointer input from devices including a mouse, pen, touchscreen, etc.. that is, the abstract pointer creates a unified input model that can represent a contact point for...
Getting started with WebGL - Web APIs
lor_buffer_bit); } window.onload = main; the first thing we do here is obtain a reference to the canvas, assigning it to a variable named canvas. once we have the canvas, we try to get a webglrenderingcontext for it by calling getcontext() and passing it the string "webgl". if the browser does not support webgl, getcontext() will return null in which case we display a message to the user and exit. if the context is successfully initialized, the variable gl is our reference to it. in this case, we set the clear color to black, and clear the context to that color (redrawing the canvas with the background color). at this point, you have enough code that the webgl context should successfully initialize, and you should wind up with a big black, empty box, ready and waiting to receive conten...
WebGL model view projection - Web APIs
rame is essentially created by starting with the set of all objects in the scene. then any objects which are entirely outside the viewing frustum are removed from the set. next, objects which partially extrude outside the viewing frustum are clipped by dropping any polygons which are entirely outside the frustum, and by clipping the polygons which cross outside the frustrum so that they no longer exit it. once that's been done, we have the largest set of polygons which are entirely within the viewing frustum. this list is usually further reduced using processes like back-face culling (removing polygons whose back side is facing the camera) and occlusion culling using hidden-surface determination (removing polygons which can't be seen because they're entirely blocked by polygons that are close...
Establishing a connection: The WebRTC perfect negotiation pattern - Web APIs
let's take a dive into the code to see how it works now. on receiving a description in the revised code, if the received message is an sdp description, we check to see if it arrived while we're attempting to transmit an offer. if the received message is an offer and the local peer is the impolite peer, and a collision is occurrin...
Signaling and video calling - Web APIs
ring. all your code needs to do is route it through to the remote peer using the signaling server. each ice message suggests a communication protocol (tcp or udp), ip address, port number, connection type (for example, whether the specified ip is the peer itself or a relay server), along with other information needed to link the two computers together. this includes nat or other networking complexity. note: the important thing to note is this: the only thing your code is responsible for during ice negotiation is accepting outgoing candidates from the ice layer and sending them across the signaling connection to the other peer when your onicecandidate handler is executed, and receiving ice candidate messages from the signaling server (when the "new-ice-candidate" message is received) and de...
WebXR application life cycle - Web APIs
each requestanimationframe() callback should use the information provided about the objects located in the 3d world to render the frame using webgl. each time the callback is invoked, it should call requestanimationframe() again in order to let the browser know that the callback needs to be run again when it's time to render the next frame. when the time comes (such as when the user exits your app or navigates away from your site), end the xr session; otherwise, continue the loop until the user chooses to exit xr mode. to end the xr session yourself, call xrsession.end(). include a handler for the xrsession event end event to be informed when the session is ending, regardless of whether your code, the user, or the browser initiated the termination of the session. ...
Spaces and reference spaces: Spatial tracking in WebXR - Web APIs
because the xr hardware lost connectivity for a time, resulting in the user's movements not being properly tracked for a while. upon recovery of tracking, a reset means tracking has been restored and the new position information represents the actual position information provided by the xr hardware, rather than cached or "best-guess" data. another reason reset may be sent is because the user has exited the bounds of a reference space and entered another reference space, or because the user has been transitioned programmatically from one reference space to another. any time the bounds geometry of the user's space changes, a reset is sent. reset is only used for signficant jumps or transitions; minor things will just be absorbed automatically. the event is always sent to every affected referen...
Using Web Workers - Web APIs
r now messages can be sent to the worker as before, but the postmessage() method has to be invoked through the port object (again, you'll see similar constructs in both multiply.js and square.js): squarenumber.onchange = function() { myworker.port.postmessage([squarenumber.value,squarenumber.value]); console.log('message posted to worker'); } now, on to the worker. there is a bit more complexity here as well (worker.js): onconnect = function(e) { var port = e.ports[0]; port.onmessage = function(e) { var workerresult = 'result: ' + (e.data[0] * e.data[1]); port.postmessage(workerresult); } } first, we use an onconnect handler to fire code when a connection to the port happens (i.e. when the onmessage event handler in the parent thread is setup, or when the start() method...
Window.confirm() - Web APIs
Web › API › Window › confirm
e and two buttons: ok and cancel. syntax result = window.confirm(message); parameters message a string you want to display in the alert dialog. return value a boolean indicating whether ok (true) or cancel (false) was selected. if a browser is ignoring in-page dialogs, then the returned value is always false. example if (window.confirm("do you really want to leave?")) { window.open("exit.html", "thanks for visiting!"); } produces: notes the following text is shared between this article, dom:window.prompt and dom:window.alert dialog boxes are modal windows — they prevent the user from accessing the rest of the program's interface until the dialog box is closed. for this reason, you should not overuse any function that creates a dialog box (or modal window). regardless, ...
Window.open() - Web APIs
Web › API › Window › open
valid for all browsers and more with variable conditions. firefox (50.0.1) functions as described: from the same domain+port reopen with same name will access the previously created window. google chrome (55.0.2883.87 m ) on the other hand will do it only from the same parent (as if the window was created dependent, which is the "opener"). this is a wide limitation and generates unbelievable complexity of development. firefox (51.) gets the handle but cannot run any element.focus() while chrome can run focus() from opener to child but not between siblings nor, reverse, from child to opener. this function is the lonely key to get back the handle on a window if the developer has access only to its name (the name can be saved with cookies or local storage but not the window object handle). for no...
XRBoundedReferenceSpace.boundsGeometry - Web APIs
the bounds on your own, as appropriate. boundary shape the shape defined by boundsgeometry may be as simple as a square or as complex as is needed, potentially including concave and/or convex sections. however, you can't represent spaces with uneven floor levels using xrboundedreferencespace. the ground is always at y = 0. it's important that your content not be designed to require the user to exit the bounds specified by boundsgeometry. however, if the user's surroundings permit them to move in such a way as to exit the defined bounds, your content must be able to gracefully handle the situation, which is not considered an error condition. although some samples render a mesh or other shape to display the bounds to the user, in a real-world application, you shouldn't do this. the browser, ...
XRInputSourceArray.values() - Web APIs
t index 0) and proceeding straight through the list. examples this example snippet walks through each input and calls the function checkinput() with each returned value. for (const source of xrsession.inputsources.values()) { checkinput(source); } here, for...of is used to iterate over the array's contents. each pass through the loop, source is the next xrinputsource in the list. the loop exits once every input has been delivered to checkinput(). specifications specification status comment webxr device apithe definition of 'xrinputsourcearray' in that specification.1 working draft xrinputsourcearray interface [1] see iterator-like methods in information contained in a webidl file for information on how an iterable declaration in an interface d...
XRReferenceSpace: reset event - Web APIs
the following: the user has manually reset the coordinate system, such as by requesting that the headset recalibrate itself to ensure that the facing direction and hand controllers are synchronized with the user's actual position and facing. this is primarily an issue for local or local-floor reference spaces. for a bounded-floor reference space, the coordinate system can be reset if the user exits the boundaries of the reference space and enters a new one (such as by crossing from one level to another in a game, where each level is its own map with its own coordinate system). the tracking system has temporarily lost the user, then regained them, but not until after they had moved enough to leave the immediate vicinity of the last-known position. primarily an issue for unbounded reference...
ARIA: timer role - Accessibility
es aria-activedescendant is used to manage the focus inside the application container. set in response to keyboard or other application events that change focus or point of interaction. the timer role does not have a related html widget and xxx. the author of the timer must take full responsibility for not letting users get stuck in a focus limbo or trap focus inside something the user cannot exit of. all aspects of interaction, including returning to the regular web content on other parts of the page, must be handled. use wisely, and cautiously! examples some prominent web timers include clocks, stop watches and countdowns, such as ticketing websites, e-commerce sites, and event countdowns (see https://countingdownto.com/). as an illustration of aria-atomic, consider a site with a sim...
ARIA: application role - Accessibility
manage the focus inside the application container. set in response to keyboard or other application events that change focus or point of interaction. the application role does not have a related html widget and thus is completely free form. the author of the application must take full responsibility for not letting users get stuck in a focus limbo or trap focus inside something the user cannot exit of. all aspects of interaction, including returning to the regular web content on other parts of the page, must be handled. use wisely, and cautiously! examples some prominent web applications that use the application role properly are: google docs, sheets and slides ckeditor and tinymce wysiwyg web editors, like the one used on the mozilla developer network some parts of gmail accessib...
Web Accessibility: Understanding Colors and Luminance - Accessibility
are physically located at a different location than the "blue" sensitive cones of our eyes, which are located away from the fovea and towards the rims. the electrical signals that go from eye to brain have much to resolve between them as the information is processed in our brains. in the article, certain colors more likely to cause epileptic fits, researchers find, the authors noted that "..complexities underlying brain dynamics could be modulated by certain color combinations more than the other, for example, red-blue flickering stimulus causes larger cortical excitation than red-green or blue-green stimulus.." adaption our eyes don't adapt equally, in the same way, going from light areas to dark ones, and vice versa. this is due to the physiological ways our eye are built. this affects...
Understandable - Accessibility
keyboard accessibility back in for some useful implementation ideas. 3.2.2 on input (a) when data is inputted into a control, or a setting is changed, context should not be changed unexpectedly. the user should be warned/advised of the impending change before it occurs. again, sensible design should be implemented. for example, if pressing a button causes the application to exit the current view, the user should be asked to confirm this action, save their work if appropriate, etc. globaleventhandlers.oninput is useful here. 3.2.3 consistent navigation (aa) navigation menu/control style and positioning should be consistent between different pages or views of a web page, and the existing items should appear in the same order, even if for example new...
@supports - CSS: Cascading Style Sheets
Web › CSS › @supports
> b) {} the not operator the not operator can precede any expression to create a new expression, resulting in the negation of the original one. the following example returns true if the browser's transform-origin property doesn't consider 10em 10em 10em valid: @supports not (transform-origin: 10em 10em 10em) {} as with any operator, the not operator can be applied to a declaration of any complexity. the following examples are both valid: @supports not (not (transform-origin: 2px)) {} @supports (display: grid) and (not (display: inline-grid)) {} note: there is no need to enclose the not operator between two parentheses at the top level. to combine it with other operators, like and and or, the parentheses are required. the and operator the and operator creates a new expression from the...
Coordinate systems - CSS: Cascading Style Sheets
user's screen geometry changes (by changing display resolution or by adding or removing monitors to their system). the mouseevent.screenx and mouseevent.screeny properties give the coordinates of a mouse event's position relative to the screen's origin. example let's take a look at an example. this simple example creates a set of nested boxes. whenever the mouse enters, moves around inside, or exits the inner box, the corresponding event is handled by updating a set of informational messages within the box, listing out the current mouse coordinates in each of the four available coordinate systems. javascript let's look at the script in two sections. first, the code that logs the coordinates to the screen. this code will be called by the event handler for the various mouse events we watch.
CSS Tutorials - CSS: Cascading Style Sheets
Web › CSS › Tutorials
learning css may be a daunting task. in order to help you, we have written numerous tutorials about css. some are aimed at complete beginners, while others present complex features to be used by more experienced users. this page lists them all, with a short description. they are grouped by complexity so that you can choose the most appropriate for your level. editor's note: we should look at using "difficulty level" tags on the tutorial/guide pages so that difficulty-based lists can be automatically built. beginner-level css tutorials getting started this guide is aimed at complete beginners: you haven't written one single line of css? — this is for you. it explains the fundamental concepts of the language and guides you in writing basic stylesheets. using multiple backgrou...
appearance (-moz-appearance, -webkit-appearance) - CSS: Cascading Style Sheets
safari datalist listitem div { color: black; -moz-appearance: listitem; -webkit-appearance: listitem; } <div>lorem</div> firefox chrome safari edge media-enter-fullscreen-button div{ color: black; -webkit-appearance: media-enter-fullscreen-button; } <div>lorem</div> chrome safari media-exit-fullscreen-button div{ color: black; -webkit-appearance: media-exit-fullscreen-button; } <div>lorem</div> chrome safari media-fullscreen-volume-slider div{ color: black; -moz-appearance: media-fullscreen-volume-slider; -webkit-appearance: media-fullscreen-volume-slider; } <div>lorem</div> safari media-full...
set:intersection() - EXSLT
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes set:intersection() returns the intersection of two node-sets. in other words, it returns a node-set containing all the nodes that exits in both nodeset1 and nodeset2. syntax set:intersection(nodeset1, nodeset2) arguments nodeset1 the first node-set. nodeset2 the second node-set. returns a node-set containing the nodes that existed in both nodeset1 and in nodeset2. specifications exslt - set:intersection ...
Sets (set) - EXSLT
Web › EXSLT › set
...
Event reference
beforeinstallprompt event chrome specific a user is prompted to save a website to a home screen on mobile. dommousescroll mozilla specific the wheel button of a pointing device is rotated (detail attribute is a number of lines). (use wheel instead) dragdrop dragevent mozilla specific an element is dropped (use drop instead). dragexit dragevent mozilla specific a drag operation is being ended (use dragend instead). draggesture dragevent mozilla specific the user starts dragging an element or text selection (use dragstart instead). mousewheel ie invented the wheel button of a pointing device is rotated. mozaudioavailable event mozilla specific the audio buffe...
Global attributes - HTML: Hypertext Markup Language
these are inherited from the xhtml specifications and deprecated, but kept for compatibility purposes. the multiple aria-* attributes, used for improving accessibility. ...
Evolution of HTTP - HTTP
lications in their own right. the amount of visual media displayed, the volume and size of scripts adding interactivity, has also increased: much more data is transmitted over significantly more http requests. http/1.1 connections need requests sent in the correct order. theoretically, several parallel connections could be used (typically between 5 and 8), bringing considerable overhead and complexity. for example, http pipelining has emerged as a resource burden in web development. in the first half of the 2010s, google demonstrated an alternative way of exchanging data between client and server, by implementing an experimental protocol spdy. this amassed interest from developers working on both browsers and servers. defining an increase in responsiveness, and solving the problem of duplica...
HTTP caching - HTTP
Web › HTTP › Caching
n their url, usually in the filename, a revision (or version) number is added. that way each new revision of this resource is considered as a resource on its own that never changes and that can have an expiration time very far in the future, usually one year or even more. in order to have the new versions, all the links to them must be changed, that is the drawback of this method: additional complexity that is usually taken care of by the tool chain used by web developers. when the infrequently variable resources change they induce an additional change to often variable resources. when these are read, the new versions of the others are also read. this technique has an additional benefit: updating two cached resources at the same time will not lead to the situation where the out-dated version ...
HTTP conditional requests - HTTP
expected, for example when resuming a download. weak validation is used when the user-agent only needs to determine if the two resources have the same content. this is even if they are minor differences; like different ads, or a footer with a different date. the kind of validation is independent of the validator used. both last-modified and etag allow both types of validation, though the complexity to implement it on the server side may vary. http uses strong validation by default, and it specifies when weak validation can be used. strong validation strong validation consists of guaranteeing that the resource is, byte to byte, identical to the one it is compared too. this is mandatory for some conditional headers, and the default for the others. strong validation is very strict and may b...
CSP: report-uri - HTTP
$current_domain . ":\n\n" . $json_data . "\n\nfurther cps violations will be logged to the following log file, but no further email notifications will be sent until this log file is deleted:\n\n" . $log_file; mail($email_address, $email_subject, $message, 'content-type: text/plain;charset=utf-8'); } else if (filesize($log_file) > $log_file_size_limit) { exit(0); } file_put_contents($log_file, $json_data, file_append | lock_ex); } specifications specification status comment content security policy level 3the definition of 'report-uri' in that specification. working draft no changes. content security policy level 2the definition of 'report-uri' in that specification. recommendation initial definitio...
Control flow and error handling - JavaScript
ecuted, and then continues execution at the statement following switch. if break is omitted, the program continues execution inside the switch statement (and will evaluate the next case, and so on). example in the following example, if fruittype evaluates to 'bananas', the program matches the value with case 'bananas' and executes the associated statement. when break is encountered, the program exits the switch and continues execution from the statement following switch. if break were omitted, the statement for case 'cherries' would also be executed. switch (fruittype) { case 'oranges': console.log('oranges are $0.59 a pound.'); break; case 'apples': console.log('apples are $0.32 a pound.'); break; case 'bananas': console.log('bananas are $0.48 a pound.'); brea...
Loops and iteration - JavaScript
s similar to the java and c for loop. a for statement looks as follows: for ([initialexpression]; [conditionexpression]; [incrementexpression]) statement when a for loop executes, the following occurs: the initializing expression initialexpression, if any, is executed. this expression usually initializes one or more loop counters, but the syntax allows an expression of any degree of complexity. this expression can also declare variables. the conditionexpression expression is evaluated. if the value of conditionexpression is true, the loop statements execute. if the value of condition is false, the for loop terminates. (if the condition expression is omitted entirely, the condition is assumed to be true.) the statement executes. to execute multiple statements, use a block statement (...
Warning: unreachable code after return statement - JavaScript
the developer intended to return the statement on the following line, or to stop execution and return. the warning indicates that there is ambiguity in the way the return statement is written. ...
Array.prototype.sort() - JavaScript
the source for this interactive example is stored in a github repository. ...
for...of - JavaScript
/ a generator function let [prev, curr] = [0, 1]; while (true) { [prev, curr] = [curr, prev + curr]; yield curr; } } for (const n of fibonacci()) { console.log(n); // truncate the sequence at 1000 if (n >= 1000) { break; } } do not reuse generators generators should not be re-used, even if the for...of loop is terminated early, for example via the break keyword. upon exiting a loop, the generator is closed and trying to iterate over it again does not yield any further results. const gen = (function *(){ yield 1; yield 2; yield 3; })(); for (const o of gen) { console.log(o); break; // closes iterator } // the generator should not be re-used, the following does not make sense! for (const o of gen) { console.log(o); // never called. } iterating over ...
function* - JavaScript
ou can also define generator functions using the generatorfunction constructor, or the function expression syntax. syntax function* name([param[, param[, ... param]]]) { statements } name the function name. param optional the name of a formal parameter for the function. statements the statements comprising the body of the function. description generators are functions that can be exited and later re-entered. their context (variable bindings) will be saved across re-entrances. generators in javascript -- especially when combined with promises -- are a very powerful tool for asynchronous programming as they mitigate -- if not entirely eliminate -- the problems with callbacks, such as callback hell and inversion of control. however, an even simpler solution to these problems can...
Digital audio concepts - Web media technologies
ques. the majority of audio codecs use some form of lossy compression, because of the better compression ratio those algorithms offer. whereas lossless compression algorithms usually manage no better than a 40-50% of the size of the original, uncompressed sound data, modern lossy compression algorithms can reduce the size of the audio to between 5-20% of the original size, depending on the complexity of the audio. the vastly superior compression ratios possible with lossy compression usually make it a compelling choice, and adequate or excellent audio quality is possible with well-chosen codec configurations. researchers are continuing to devise better ways to analyze and compress audio, so new formats come out periodically that offer various improvements, either in compression ratio or aud...
Web video codec guide - Web media technologies
orks by comparing frames, finding where they differ, and constructing records containing enough information to update the previous frame to approximate the appearance of the following frame. the more successive frames differ from one another, the larger these differences are, and the less effective the compression is at avoiding the introduction of artifacts into the compressed video. the complexity introduced by motion results in larger intermediate frames due to the higher number of differences between frames). for this and other reasons, the more motion there is in a video, the larger the output file will typically be. noise picture noise (such as film grain effects, dust, or other grittiness to the image) introduces variability. variability generally makes compression more d...
Lazy loading - Web Performance
thin the visual viewport that haven't yet loaded. you can determine if a given image has finished loading by examining the value of its boolean complete property. polyfill include this polyfill to provide support for older and currently incompatible browsers: loading-attribute-polyfill intersection observer api intersection observers allow the user to know when an observed element enters or exits the browser’s viewport. event handlers when browser compatibility is crucial, there are a few options: polyfill intersection observer fallback to scroll, resize or orientation change event handlers to determine if a specific element is in viewport specifications specification status comment html living standard living standard ...
Understanding latency - Web Performance
secure connection, the additional time needed for a secure connection is worth it. sending is the time taken to send the http request to the server. waiting is disk latency, the time it took for the server to complete its response. disk latency used to be the main area of performance concern. however server performance has improved as computer memory, or cpu, has improved. depending on the complexity of what is needed from the server, this can still be an issue. receiving is the time it takes to download the asset. the receiving time is determined by a combination of the network capacity and the asset file size. if the image been cached, this would have been nearly instantaneous. had we throttled, receiving could have been 43seconds! measuring latency network latency is the time it takes ...
Privacy, permissions, and information security
s the <iframe> element to embed content from another site inside your own, especially if the document you load into the frame has its own permission needs to consider. while specifications 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 ...
Graphic design for responsive sites - Progressive web apps (PWAs)
d in older browsers like ie6-8, but they generally degrade gracefully, are fairly easy to write, and become much more flexible and powerful when combined with javascript and other technologies. javascript javascript has functions that enable developers to create animations, and any other type of interactivity you want. it is very powerful when combined with other technologies, although its complexity is a barrier for non-developers. svg svg, just like html/css, can be manipulated via javascript. so adding interactivity is not difficult. you can also add links direcly into svg and can create animations using smil (synchronized multimedia intergration language). webgl/canvas you can create a canvas to draw interactive graphics on using the html <canvas> element, then use the canvas api to ...
SVG Event Attributes - SVG: Scalable Vector Graphics
Web › SVG › Attribute › Events
s. all event attribute are not animatable. ...
SVG Attribute reference - SVG: Scalable Vector Graphics
Web › SVG › Attribute
to, by, autoreverse, accelerate, decelerate animation addition attributes additive, accumulate event attributes animation event attributes onbegin, onend, onrepeat 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, onse...
Referer header: privacy and security concerns - Web security
eferrerpolicy attribute on html elements that are in danger of leaking such information (such as <img> and <a>). this can for example be set to no-referrer to stop the referer header being sent altogether. the rel attribute set to noreferrer on html elements that are in danger of leaking such information (such as <img> and <a>). see link types and search for noreferrer for more information. the exit page technique. security-conscious server-side frameworks tend to have built in mitigations for such problems, for example: security in django (especially see cross site request forgery (csrf) protection). helmetjs referrer-policy — middleware for setting referrer-policy in node.js/express apps (see also helmetjs for more security provisions). policy and requirements it would make sens...