User JavaScript

Last update: 2012-06-02

While User JavaScript is still supported in Opera, extensions are the preferred method for adding custom JavaScript. Support for extensions is more robust and receives frequent updates and enhancements.

Contents

  1. The UserJSEvent object

  2. Available methods, events, and properties:

Important note: When using includes, files will be loaded in alphabetical order.

The UserJSEvent object

This is the event object passed to User JavaScript event handler functions (it is also available through window.event). As well as the usual event object properties, it has a few that are specific to User JavaScript events. While many of the properties serve little purpose in User JavaScript (for example, the currentTarget, srcElement, and target properties all reference window.opera), the following properties and methods are the most useful:

element
  • Object, readonly: the script, object, embed, style, or link elements.
  • All the usual DOM methods are available, such as getAttribute and setAttribute.
  • Available for BeforeExternalScript, BeforeScript, AfterScript, PluginInitialized, BeforeCSS and AfterCSS events.
element.text
  • String, read-write: the script that is about to be executed.
  • Available for BeforeScript and AfterScript events.
  • Unlike normal page scripts, User JavaScripts are allowed to see the script source from any domain, not just those that are served from the same domain as the current page.
  • Note: behavior is different from the one specified in DOM 3 Core
event
  • Object, readonly: the regular event object.
  • Available for BeforeEvent, AfterEvent, BeforeEventListener and AfterEventListener events.
eventCancelled
  • Boolean, readonly: says if an event handler has canceled the event.
  • Available for AfterEvent events.
listener
  • Function, readonly: a reference to the event handler function.
  • Available for BeforeEventListener and AfterEventListener events.
preventDefault
  • Function, readonly: Prevents the default action, for example;
    • Prevents a script from being executed
    • Prevents an event from firing
    • Prevents an event handler from blocking a form submission
    • Prevents a stylesheet from being parsed and applied to the document
  • Available for all events, but has no effect with AfterScript and AfterCSS events.
propagationStopped
  • Boolean, read-write: says if an event handler has stopped propagation of the event.
  • Available for AfterEventListener events.
returnValue
  • String, read-write: the value returned by the script.
  • Available for AfterJavascriptURL events.
source
  • String, read-write: the script that is about to execute or has been executed.
  • Available for BeforeJavascriptURL and AfterJavascriptURL events.
type
  • String, readonly: the type of the event that was detected; for example, BeforeJavascriptURL.
  • Available for all events.
cssText
  • String, writable: the stylesheet CSS contents
  • Available for BeforeCSS and AfterCSS events.

window.opera.defineMagicVariable

This method can be used by User JavaScripts to override global variables defined by regular scripts. It accepts three parameters:

Name
String giving the name of the variable to be overridden.
Getter
Function to be run whenever a script attempts to access the contents of the variable. Any value returned by the function is used as the value of the variable. The function will be passed a single parameter; the current value of the variable.
Setter
Optional; function to be run whenever a script attempts to set the value of the variable. The function will be passed a single parameter; the value that the script was attempting to assign to the variable. If no setter function is required, the value null must be used instead.

For example:

window.opera.defineMagicVariable('isGoodBrowser', function (curVal)
{
  return true;
}, function (newVal)
{
  if (!newVal)
  {
    window.status = 'Repairing script';
  }
});

window.opera.defineMagicFunction

This method can be used by User JavaScripts to override global functions defined by regular scripts. It accepts two parameters:

Name
String giving the name of the variable to be overridden.
Implementation
Function to be run in place of the function defined by the page. The function will be passed the following parameters:
  • A reference to the real function defined by the page.
  • The object that would have been referred to by the this keyword in the real function.
  • Any parameters that would have been passed to the real function (each is passed as a separate parameter to the magic function).

For example:

window.opera.defineMagicFunction('getLayer', function (oRealFunc, oThis, oParam1, oParam2)
{
  return oParam1.getElementById(oParam2).style;
});

This example overrides a function f. If the this object refers to the window object, it returns false. Otherwise it just runs the real function instead:

window.opera.defineMagicFunction('f', function (real, thisObject)
{
  if (thisObject == window)
  {
    return false;
  }
  else
  {
    return real.apply(thisObject, Array.prototype.slice.call(arguments, 2));
  }
});

