top of page
  • Writer's pictureDarrin Southern

demystify[FM-JS]

You’re invited to explore this demystify(FM-JS) blog post and download this demo file – as you embark on expanding your Claris® FileMaker® solutions into the vast and captivating realm of JavaScript.


Introduction.


This demystifying blog post and demo file aim to demonstrate a simple way to apply two FileMaker script steps within your solutions, outlining a method to pass data between FileMaker (FM) and JavaScript (JS) functions and back again.

We will start with straightforward examples and then progress to more complex ones, showcasing how JavaScript can greatly enhance your upcoming FileMaker solution.

As always, our focus remains on enhancing your Developer Experience (DX) and simplifying your initial journey with FileMaker-JavaScript (FM-JS).


This content is released under the MIT Licence.

demystify
.zip
Download ZIP • 201KB

The demo file authentication is username/password: admin/admin


Getting Started with demystify(FM-JS).


This content – blog post and demo file – are divided into two distinct sections.


The first section focuses on setting up the environment of the demo file and configuring various elements of the solution, such as fields, scripts, and layout objects like the FileMaker web viewer.


Environment:


The second section revolves around examples, providing detailed explanations of the features and functions associated with each example.


Examples:


Two Simple FileMaker Scripts.


Although these two scripts are not referenced in the examples, it’s worth investigating these basic FileMaker Scripts with the minimum steps required to perform JavaScript in a FileMaker web viewer.


These scripts also rely on the fact that we have a web viewer on the layout called ‘web.viewer’.


Script: Simple One Step.

This ‘one-step’ script relies on the fact that there are existing built-in JavaScript functions to call.

Perform JavaScript in Web Viewer [ Object Name: "web.viewer"; Function Name: "alert";
   Parameter 1:  "Hello World!" ]

  • document.write

  • window.alert

  • console.log


Script: Simple Three Step.

This script is a little more like the structure we will be moving forward with.

Insert Text [ $_js ]
data:text/html,
<script>
   function showAlert() {
     alert('Hello World!') ;
   }
</script>
Set Web Viewer [ Object Name: "web.viewer"; URL: $_js ]
Perform JavaScript in Web Viewer [ Object Name: "web.viewer"; Function Name: "showAlert" ]

As mentioned, although these two scripts is not referenced in the actual examples, both are alternative methods of setting up the example called ‘Minimal non-HTML Hello World Alert’.


FileMaker and JavaScript Interaction Structure.


As previously discussed, starting with basic functions requires minimal effort. However, when your requirements expand beyond the initial stage, the potential for designing powerful and limitless structures and code arises.


To execute JavaScript functions, three fundamental elements are necessary:

  • Web Viewer (given a specific name)

  • JavaScript function (enclosed within HTML)

  • FileMaker scripts (to establish and execute functions)

This structured approach will be employed in the example demos we will be working with. It provides a solid foundation for implementing and utilising JavaScript functions within FileMaker.


Web Viewer Set Up.


Ensure you have named your web viewer and turned on o ‘Allow JavaScript to perform FileMaker scripts’ option. It’s best practice to also set the initial data calculation to an empty string eg: “”.


The following FileMaker script step targets the contents of the Web Viewer, to run the JavaScript function, also allowing for parameters to be passed:

Perform JavaScript in Web Viewer [ Object Name ; Function Name ; Parameters ]


Web Viewer Troubleshooting.


There is one caveat – for setting up your web viewer — only to aid in troubleshooting: You can turn on the ‘Web Debugger’ for the FileMaker Web Viewers via your Terminal app on your Mac.


defaults write com.filemaker.client.pro12 WebKitDebugDeveloperExtrasEnabled -bool YES


Script Calls.


There are two functions that you can call to perform FileMaker Scripts from within your JavaScript.


The second function does have an extra option:

FileMaker.PerformScript ( script, parameter )
FileMaker.PerformScriptWithOption ( script, parameter, option )

FileMaker Calculation: Substitute.


We’re applying the Substitute function to replace data from fields into the HTML:

Substitute ( text ; searchString ; replaceString )

