Overview
Javascript is critical to supporting functionality across websites and mobile apps. Among its many capabilities, it can be used to simulate a user interacting with the page.
This guide is a resource for those wanting to use Javascript and jQuery (a popular javascript library) in their Audits and Journeys.
Query Selector
Because selecting HTML elements to manipulate the page is key to success with Audits and Journeys, you'll want to master these 2 tools:
Basic JS Examples
To click:
document.querySelector('#example').click();
To change values (inputs):
document.querySelector('#example').value = 'this value';
To select from dropdown:
document.querySelector('#selectorForDropdown).value = 'value of option';
Note: For select HTML elements you probably need to trigger a change event (see below).
Trigger Event
With vanilla JS (recommended):
document.querySelector('#example').dispatchEvent(new Event('change', { bubbles: true }));
With jQuery:
jQuery('#example').trigger("change");
Optional Event
With Vanilla JS:
try { document.querySelector('#example').click(); //example action} catch(e) { console.log('Could not click on element'); //notify that action didn't happen}
Find an an element with a certain HTML property
document.querySelector('[{insert HTML Property here}="{insert value here}"]');
Prevent Navigating to new tab
document.querySelector('#example').setAttribute('target', '_self');
“Get Selector” Function
Note: In the DOM, click on the element you want first.
var elem = $0;
function getDynSelector(e) {
var t = e.tagName.toLowerCase(),
l = e.attributes,
n = [];
for (i = 0; i < l.length; i++) - 1 == l[i].value.search(/{.*}/g) && n.push({
len: l[i].nodeName.length + l[i].value.length,
selector: t + "[" + l[i].nodeName + "='" + l[i].value + "']"
});
var r = 0,
o = -1;
for (i = 0; i < n.length; i++) 1 == document.querySelectorAll(n[i].selector).length && (0 == r || r > n[i].len) && (r = n[i].len, o = i);
if (-1 != o) return n[o].selector;
var a = e.parentElement.children,
c = 0;
for (i = 0; i < a.length; i++) a[i] == e && (c = i);
return getDynSelector(e.parentElement) + " > " + e.tagName.toLowerCase() + ":nth-child(" + (c + 1) + ")"
}
console.log(getDynSelector(elem));
Trigger a lot of events w/ minimal setup
var el = document.querySelector('#example');
el.dispatchEvent(new Event('dblclick', {
bubbles: true
}));
el.dispatchEvent(new Event('mouseenter', {
bubbles: true
}));
el.dispatchEvent(new Event('mouseleave', {
bubbles: true
}));
el.dispatchEvent(new Event('mousemove', {
bubbles: true
}));
el.dispatchEvent(new Event('mouseover', {
bubbles: true
}));
el.dispatchEvent(new Event('mouseout', {
bubbles: true
}));
el.dispatchEvent(new Event('mouseup', {
bubbles: true
}));
el.dispatchEvent(new Event('keydown', {
bubbles: true
}));
el.dispatchEvent(new Event('keypress', {
bubbles: true
}));
el.dispatchEvent(new Event('keyup', {
bubbles: true
}));
el.dispatchEvent(new Event('load', {
bubbles: true
}));
el.dispatchEvent(new Event('blur', {
bubbles: true
}));
el.dispatchEvent(new Event('change', {
bubbles: true
}));
el.dispatchEvent(new Event('focus', {
bubbles: true
}));
el.dispatchEvent(new Event('focusin', {
bubbles: true
}));
el.dispatchEvent(new Event('focusout', {
bubbles: true
}));
el.dispatchEvent(new Event('input', {
bubbles: true
}));
el.dispatchEvent(new Event('submit', {
bubbles: true
}));
Normal “Hit it with every event”
var el = document.getElementById('example');
var arr = ['click', 'compositionstart', 'compositionend', 'ctextmenu', 'dblclick', 'mousedown', 'mouseenter', 'mouseleave', 'mousemove', 'mouseover', 'mouseout', 'mouseup', 'keydown', 'keypress', 'keyup', 'abort', 'beforeunload', 'error', 'hashchange', 'load', 'pageshow', 'pagehide', 'resize', 'visibilitychange', 'scroll', 'unload', 'blur', 'change', 'focus', 'focusin', 'focusout', 'input', 'invalid', 'reset', 'search', 'select', 'submit', 'drag', 'dragend', 'dragenter', 'dragleave', 'dragover', 'dragstart', 'drop', 'copy', 'cut', 'paste', 'afterprint', 'beforeprint', 'abort', 'canplay', 'canplaythrough', 'duratichange', 'emptied', 'ended', 'error', 'loadeddata', 'loadedmetadata', 'loadstart', 'pause', 'play', 'playing', 'progress', 'ratechange', 'seeked', 'seeking', 'stalled', 'suspend', 'timeupdate', 'volumechange', 'waiting', 'animatiend', 'animatiiterati', 'animatistart', 'transitiend', 'error', 'message', 'open', 'message', 'mousewheel', 'line', 'offline', 'popstate', 'show', 'storage', 'toggle', 'wheel', 'touchcancel', 'touchend', 'touchmove', 'touchstart', 'orientationchange'];
function triggerEvent(el, type) {
if ('createEvent' in document) {
var e = document.createEvent('HTMLEvents');
e.initEvent(type, true, false);
el.dispatchEvent(e);
}
};
var w = 0;
var myvar = setInterval(function() {
if (w == arr.length + 1) {
clearInterval(myvar)
}
triggerEvent(el, arr[w]);
console.log(arr[w]);
w++;
}, 800);
Getting stuff from iFrame w/ Vanilla JS
document.querySelector('iframeSelector').contentDocument.querySelector('.elementiniframe).value = "ObservePoint";
Click All Elements of a Certain Type
var elements = 'a, input'; /*add whatever elements you want to click on here, separated by commas.*/
document.querySelectorAll(elements).forEach((el) => {
el.click();
});
ObservePoint Action Events
Click
var el = document.querySelector('#example');
el.dispatchEvent(new Event('mouseover', {
bubbles: true
}));
el.dispatchEvent(new Event('mousemove', {
bubbles: true
}));
el.dispatchEvent(new Event('mousedown', {
bubbles: true
}));
el.dispatchEvent(new Event('mouseup', {
bubbles: true
}));
el.dispatchEvent(new Event('click', {
bubbles: true
}));
Input
var el = document.querySelector('#example');
el.value = 'example value';
el.dispatchEvent(new Event('focus', {
bubbles: true
}));
el.dispatchEvent(new Event('select', {
bubbles: true
}));
el.dispatchEvent(new Event('input', {
bubbles: true
}));
el.dispatchEvent(new Event('keydown', {
bubbles: true
}));
el.dispatchEvent(new Event('keypress', {
bubbles: true
}));
el.dispatchEvent(new Event('keyup', {
bubbles: true
}));
el.dispatchEvent(new Event('change', {
bubbles: true
}));
el.dispatchEvent(new Event('blur', {
bubbles: true
}));
Get Elements that Contain HTMLText
try {
var elType = 'el type (div, a, p)';
var SearchText = 'Example Search Text';
function contains(selector, text) {
var elements = document.querySelectorAll(selector);
return [].filter.call(elements, function(element) {
return RegExp(text).test(element.textContent);
});
}
var el = contains(elType, SearchText);
el[0];
Monitor Events on an element
Note: First click on the element you want in the DOM
To start it
monitorEvents($0)
To stop it
unmonitorEvents($0)
Get Today’s Date String (yyyy-mm-dd)
Note: Places 0 in front of single digit numbers (9 => 09)
var d = new Date();
var year = d.getFullYear();
var month = d.getMonth() + 1 <= 9 ? '0' + (d.getMonth() + 1) : d.getMonth() + 1;
var day = d.getDate() <= 9 ? '0' + d.getDate() : d.getDate();
var fullDate = year + '-' + month + '-' + day;
Add months & days to Date (same format as above)
var days = 2; //days to add
var months = 2; //months to add
var d = new Date();
d.setDate(d.getDate() + days);
d.setMonth(d.getMonth() + months);
var month = d.getMonth() <= 8 ? '0' + (d.getMonth() + 1) : (d.getMonth() + 1);
var day = d.getDate() <= 9 ? '0' + d.getDate() : d.getDate();
var fullDate = '' + d.getFullYear() + '-' + month + '-' + day;
Make n number of random characters
function randomString(strLength) {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < strLength; i++) text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
Example:
randomString(10);
Output:
eXxVsw0u44
Make Dynamic Email
var d = new Date();
var email = 'test' + (new Date).getTime().toString() + '@observepoint.com'; < br > < br > //OR THIS FOR WEBSITES WITH SECURITY SYSTEMS <br><br>var d = new Date();
var email = 'test' + (new Date).getTime().toString() + '@observepoint.com';
var input = document.querySelector('#email');
var lastValue = input.value;
input.value = email;
var event = new Event('input', {
bubbles: true
});
event.simulated = true;
var tracker = input._valueTracker;
if (tracker) {
tracker.setValue(lastValue);
}
input.dispatchEvent(event);
Slow Scroll
function pageScroll() {
window.scrollBy(0, 500); // horizontal and vertical scroll increments
scrolldelay = setTimeout('pageScroll()', 100); // scrolls every 100 milliseconds
if ((window.innerHeight + window.pageYOffset) >= document.body.offsetHeight) {
clearTimeout(scrolldelay);
}
}
pageScroll();
React
Websites and Web Apps built with React have exceptional behavior. This is a guide for Javascript tools for manipulating UIs that are built with React JS.
Inputting into React JS Field
For hitting the two different input methods between v. 15 and v. 16 of React:
For standard input:
var input = document.querySelector('#example');
var lastValue = input.value;
input.value = 'new value';
var event = new Event('input', {
bubbles: true
});
event.simulated = true;
var tracker = input._valueTracker;
if (tracker) {
tracker.setValue(lastValue);
}
input.dispatchEvent(event);
For Select:
var input = document.querySelector('#example');
input.selectedIndex = 3;
event = new Event('change', {
bubbles: true
});
input.dispatchEvent(event);
React “Hit it with every event”
var el = document.getElementById('example');
var arr = ['click', 'compositionstart', 'compositionend', 'ctextmenu', 'dblclick', 'mousedown', 'mouseenter', 'mouseleave', 'mousemove', 'mouseover', 'mouseout', 'mouseup', 'keydown', 'keypress', 'keyup', 'abort', 'beforeunload', 'error', 'hashchange', 'load', 'pageshow', 'pagehide', 'resize', 'visibilitychange', 'scroll', 'unload', 'blur', 'change', 'focus', 'focusin', 'focusout', 'input', 'invalid', 'reset', 'search', 'select', 'submit', 'drag', 'dragend', 'dragenter', 'dragleave', 'dragover', 'dragstart', 'drop', 'copy', 'cut', 'paste', 'afterprint', 'beforeprint', 'abort', 'canplay', 'canplaythrough', 'duratichange', 'emptied', 'ended', 'error', 'loadeddata', 'loadedmetadata', 'loadstart', 'pause', 'play', 'playing', 'progress', 'ratechange', 'seeked', 'seeking', 'stalled', 'suspend', 'timeupdate', 'volumechange', 'waiting', 'animatiend', 'animatiiterati', 'animatistart', 'transitiend', 'error', 'message', 'open', 'message', 'mousewheel', 'line', 'offline', 'popstate', 'show', 'storage', 'toggle', 'wheel', 'touchcancel', 'touchend', 'touchmove', 'touchstart', 'orientationchange'];
function triggerEvent(el, type) {
if ('createEvent' in document) {
var lastValue = el.value;
var event = new Event(type, {
bubbles: true
});
event.simulated = true;
var tracker = el._valueTracker;
if (tracker) {
tracker.setValue(lastValue);
}
el.dispatchEvent(event);
}
};
var w = 0;
var myvar = setInterval(function() {
if (w == arr.length + 1) {
clearInterval(myvar)
}
triggerEvent(el, arr[w]);
console.log(arr[w]);
w++;
}, 800);