window.opera.addEventListener

This is the generic method used to add listeners for User JavaScript events. When an event is detected, the event handler is passed a UserJSEvent object (which is also available through window.event). In addition to the usual event properties, the UserJSEvent object may also populate the element, event, listener, eventCancelled, propagationStopped, source and returnValue properties, depending on what type of event was being detected. Some events can be canceled using preventDefault, and this may be used to prevent the script or event handler from being executed.

Listeners for the User JavaScript events can be added almost anywhere within a User JavaScript file. Listeners can not be added by the handler functions for regular events, or by scripts activated by timers. The following events can be detected:

BeforeExternalScript
  • Fired when a script element with a src attribute is encountered.
  • The script element is available as the element attribute of the UserJSEvent.
  • If canceled, the external source is not loaded and the script element is not executed.
  • In addition, if it is canceled, the BeforeScript and AfterScript events will not fire.
BeforeScript
  • Fired before a script element is executed.
  • The script element is available as the element attribute of the UserJSEvent.
  • The content of the script is available as the text property of the script element, and is also writable. Do note that this behavior is different from the one specified in DOM 3 Core by design, but only during the BeforeScript and AfterScript events. Usage example follows:
    window.opera.addEventListener('BeforeScript', function(userJSEvent){
      userJSEvent.element.text = userJSEvent.element.text
        .replace(/function\s+window\.onload\(/g,'window.onload = function(');
    }, false);
  • The BeforeScript event is fired for inline scripts as well as external scripts, including scripts with a type that Opera normally does not execute (such as VBScript). If the type is changed to something recognizable (only JavaScript currently), and the contents changed to match the new script type, then the script will execute.
  • If canceled, the script element is not executed.
AfterScript
  • Fired after a script element has finished executing.
  • The script element is available as the element attribute of the UserJSEvent.
  • Modifying the text property of the element attribute of the UserJSEvent has no effect, unlike the BeforeScript event.
BeforeEvent
  • Fired before a regular event is fired, regardless of whether such an event would be handled by any event handlers.
  • The regular event is available as the event attribute of the UserJSEvent.
  • If canceled, the regular event is not fired, its default action is performed, and any associated BeforeEventListener events are not fired.
BeforeEvent.type
  • Like BeforeEvent, but fired only for events of the specified type (for example, BeforeEvent.click).
  • In Opera 8, if any listeners are registered for a matching BeforeEvent.type event, no BeforeEvent event is fired.
  • In Opera 9 and in later releases, both will fire.
AfterEvent
  • Fired after a regular event has been fired and handled but before its default action has been performed.
  • The regular event is available as the event attribute of the UserJSEvent.
  • If canceled, any attempts by a regular event handler to cancel the regular event will be ignored.
  • The UserJSEvent object will also have the eventCancelled property, that will be set to true if any regular event handlers have canceled the event. This feature is duplicated by defaultPrevented from DOM 3 Events, but kept for legacy reasons.
AfterEvent.type
  • Like AfterEvent, but fired only for events of the specified type (for example, AfterEvent.click).
  • In Opera 8, if any listeners are registered for a matching AfterEvent.type event, no AfterEvent event is fired.
  • In Opera 9 and later releases, both will fire.
BeforeEventListener
  • Fired before a listener for a regular event is called.
  • The regular event is available as the event attribute of the UserJSEvent, and the listener to be invoked is available as the listener attribute of the UserJSEvent.
  • If canceled, the regular event listener will not be called.
BeforeEventListener.type
  • Like BeforeEventListener, but fired only for events of the specified type (for example, BeforeEventListener.click).
  • In Opera 8, if any listeners are registered for a matching BeforeEventListener.type event, no BeforeEventListener event is fired.
  • In Opera 9 and later releases, both will fire.
AfterEventListener
  • Fired after a listener for regular event is called.
  • The regular event is available as the event attribute of the UserJSEvent, and the listener to be invoked is available as the listener attribute of the UserJSEvent.
  • If canceled, any attempts by a regular event handler to cancel the regular event propagation will be ignored.
  • The UserJSEvent object will also have the propagationStopped property, that will be set to true if any regular event handlers have canceled the event propagation.
AfterEventListener.type
  • Like AfterEventListener, but fired only for events of the specified type (for example, AfterEventListener.click).
  • In Opera 8, if any listeners are registered for a matching AfterEventListener.type event, no AfterEventListener event is fired.
  • In Opera 9 and later releases, both will fire.
BeforeJavascriptURL
  • Fired before a javascript: URL is executed.
  • The JavaScript code to be executed (everything after the javascript: in the URL) is available as the source attribute of the UserJSEvent, and is also writable.
  • If canceled, the javascript: URL is not executed.
AfterJavascriptURL
  • Fired after a javascript: URL is executed.
  • The JavaScript code that was executed (everything after the javascript: in the URL) is available as the source attribute of the UserJSEvent, and any value returned by that code is available as the returnValue attribute of the UserJSEvent.
  • The returnValue is also writable.
  • If canceled, any returned value will not be used as the source of a new page.
PluginInitialized
  • Fired after a plug-in instance has been initialized.
  • The element which represents the plug-in instance is available as the element attribute of the UserJSEvent.
BeforeCSS
  • Fired before a CSS style sheet is parsed.
  • The element attribute of the UserJSEvent refers either to the style or the link elements that include the styles in the document. For style sheets imported using a CSS import rule, a placeholder link element is returned which provides access to the style sheet url, media, and other properties.
  • The content of the style sheet is available in the cssText property of the UserJSEvent object, and is also writable. Usage example follows:
    window.opera.addEventListener('BeforeCSS', function(userJSEvent){
      userJSEvent.cssText = userJSEvent.cssText
        .replace(/-(moz|ms|webkit|o)-(border|text-overflow)/g,'$2')
        .replace(/-(moz|ms|webkit)-(gradient|transform|transition)/g,'-o-$2');
    }, false);
  • If canceled, the style sheet element is not parsed and its styles are not applied to the page.
  • While a BeforeCSS event is being processed for a given style sheet, changes to that style sheet, like changing textContent on the style element, will only be applied after the BeforeCSS event, if it is not canceled.
AfterCSS
  • Fired after a CSS style sheet is parsed, if the respective BeforeCSS event was not canceled.
  • The element attribute of the UserJSEvent refers either to the style or the link elements that include the styles in the document. For style sheets imported using a CSS import rule, a placeholder link element is returned which provides access to the style sheet url, media, and other properties.
  • The content of the style sheet is available in the cssText property of the UserJSEvent object.
  • Modifying the cssText property of the event object triggers a new BeforeCSS event.

window.opera.removeEventListener

This can be used to remove User JavaScript event listeners that were added using window.opera.addEventListener. This cannot be used if the event listener was added as an anonymous function. For further details, see the W3C DOM Level 2 Events - Event registration interfaces specification.

window.opera.scriptStorage

This property returns a Storage object as specified in the W3C Web Storage API, unique per script. User scripts can use this object to share persistent data across domains. Script storage objects currently do not fire storage events. This property is available in the Opera Presto 2.6 rendering engine; see Web specifications support in Opera Presto 2.6: Web Storage.

The scriptStorage object is available only during the main User JavaScript thread, being therefore accessible only in the main body of the user script. To access the storage object later, keep a reference to the object.

(function(opera, storage)
  {
    if (storage)
      storage.key = 'value';
    /* Rest of script */
  }
)(opera, opera.scriptStorage);

The scriptStorage object has a limited quota, defined in opera:config. If the quota is 0, the object is not accessible. To see all storage objects created by user scripts, refer to opera:webstorage.

window.opera.setOverrideHistoryNavigationMode

This method can be used by User JavaScripts to set what history navigation mode Opera should use for the current document. It accepts one parameter:

Mode
One of automatic, compatible, or fast.

See the knowledge base article for more details.

window.opera.getOverrideHistoryNavigationMode

Retrieves the last value of history navigation mode that was set for the current document using setOverrideHistoryNavigationMode. Defaults to automatic.

Documentation

Opera Help

Need help? Hit F1 anytime while using Opera to access our online help files, or go here.