Components All New MacOS Windows Linux iOS
Examples Mac & Win Server Client Guides Statistic FMM Blog Deprecated Old

WebView.RunJavaScript

Executes the Javascript on the specified webViewer control.

Component Version macOS Windows Linux Server iOS SDK
WebView 1.3 ✅ Yes ✅ Yes ❌ No ❌ No ✅ Yes
MBS( "WebView.RunJavaScript"; WebViewerRef; Javascript { ; Async } )   More

Parameters

Parameter Description Example Flags
WebViewerRef Either the Web Viewer Object Name or the Web Viewer ID as returned by "WebView.FindByName" function.
Javascript The Javascript to be executed
Async Available in MBS FileMaker Plugin 10.0 or newer.
Whether to run asynchronously.
On MacOS and iOS you can choose between running sync and waiting for result (and returns result) or running asnychronously and returning just OK.

For older WebKit 1.x in FileMaker 15 or older or web viewers created with WebView.Create function, we always use synchronous mode.

Windows is always synchronously.

Default is 0 for synchronous mode.
0 Optional

Description

Executes the Javascript on the specified webViewer control.
Allows you to call any Javascript function that is in loaded in the WebViewer OR you can just run arbitrary JavaScript on an empty web page. The results of the JavaScript are returned on Macintosh only. There is another function called WebView.RunJavaScriptReturnTitle which can be used to return the value of a Javascript function on both platforms. Use "\n" in javascript strings for a newline character.

Does not work on Web Direct!

See newer WebView.Evaluate function which works better on Windows and returns results.
Check JS Functions for JavaScript engine for cross platform code to run without web viewer.

Version 10.0 or newer return result on MacOS/iOS if possible in original data type, so numbers are returned as number and not as text. We try to return array or objects as JSON.

For Windows with Edge browser or Web Direct, you may use the Perform JavaScript script step in FileMaker 19 instead.

Examples

Set the htmlcode of a field as string:

MBS( "WebView.RunJavaScript"; "browser"; "document.getElementById('td_ProcName_v').innerHTML='hello';" )

Run JavaScript

Let(
[

// very simple javascript

javascript = "alert('OK');";

webViewerName = "myWebViewer";
windowRef = MBS("Window.FindByTitle"; Get ( WindowName ));
webViewerID = MBS("WebView.FindByName"; windowRef; webViewerName)

];
Case(
webViewerID = 0; "Web Viewer \"" & webViewerName & "\" Not Found: " &windowRef ;

MBS("WebView.RunJavaScript"; webViewerID; javaScript)

)

)

Send change event to send to a field with ID $FieldID so javascript code on webpage knows we changed something:

MBS( "WebView.RunJavaScript" ; "web";
"var o = document.getElementById('" & $FieldID & "');
                var evt = document.createEvent('Events');
                evt.initEvent('change', true, true);
                o.dispatchEvent(evt); ")

Clear onBeforeLoad event handler:

MBS( "WebView.RunJavaScript" ; "HTMLEditor"; "window.onbeforeunload = null;")

Send click event:

MBS( "WebView.RunJavaScript" ; "browser"; "var o = document.forms[0].loginButton;
        if (document.createEvent)
        {
                var evt = document.createEvent('Events');
                evt.initEvent('click', true, true);
                o.dispatchEvent(evt);
          }")

Filling a complex form of a web app with help of Javascript:

# go to Vouchers
Imposta variabile [ $r ; Valore: MBS( "WebView.RunJavaScript" ; "browser"; "var o = document.getElementsByClassName('appGlobalSideNav')[0].getElementsByTagName('a')[2]; if (document.createEvent) { var evt = document.createEvent('Events'); evt.initEvent('click', tr… ]
Pausa/continua lo script [ Durata (secondi): ,3 ]
# open popup
Imposta variabile [ $r ; Valore: MBS( "WebView.RunJavaScript" ; "browser"; "document.getElementsByClassName('appMainButton')[0].click();") ]
Pausa/continua lo script [ Durata (secondi): ,3 ]
# Set Values in various fields and trigger change/click events
Imposta variabile [ $r ; Valore: MBS( "WebView.SetFormInputValue" ; "browser"; "vouchersCreateCtrl.form"; "number"; "1") ]
Imposta variabile [ $r ; Valore: MBS( "WebView.RunJavaScript" ; "browser"; "var o = document.forms[0].number; if (document.createEvent) { var evt = document.createEvent('Events'); evt.initEvent('change', true, true); o.dispatchEvent(evt); }") ]
Imposta variabile [ $r ; Valore: MBS( "WebView.SetFormSelectValue" ; "browser"; "vouchersCreateCtrl.form"; "quota"; "0") ]
Imposta variabile [ $r ; Valore: MBS( "WebView.SetFormSelectValue" ; "browser"; "vouchersCreateCtrl.form"; "expire"; "custom") ]
Imposta variabile [ $r ; Valore: MBS( "WebView.RunJavaScript" ; "browser"; "var o = document.forms[0].expire; if (document.createEvent) { var evt = document.createEvent('Events'); evt.initEvent('change', true, true); o.dispatchEvent(evt); }") ]
Pausa/continua lo script [ Durata (secondi): ,3 ]
Imposta variabile [ $r ; Valore: MBS( "WebView.SetFormInputValue" ; "browser"; "vouchersCreateCtrl.form"; "expire_number"; "2") ]
Imposta variabile [ $r ; Valore: MBS( "WebView.SetFormSelectValue" ; "browser"; "vouchersCreateCtrl.form"; "expire_unit"; "1440") ]
Imposta variabile [ $r ; Valore: MBS( "WebView.RunJavaScript" ; "browser"; "var o = document.forms[0].expire_number; if (document.createEvent) { var evt = document.createEvent('Events'); evt.initEvent('change', true, true); o.dispatchEvent(evt); }") ]
Imposta variabile [ $r ; Valore: MBS( "WebView.RunJavaScript" ; "browser"; "document.forms[0].limitDownload.checked = true;") ]
Imposta variabile [ $r ; Valore: MBS( "WebView.RunJavaScript" ; "browser"; "var o = document.forms[0].limitDownload; if (document.createEvent) { var evt = document.createEvent('Events'); evt.initEvent('click', true, true); o.dispatchEvent(evt); }") ]
Pausa/continua lo script [ Durata (secondi): ,1 ]
Imposta variabile [ $r ; Valore: MBS( "WebView.SetFormInputValue" ; "browser"; "vouchersCreateCtrl.form"; "down"; "512") ]
Imposta variabile [ $r ; Valore: MBS( "WebView.RunJavaScript" ; "browser"; "var o = document.forms[0].down; if (document.createEvent) { var evt = document.createEvent('Events'); evt.initEvent('change', true, true); o.dispatchEvent(evt); }") ]
Pausa/continua lo script [ Durata (secondi): ,1 ]
Imposta variabile [ $r ; Valore: MBS( "WebView.RunJavaScript" ; "browser"; "document.forms[0].limitUpload.checked = true;") ]
Imposta variabile [ $r ; Valore: MBS( "WebView.RunJavaScript" ; "browser"; "var o = document.forms[0].limitUpload; if (document.createEvent) { var evt = document.createEvent('Events'); evt.initEvent('click', true, true); o.dispatchEvent(evt); }") ]
Pausa/continua lo script [ Durata (secondi): ,1 ]
Imposta variabile [ $r ; Valore: MBS( "WebView.SetFormInputValue" ; "browser"; "vouchersCreateCtrl.form"; "up"; "512") ]
Imposta variabile [ $r ; Valore: MBS( "WebView.RunJavaScript" ; "browser"; "var o = document.forms[0].up; if (document.createEvent) { var evt = document.createEvent('Events'); evt.initEvent('change', true, true); o.dispatchEvent(evt); }") ]
Pausa/continua lo script [ Durata (secondi): ,1 ]
Imposta variabile [ $r ; Valore: MBS( "WebView.RunJavaScript" ; "browser"; "document.forms[0].byteQuota[0].checked = true;") ]
Imposta variabile [ $r ; Valore: MBS( "WebView.RunJavaScript" ; "browser"; "var o = document.forms[0].byteQuota[0]; if (document.createEvent) { var evt = document.createEvent('Events'); evt.initEvent('click', true, true); o.dispatchEvent(evt); }") ]
Pausa/continua lo script [ Durata (secondi): ,1 ]
Imposta variabile [ $r ; Valore: MBS( "WebView.SetFormInputValue" ; "browser"; "vouchersCreateCtrl.form"; "byteQuota"; "123") ]
Imposta variabile [ $r ; Valore: MBS( "WebView.RunJavaScript" ; "browser"; "var o = document.forms[0].byteQuota[1]; if (document.createEvent) { var evt = document.createEvent('Events'); evt.initEvent('change', true, true); o.dispatchEvent(evt); }") ]
Imposta variabile [ $r ; Valore: MBS( "WebView.SetFormInputValue" ; "browser"; "vouchersCreateCtrl.form"; 8; "CLIENTE") ]
Imposta variabile [ $r ; Valore: MBS( "WebView.RunJavaScript" ; "browser"; "var o = document.forms[0].elements[11]; if (document.createEvent) { var evt = document.createEvent('Events'); evt.initEvent('change', true, true); o.dispatchEvent(evt); }") ]
Pausa/continua lo script [ Durata (secondi): ,3 ]
# press save button
Imposta variabile [ $r ; Valore: MBS( "WebView.RunJavaScript" ; "browser"; "var o = document.forms[0].elements[13]; if (document.createEvent) { var evt = document.createEvent('Events'); evt.initEvent('click', true, true); o.dispatchEvent(evt); }") ]
Pausa/continua lo script [ Durata (secondi): ,3 ]
# find the voucher ID and save it to field.
Imposta variabile [ $r ; Valore: MBS( "WebView.RunJavaScript" ; "browser"; "document.getElementById('vouchersTable').getElementsByClassName('voucherCode')[1].innerText") ]
Imposta campo [ Browser Web::VAR txt ; $r ]

Start a video inside an interactive container on Mac:

MBS( "WebView.RunJavaScript" ; "movie"; "document.getElementsByTagName('video')[0].play();" )

Start a video inside an interactive container on Win:

MBS( "WebView.RunJavaScript" ; "player"; "document.getElementById('Player').controls.play();" )

# see https://msdn.microsoft.com/en-us/library/windows/desktop/dd562656(v=vs.85).aspx

Redirect Window.Open to trigger a FileMaker Script:

Set Variable [ $r ; Value: MBS("WebView.RunJavaScript"; "web"; "window.open = function(url, name, features, replace) { location.href='fmp://$/MyDatabase.fmp12?script=NewWindow&param='+encodeURIComponent(url); return {}; }") ]
// may not work for all platforms!

Query text of an element found by it's CSS class name:

MBS( "WebView.RunJavaScript"; WebViewerRef; "document.getElementsByClassName('topteaser_master')[0].innerText")

Query duration of video in interactive container on Mac:

MBS( "WebView.RunJavaScript" ; "web"; "document.getElementsByTagName('video')[0].duration;" )

Query current time of video in interactive container on Mac:

MBS( "WebView.RunJavaScript" ; "web"; "document.getElementsByTagName('video')[0].currentTime;" )

Login for realtytrac website:

Set Web Viewer [ Object Name: "web" ; URL: "https://www.realtytrac.com/login" ]
#
# wait for website loading
#
Loop
    Pause/Resume Script [ Duration (seconds): .1 ]
    Exit Loop If [ MBS("WebView.IsLoading"; "web") ≠ 1 ]
End Loop
Pause/Resume Script [ Duration (seconds): .1 ]
#
# fill in form values with login:
Set Variable [ $r ; Value: MBS( "WebView.SetFormInputValue" ; "web"; 0; "userName"; "xxx" ) ]
Set Variable [ $r ; Value: MBS( "WebView.SetFormInputValue" ; "web"; 0; "password"; "yyy" ) ]
#
# send change events to let the javascript framework know we changed them
#
Set Variable [ $r ; Value: MBS( "WebView.RunJavaScript" ; "web"; "var o = document.getElementById('loginFormPagePassword'); if (document.createEvent)
        {
                var evt = document.createEvent('Events');
                evt.initEvent('change', true, true);
                o.dispatchEvent(evt);
          }")]
Set Variable [ $r ; Value: MBS( "WebView.RunJavaScript" ; "web"; "var o = document.forms[0].userName.value;
if (document.createEvent)
        {
                var evt = document.createEvent('Events');
                evt.initEvent('change', true, true);
                o.dispatchEvent(evt);
          }")]
#
Pause/Resume Script [ Duration (seconds): .1 ]
#
# Send click event to submit button
#
Set Variable [ $r ; Value: MBS( "WebView.RunJavaScript" ; "web"; "var o = document.getElementById('btnLoginPageSubmit'); if (document.createEvent)
        {
                var evt = document.createEvent('Events');
                evt.initEvent('click', true, true);
                o.dispatchEvent(evt);
          }")]

Go to record, wait and than jump to position to play video from there: (Mac)

# Go to record with video
Go to Record/Request/Page [ Next ; Exit after last: Off ]
# give time to load movie
Pause/Resume Script [ Duration (seconds): ,5 ]
# jump to position
Set Variable [ $r ; Value: MBS( "WebView.RunJavaScript"; "MovieView"; "document.getElementById('fm-player').currentTime = 30;" ) ]
# play
Set Variable [ $r ; Value: MBS( "WebView.RunJavaScript"; "MovieView"; "document.getElementById('fm-player').play();" ) ]

Work with form fields via JavaScript:

// Query number of forms on website:

MBS( "WebView.RunJavaScript" ; "web"; "document.forms.length;")

Query name of form number 0:

MBS( "WebView.RunJavaScript" ; "web"; "document.forms[0].name;")

Query number of elements on first form:

MBS( "WebView.RunJavaScript" ; "web"; "document.forms[0].elements.length")

Query name of first element in first form:

MBS( "WebView.RunJavaScript" ; "web"; "document.forms[0].elements[0].name")

Query value of first element in first form:

MBS( "WebView.RunJavaScript" ; "web"; "document.forms[0].elements[0].value")

Query value of element by name in form by name:

MBS( "WebView.RunJavaScript" ; "web"; "document.forms['RegisterForm'].elements['path'].value")

You can mix index or field/form names as needed.

Call doSave with try/catch to show error messages:

MBS( "WebView.RunJavaScript"; WebViewerRef; "try { doSave(); } catch(error) { alert(error);}" )

Switch windows media player for a container to fill the field:

MBS( "WebView.RunJavaScript";
"MovieField"; // name of layout element for container
document.getElementById('Player').uiMode='none';
document.body.style.transform='';
document.getElementById('Player').stretchToFit=true; " )

Fill a search form, submit and query result:

# load website with search field:
Set Web Viewer [ Object Name: "web" ; URL: "https://something.com/searchpage" ]
#
# wait for website to finish loading
Pause/Resume Script [ Duration (seconds): ,5 ]
Loop
    Exit Loop If [ MBS("WebView.IsLoading"; "web") ≠ 1 ]
    Pause/Resume Script [ Duration (seconds): ,1 ]
End Loop
Pause/Resume Script [ Duration (seconds): ,5 ]
#
# fill in search term and send change event, so this website sees it:
Set Variable [ $r ; Value: MBS("WebView.RunJavaScript"; "web"; "document.getElementById('searchField').value = '" & Substitute ( Web::SearchTerm ; "'" ; "" ) & "'") ]
Set Variable [ $r ; Value: MBS("WebView.RunJavaScript"; "web"; "var o = document.getElementById('searchField'); var evt = document.createEvent('Events'); evt.initEvent('change', true, true); o.dispatchEvent(evt); }") ]
#
# wait a bit
Pause/Resume Script [ Duration (seconds): ,5 ]
#
# send click event to search button
Set Variable [ $r ; Value: MBS("WebView.RunJavaScript"; "web"; "var o = document.getElementById('searchButton'); var evt = document.createEvent('Events'); evt.initEvent('click', true, true); o.dispatchEvent(evt); ") ]
#
# wait for website to finish loading
Pause/Resume Script [ Duration (seconds): ,5 ]
Loop
    Exit Loop If [ MBS("WebView.IsLoading"; "web") ≠ 1 ]
    Pause/Resume Script [ Duration (seconds): ,1 ]
End Loop
Pause/Resume Script [ Duration (seconds): ,5 ]
#
# query values from website
Set Field [ Web::articleId ; MBS("WebView.Evaluate"; "web"; "document.getElementById('articleId').innerText;") ]
Set Field [ Web::price ; MBS("WebView.Evaluate"; "web"; "document.getElementById('price').innerText;") ]

Send change, input and blur events to text field:

# define sendChangeEvent function
Set Variable [ $r ; Value: MBS("WebView.RunJavaScript"; "web"; " function sendChangeEvent(ID) { var o = document.getElementById(ID); var evt = document.createEvent('Events'); evt.initEvent('change', true, true); o.dispatchEvent(evt); } ") ]
#
# define sendInputEvent function
Set Variable [ $r ; Value: MBS("WebView.RunJavaScript"; "web"; " function sendInputEvent(ID) { var o = document.getElementById(ID); var evt = document.createEvent('Events'); evt.initEvent('input', true, true); o.dispatchEvent(evt); } ") ]
#
# define sendBlurEvent function
Set Variable [ $r ; Value: MBS("WebView.RunJavaScript"; "web"; " function sendBlurEvent(ID) { var o = document.getElementById(ID); var evt = document.createEvent('Events'); evt.initEvent('blur', true, true); o.dispatchEvent(evt); } ") ]
#
Set Variable [ $r ; Value: MBS("WebView.RunJavaScript"; "web"; "document.getElementById('name').value = '" & Substitute ( $Name ; "'" ; "" ) & "'") ]
#
# send three events as we often don't know which one is used on the website to recognize the change
#
# send input event, so JavaScript code notices we put something in
Set Variable [ $r ; Value: MBS("WebView.RunJavaScript"; "web"; "sendInputEvent('name');") ]
# send change event, so JavaScript code notices we changed text
Set Variable [ $r ; Value: MBS("WebView.RunJavaScript"; "web"; "sendChangeEvent('name');") ]
# send blur event, so JavaScript code notices the user left the field
Set Variable [ $r ; Value: MBS("WebView.RunJavaScript"; "web"; "sendBlurEvent('name');") ]
# give time for web viewer to run all the events
Pause/Resume Script [ Duration (seconds): ,5 ]

Zoom website to 200%:

MBS( "WebView.RunJavaScript"; "web"; "document.body.style.zoom = \"200%\"; ")

# see also WebView.SetInternetExplorerHiDPI

Run FileMaker's message handler in FileMaker 19:

MBS( "WebView.RunJavaScript"; "web"; "FileMaker.PerformScript('test', 'Hello');")

Press Shift-F in the WebViewer to trigger fullscreen for a specific web app:

Set Variable [ $r ; Value: MBS("WebView.RunJavaScript"; "web";
"window.dispatchEvent(new KeyboardEvent('keydown', {
        'key': 'F',
        'shiftKey':true,
        'metaKey':false,
        'keyIdentifier':'U+0046',
        'altKey':false,
        'isTrusted':true,
        'bubbles':true,
        'cancelable':true,
        'composed':true,
        'defaultPrevented':true,
        'charCode': 0,
        'keyCode': 70,
        'code': 'KeyF',
        'ctrlKey':false
}));""
]

// you can monitor events to learn what values to pass by logging all key events in JavaScript console with some code like this:
//
// window.addEventListener('keydown', (e) => {
// console.log(e)
// })

See also

Release notes

  • Version 10.2
  • Version 10.0
    • Added Async parameter for WebView.RunJavaScript function.
    • Changed WebView.RunJavaScript for Mac and iOS to return values in right data types and report errors better. If array or dictionary is returned, we encode it as JSON.

Example Databases

Blog Entries

This function checks for a license.

Created 18th August 2014, last changed 27th June 2022


WebView.ResetPageZoom - WebView.RunJavaScriptReturnTitle