# Javascript Snippets for Browser Monitor Scripts

**URL:** <https://community.dynatrace.com/t/javascript-snippets-for-browser-monitor-scripts/37444>\
**Category:** Troubleshooting\
**Tags:** browser-monitors, synthetic-monitoring\
**Created:** [November 24, 2022, 11:06pm UTC](https://community.dynatrace.com/t/javascript-snippets-for-browser-monitor-scripts/37444 "2022-11-24T23:06:23Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![xu\_guo](https://dub1.discourse-cdn.com/dynatrace/user_avatar/community.dynatrace.com/xu_guo/32/20268_2.png) [@xu\_guo](https://community.dynatrace.com/u/xu_guo)\
**Post date:** [November 24, 2022, 11:06pm UTC](https://community.dynatrace.com/t/javascript-snippets-for-browser-monitor-scripts/37444/1 "2022-11-24T23:06:23Z")

</div>

## Summary

Dynatrace Synthetic Browser Monitors support JavaScript events for advanced scripting scenarios. This article provides reusable JavaScript snippets to handle dynamic elements, locations, iFrames, mouse interactions, and conditional logic in browser monitor scripts.

For editing a browser monitor in script mode rather than as a clickpath, please see the documentation on correct script formatting: [Script mode for Browser Monitors](https://docs.dynatrace.com/docs/observe/digital-experience/synthetic-monitoring/browser-monitors/script-mode-for-browser-monitor-configuration). Note: **Ctrl + Spacebar** will provide a list of autocomplete suggestions when working in script mode.

## Find the Location and Cloud Platform where an execution is running

Rather than having multiple browser monitors running in different locations, so they can each use different values for certain fields, this script allows the values to be changed dynamically.

- This example gets the location name and cloud platform that the browser monitor is running on, and uses it to set the value of a variable “searchValue” based on the location. The value can then be accessed later in a keystroke event using {searchvalue} as the Text Value.

```javascript
// assign default value. validate on this value after page load (fail if found)
var mysearchvalue = "ValueDidNotGetAssigned";
try {
    var loc = api.getContext().location.name;
    api.info("Location Name is: " + loc);
    var platform = api.getContext().location.cloudPlatform;
    api.info("Cloud Platform is: " + platform);

    // set parameters
    if ((loc.indexOf("Mumbai") >= 0) && (platform.indexOf("Alibaba") >= 0)) {
        mysearchvalue = 'Mumbai';
    } else if ((loc.indexOf("Sydney") >= 0) && (platform.indexOf("AWS") >= 0)) {
        mysearchvalue = 'Sydney';
    } else if ((loc.indexOf("N. California") >= 0) && (platform.indexOf("AWS") >= 0)) {
        mysearchvalue = 'N. California';
    } else if ((loc.indexOf("Chennai") >= 0) && (platform.indexOf("Azure") >= 0)) {
        mysearchvalue = 'Chennai';
    }

    // display location, platform and parameter values on error screenshot
    document.body.innerText = "Location Name is: " + loc + ' and Cloud Platform is:' + platform + ' and Search Value is: ' + mysearchvalue;

} catch (err) {
    api.info("Error message: " + err.description);
}
api.setValue("searchvalue", mysearchvalue);

```

## Double-click mouse event

- From time-to-time an application requires a double-click mouse interaction. This can only be accomplished through a custom JavaScript event. _(Please replace `unique-id` in the example below)_

```javascript
var Clickevent = new MouseEvent('dblclick', {'view': window});
document.getElementById('unique-id').dispatchEvent(Clickevent);

```

## How to create a locator for a resource in a iFrame

- This snippet can be used for a CSS in an iFrame, and, also, be used on the parent page. _(Please replace both `id-of-iframe` & `CSS-selector-for-element`)_

```javascript
document.getElementById('id-of-iframe').contentWindow.document.querySelector('CSS-selector-for-element')

```

## 

How to change the setting for --disable-web-security

- By default as of `1.198`, `--disable-web-security` is set to `true`. It can be set to `false` by adding the following line to the Synthetic Script.

```javascript
"configuration": {
      "device": {
          "orientation": "landscape",
          "deviceName": "Desktop"
      },
      "disableWebSecurity": false
  },

```

## Handling an randomly appearing question

- Here is a JavaScript synthetic event example for handling a randomly appearing security question. If the security question is asked, the answer is set as the last word in the question. If the security question does not appear, skip the next click that would submit the answer.

```javascript
// Capture the security question element
var question = document.getElementById("CSS ID of the Security Question Text");
// Check to see if the security question element exists
if (question === null) {
    // No security question was asked so skip the next click
    api.skipNextSyntheticEvent();
} else {
    //Security question was asked so get the words of the question
    var words = question.textContent.split(" ");
    //Select the last word of the question and remove the question mark at the end
    var answer = words[words.length - 1].slice(0, -1);
    // set the answer to the security question
    document.getElementById("CSS ID for the Answer Box").value = answer;
}

```

## 

Validate text in a JavaScript event

```markup
text = 'Text to validate';
text1 = document.documentElement.innerText;
api.info(text1);
api.info(text1.indexOf(text));
if (text1.indexOf(text) == -1) {
  api.fail("execution failed");
}

```

## What’s Next

You can find more helpful tips for Synthetic in the&nbsp;[Synthetic Troubleshooting Map](https://community.dynatrace.com/topic/250426)

### Related reading

📖&nbsp;&nbsp;[How to perform a right-click in a Browser Clickpath Synthetic Monitor](https://community.dynatrace.com/topic/233062)

📖&nbsp;&nbsp;[How to perform a keypress in a Browser Clickpath Synthetic Monitor](https://community.dynatrace.com/topic/237412)

📖&nbsp;&nbsp;[How to perform mouseover event on browser click path synthetic monitor.](https://community.dynatrace.com/topic/209305)

📖&nbsp;&nbsp;[How to perform DoubleClick event on browser click path synthetic monitor.](https://community.dynatrace.com/topic/209309)

---

<div class="post-metadata">

**Author:** ![ChadTurner](https://dub1.discourse-cdn.com/dynatrace/user_avatar/community.dynatrace.com/chadturner/32/161_2.png) [@ChadTurner](https://community.dynatrace.com/u/ChadTurner)\
**Post date:** [January 10, 2023, 8:06pm UTC](https://community.dynatrace.com/t/javascript-snippets-for-browser-monitor-scripts/37444/2 "2023-01-10T20:06:48Z")

</div>

Thanks for sharing this&nbsp;[@xu\_guo](https://community.dynatrace.com/user/21845)

---

<div class="post-metadata">

**Author:** ![michael\_2\_kumme](https://avatars.discourse-cdn.com/v4/letter/m/db5fbb/32.png) [@michael\_2\_kumme](https://community.dynatrace.com/u/michael_2_kumme)\
**Post date:** [February 24, 2023, 3:29pm UTC](https://community.dynatrace.com/t/javascript-snippets-for-browser-monitor-scripts/37444/3 "2023-02-24T15:29:37Z")

</div>

Can the JS also be used to simulate a TAP action for a mobile device script?&nbsp; We have attempted to record a new mobile device monitor that must select an item from a drop down, but the playback will not execute the selection.&nbsp; Would a JS command work for that tap action and/or would it possible to simply set the value with a JS?&nbsp; IF you have an example to share, that would be great.&nbsp; Thanks

---

<div class="post-metadata">

**Author:** ![hannahmac](https://dub1.discourse-cdn.com/dynatrace/user_avatar/community.dynatrace.com/hannahmac/32/41823_2.png) [@hannahmac](https://community.dynatrace.com/u/hannahmac)\
**Post date:** [February 24, 2023, 4:04pm UTC](https://community.dynatrace.com/t/javascript-snippets-for-browser-monitor-scripts/37444/4 "2023-02-24T16:04:17Z")

</div>

I just tested it with a mobile site and, if the out of the box tap doesn’t work, you can indeed just use a click. This was the code I used.

document.querySelector(‘yourCSSSelector’).click();