This allows us to take the data from the input field, replace the input string:

Substitute ( JavaScript::html ; JavaScript::input.string ; JavaScript::input  )

The Input field has been set up to allow ‘quotations’ as method to define the data as text, as no quotations defines the data as a number. You can define the replacement string to your own preference.


Currently we have supplied five sets of input and replacement strings. Of course, we’re making good use of Repeating Fields to allow us five Substitutes.


Creating and populating your HTML.


There are various methods of creating your HTML to populate your web viewer and/or solution.


In the demo file, we have written the HTML directly in a text field, which allows for easy reading, and therefore editing without needing to include quotations, as we would with a field calculation.


Insert Text.

A popular method to define the code required, is to apply the ‘Insert Text’ script step, with the target being a variable, rather than a field directly:


Insert Text [ $_html ] '<your text here>'

As FileMaker Developers, our normal go-to method would be to create a text calculation with the required data:

"data:text/html," & ¶ & 
¶ &
"<script>" & ¶ & 
"   function showAlert() {" & ¶ & 
"     alert('Hello World!') ;" & ¶ & 
"   }" & ¶ &
"</script>"

As evident, the current approach is far from ideal and can easily become complicated.


In these examples, the HTML code is being assigned through a text field, which offers several advantages:

  • The code is readily visible on the layout, making it easily accessible.

  • The code can be edited effortlessly as it is entered as plain text.

  • Each record has its own separate code.

  • The data for each record can be saved and reverted individually.

  • Formatted HTML.


Formatted HTML.


In this demo file, the HTML for each example has been exposed, formatted and even colour-coded for ease of reading and editing.


Providing “Developer Next” clean and readable code is always high on our list of coding best practices. Formatted HTML is one of these clean code techniques.


One of the most recent web sites for formatting code that I like is Web Formatter:


HTML Master and HTML Template.


The template HTML allows for further functions and tags to be added, and this can be saved back as the Master HTML for future ‘reverting’. This is useful if you find you have messed up your updated HTML code.

<html>
    <head>
        <title>FileMaker JavaScript</title>
        <script>
            function jsFunction() {
                "your function goes here . . ." ;
            }
        </script>
    </head>
    <body>
        <h4>WebViewer</h4>
        <p>This is just the HTML preview for our custom FM-JS function</p>
    </body>
</html>

Your First FileMaker JavaScript Function.


In addition to the provided FileMaker JavaScript functions, this solution serves as a versatile playground for developing and testing your own functions.


Each record within this solution functions as an independent space where you can freely create, edit, and experiment with your code.


To create new records, you can utilise the native FileMaker ‘New Record’ menu item. Each record comes equipped with its own ‘Sort Order’ field, allowing for an organised display.


Feel free to explore, save, and reload the provided functions, as well as your own creations, within this solution. It offers a flexible environment for your coding endeavours.


Troubleshooting HTML via the FileMaker Web Viewer.


One of the nice features of the FileMaker Web Viewer is the ability to right click a web viewer and ‘Inspect Element’.


You will find the ‘Golf Sample with Error’ has a big red error within the JS. Although FM reports ‘Error: 5’, the error detail is shown within the console output of the ‘Web Inspector’.


ReferenceError: Can't find variable: swings

FM-JS Demo File Examples.


In the demo file, we have included several sample records. Each record has its own dedicated space where you can view, edit, and load the raw HTML. Additionally, you can define input text and replacement scripts.


Minimal non-HTML > Hello World Alert.


For illustrative purposes, we have included this minimalist non-HTML code to showcase the bare minimum required to execute a JavaScript ‘Alert’ function within a web viewer.

data:text/html,

<script>
   function showAlert() {
     alert('Hello World!');
   }
</script>

It is worthwhile to take some time to analyse and deconstruct this code into its fundamental components.


In this code snippet, we are informing the web viewer that the data being transmitted is HTML. The script itself is defined within the script tags, and it consists of a function named showAlert, which triggers an alert with the message “Hello World!”


