13.3 Accessing JavaScript from Prolog
AllApplicationManualNameSummaryHelp

  • Documentation
    • Reference manual
      • Using SWI-Prolog in your browser (WASM)
        • Accessing JavaScript from Prolog
          • :=/2
          • is_object/1
          • is_object/2
          • js_script/2
          • fetch/3
          • Asynchronous access to JavaScript from Prolog
          • JavaScript Promise that can be aborted
    • Packages
Left := Right
Depending on Left, this predicate implements two different actions. If Left is a Prolog variable, it evaluates the expression Right in JavaScript and unifies the result to Left. If Left is a term Obj[Key], where Key is an atom, it accesses a JavaScript setter. The general form of an expression is Expression[Callable] or simply Callable. If Callable is compound it expresses a function (or method) call. Otherwise we call JavaScript eval(), except for these special values:
window
The main browser window itself (undefined when not in a browser).
prolog
The Prolog instance.

Prolog values are translated according to the rules in section 13.2.2.2 and the result is translated back to Prolog according to the rules in section 13.2.2.1. Because callables are translated to function calls, object properties or global variables we need an escape to pass them as data. This is achieved using the prefix operator #. Note that lists are passed as JavaScript arrays rather than calls to the list functor. For convenience Prolog strings are by default translated to JavaScript String objects rather than Prolog.String instances. Below are some examples:

?- Res := myfunc([1,2,3]).
?- Max := 'Math'.max(10, 20).
?- Out := document.getElementById('output').
?- Par := document.createElement(p),
   Par.textContent := #Text.
?- Par.textContent := "aap" + " " + "noot".

Some JavaScript expressions are not implemented as functions. The following “functions'' are handled directly by the implementation.

instanceof
Returns the name of the class to which the object belongs. Same as Obj.constructor.name.
instanceof(ClassName)
Returns a Boolean indicating whether the object is an instance of ClassName. Note that the class name must be an atom and as JavaScript class names normally start with a capital, the names dypically need to be quoted using single quotes. For example:
?- W := window, T := W.instanceof('Window').
W = <js_Window>(1),
T = true.
-(Any)
Numerical negation
!(Any)
Logical negation.
+(Any, Any)
-(Any, Any)
*(Any, Any)
/(Any, Any)
&(Any, Any)
|(Any, Any)
&&(Any, Any)
||(Any, Any)
Binary operators. Note that some are not defined as Prolog operators and thus one must write e.g. A := &&(true,false). || is not a Prolog atom, so logical disjunction gets A := '||'(false,false).