There is no requirement to enclose the JavaScript code within HTML tags, nor are we anticipating any input data, export data, nor FileMaker scripts at this stage. These elements will come into play later. However, it is crucial to first comprehend the necessary interaction structure.


FM Text > Pass Through.


This is our first real JavaScript example:

<script>
    function jsPassThrough() {
        FileMaker.PerformScript( 'Set: Output', 'This text is for our FM-JS function' ) ;
    }
</script>

Admittedly, not really much of an example – it simply passes the data from the input field to the ‘jsFunction’ which passes the data to the ‘Set: Output’ script, as a parameter and then the script writes the data to the Output field.


With this example, we have also updated our HTML to include the standard tags, such as <head> and <body>.


FM Text > Text Equation.


Each example builds on the previous, and in this case, we’ve added further inputs and replacement strings to allow JavaScript to add these two text strings together.


Again, the replacement strings can be customised. It’s worth noting that single or double quotation marks are acceptable.


FM Numbers > JS Equation.


This time we are passing three value pairs, and now without quotations, we can ask JavaScript to perform equations:

~a ~b ~c which substitutes to 6 + 2


<<script>
    function jsEquation() {
       var jsOutput = 6 + 2 ;
       FileMaker.PerformScript('Set: Output', jsOutput ) ;
    }
</script>

FM Numbers > JS Equation > FM Result & Web Viewer.


he following two examples show that the result or output can be passed to the web viewer, via the body HTML, either on loading the HTML or running the main script.


Feel free to change the number and operators ( + – * / ) and explore the output options.


FM Text > Pass Through ‘Loading’.


In this particular example, the loading of the web viewer and the execution of the FileMaker script are combined into a JavaScript function, including a re-try on the perform function.


Compared to the previous examples, the code for this example is evidently more complex.


Alternatively, you have the option to separate the loading and execution into separate script steps. However, there is no guarantee that the JavaScript has finished loading within the web viewer before the FileMaker script calls the JavaScript function.


It’s worth noting that in this example, the variable jsOutput is defined outside the function, making it a global variable.


The key distinction of this ‘loop’ compared to FileMaker loops is the pause. In the provided code snippet, the pause is set to 200, where 1000 equals 1 second.


<script>

    var jsOutput = ~input ;

    function jsPassThrough() {
        fmPerformScript( ) ;
    }

    jsPassThrough() ;

    function fmPerformScript( attemptCount = 0 ) {
        var maxAttempts = 5 ;

       if ( window.FileMaker && window.FileMaker.PerformScript ) {
             FileMaker.PerformScript( '~fmScript', jsOutput ) ;
          } else if ( attemptCount < maxAttempts ) {
             window.setTimeout(function () {
                 fmPerformScript( attemptCount + 1 ) ;
                 } , 200 ) ;
          } else {
             alert( maxAttempts + " attempts exceeded." ) ;
        }
     }

</script>

Golf Score.


This is one of the most well known JavaScript examples for configuring an If/Else statement with text from the equations for output.


The code was updated to include the FileMaker script as the output.


You’ll notice that we have taken the FileMaker strings of ~par and ~strokes and ‘re-defined’ these to the variable names within the jsFunction.


Golf Score with Error.


We’ve purposely created an error in the JavaScript for this one.


Go ahead and run the web viewer code, and the output = Error: 5

Right click on the web viewer, Inspect Element, and view the error within the Web Inspector:


Reference Error: Can't find variable: swings

JSON > CSV.


This JavaScript example was actually created by ChatGPT 3.5 with the simple prompt of ‘HTML with JavaScript to parse JSON to CSV’.


Rather than include the JSON in the code, I have abstracted this data to our input and substitute string fields.


Notice there’s only a minor change to the output from ‘console.log( csv )’ to our output of ‘FileMaker.PerformScript(“Set: Output”, csv )’


Final Note.


This blog post and example file is a co-production between Beezwax and CadenceUX. https://blog.beezwax.net


We hope that demystify(FM-JS) will help you as you embark on expanding your Claris FileMaker solutions into the vast and captivating realm of JavaScript.

106 views0 comments

Recent Posts

See All
bottom of page