How to simulate mouseenter event in Selenium or Javascript? - javascript

I've been working on a web UI automation task with Selenium, Javascript and SeLion. I would like to take a screenshot of some equivalent scenario as Google homepage below:
In which the "Search by voice" should be present when mouse moves in that microphone icon (neither Click or Hover). I have search bunch of solutions, unfortunately non of them works as expected.
I'm basically dealing with something like this:
<div id="div_id">
<button type="button" class="button_class" disabled="" data-marko=" .
{"onclick":"handleClick s0-2-0-27-0
false","onkeydown":"handleKeydown s0-2-0-27-0 false"}"
title="This message shows by mouseenter event" aria-label="This
message shows by mouseenter event">
<span class="span_class"></span>
</button>
</div>
When mouse enters that button, "This message shows by mouseenter event" will be present. The page is likely written by Marko-js. Couldn't really handle it with plain Javascript, I tried.
Any idea?
Thanks in advance!

In which the "Search by voice" should be present when mouse moves in that microphone icon (neither Click or Hover)
if u read this link : https://www.w3.org/TR/DOM-Level-3-Events/#trusted-events , it says that only user agent events can trigger "search by voice" . its cant be done by scripts

I provided you a simple working example, give me a feedback if it is suitable for your needs.
function simulateMouseEnter() {
var event = new MouseEvent('mouseenter', {
'view': window,
'bubbles': true,
'cancelable': true
});
var myTarget = document.getElementById('target_div');
var canceled = !myTarget.dispatchEvent(event);
if (canceled) {
// A handler called preventDefault.
alert("canceled");
} else {
// None of the handlers called preventDefault.
alert("not canceled");
}
}
function mouseEnterBehaviour() {
myElement = document.getElementById("target_div");
// attach mouseenter event listener to element
myElement.addEventListener("mouseenter", function(event) {
// change the color of the font
event.target.style.color = "red";
});
// call the simulation
setTimeout(simulateMouseEnter,3000);
}
mouseEnterBehaviour();
<div id="target_div">target div</div>
Note: this should work with the most of the browser events

Related

Bypassing javascript event using another javascript event

I have a button which when click will trigger to open up a popup.
<button id="thisId">OPEN POPUP</button>
The event for it will be something as follow
$(document).on('click', '#thisId', function(){
// DO SOMETHING TO OPEN THE POPUP HERE
});
This button should work as expected if the browser allows popup to be opened on it. Problem is when the popup blocker is enabled. I have quite an amount of buttons like this, probably like nearly 100 buttons with similar thing in the project that i currently working on, and i dont want to do the checking on each of the event handler for each respective buttons. I wanna make a common event handler for all the buttons, which will trigger on click of the button.
So i added another attribute to the same button
<button data-openpopup id="thisId">OPEN POPUP</button>
For this i attach an event specific to this attribute. When the button is clicked, in case if popup blocker is set on for that browser, it will do a checking to check whether popup blocker is on, and if it is, it will throw an alert to the user using jconfirm's alert box. The event for it will be something as follow
$(document).on('click', '[data-openpopup]', function(){
var $this = $(this);
var pop = window.open("about:blank", "new_window_123", "height=150,width=150");
if (!pop || pop.closed || pop.closed == "undefined" || pop == "undefined" || parseInt(pop.innerWidth) == 0 || pop.document.documentElement.clientWidth != 150 || pop.document.documentElement.clientHeight != 150){
pop && pop.close();
// Call jconfirm alert if popup is disabled
$.alert({
title: 'Popup blocked alert!',
content: 'Your popup blocker is currently enabled.',
closeIcon: true,
buttons: {
close: {
text: 'Close',
btnClass: 'btn-blue'
}
}
});
} else {
pop && pop.close();
}
});
Now the issue here is, i want it so that, when click on the button, it will override the original click method which is to open a popup, preventing it from running, and do the popup checking first. If checking is false, then only proceed with the event to open the popup.
So how can i do this?
You could use .stopImmediatePropagation() to prevent the other handler from executing.
But you have to put that in a handler that must be registered before the other(s) since the callbacks are executed in the order the listeners were registered.
If several listeners are attached to the same element for the same event type, they are called in order in which they have been added. If during one such call, event.stopImmediatePropagation() is called, no remaining listeners will be called.
Below, I "simulated" your popup blocker test with an additionnal button... Since it does not seem to be working, at least with AdBlocker Plus (Chrome extention). From what I saw, your condition is always true, AdBlocker active or not.
// To simulate a working blocker detection
var blocker=true;
$("#blockerToggle").on("click",function(){
blocker=!blocker;
$(this).find("span").text(blocker.toString().toUpperCase()).css({"color":(blocker)?"green":"red"});
}).trigger("click");
// Assuming a good popup blocker detection
// This handler can stop the others... Registered AFTER this one.
$(document).on('click', '[data-openpopup]', function(e){
if(blocker){
console.log("Blocker ON! Prevent the other listener(s) from executing.");
e.stopImmediatePropagation();
} else {
console.log("Okay, let the other listener(s) execute.");
}
});
// Other handler
$(document).on('click', '#thisId', function(){
console.log("Other handler executed.");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button data-openpopup id="thisId">OPEN POPUP</button> <button id="blockerToggle">Popup blocker active => <span></span></button>

Is it possible to emit an event using a standard HTML button?

Maybe this is a really stupid question, but I can't figure it out.
Basically all I want to do is emit a single event when the screen is touched (using a physical button on the model of google cardboard that we are ordering). Couldn't work out how to have a 'whole screen touch' so I made a button element outside the a-scene. This is positioned absolutely at the point where the button hits the screen, and console logs when clicked (via mouse) - so I know that the button works. However, trying to emit an event or setAttribute does nothing.
Is there something I'm doing wrong, or is there just some other approach entirely that is better suited?
Here's the code:
<body>
<button id="nav-btn" class="btn btn-primary">Menu</button>
<a-scene id="scene">
and:
AFRAME.registerComponent('nav', {
schema: {},
init: function () {
var navBtn = document.querySelector('#nav-btn');
var btnEls = document.querySelectorAll('.link');
navBtn.addEventListener('click', function () {
console.log('clicked');
for (var i = 0; i < btnEls.length; i++) {
console.log(btnEls[i]);
btnEls[i].emit('menuFade');
}
});
},
});
This works when using an a-entity as a button by the way, but I also couldn't find out how to make that work as a physical button!?
Thanks for any help or advice!
If you care about figuring out when the physical button is pressed on a Google Cardboard, then you don't even need a button element. Attach a "click" or "touchstart" handler to the window and you should be good:
window.addEventListener('touchstart', function(evt) {
console.log('there we go')
})
Note that emit isn't a vanilla JS way of emitting events but an A-Frame specific function, which is why it won't work from a button.
You can use dispatchEvent and CustomEvent for that instead:
window.addEventListener('touchstart', function(evt) {
console.log('there we go')
window.dispatchEvent(new CustomEvent('menuFade'))
})
You may need to change the object that emits the event to something inside the a-scene but it should work.

Cordova iOS: Click on custom auto suggest not recognized cause keyboard closes

in my Cordova App I have a problem on iOS devices and I have no idea how to solve.
I have a custom auto-suggest which shows up below an input field while typing. All is contained in a dialog box with "position: fixed;".
Autocomplete is an unordered list. Click on < li > Element should place the selected text into the input.
The problem is, when user clicks on the li, the input loses focus, the keyboard disappears and the whole fixed dialog box "jumps" down and the click event is not recognized.
It is recognized when the keyboard already IS closed.
I tried several workarounds, like giving focus back to input field immediately after blur. But it does not help. Keyboard closes and opens instead of just keeping opened.
Any Ideas how to solve?
Here is a video showing the behaviour. It is recorded on the iOS Simulator but same behaviour on real iPhone 6s.
I have found a solution now. As I said the click event is not triggered when the keyboard hides, but a touchstart event is triggered.
So I did a workaround, looking for touchstart event followed by a blur event. If the touchstart-target does not receive a click event within a given time, I will trigger one. This works on my test iPhone 6s.
Here is the code:
var iosTapTarget=null;
if (device.platform === 'iOS') {
js.eventListener(document.body).add('iosTap', 'touchstart', function (e) {
iosTapTarget = e.target;
js.eventListener(iosTapTarget).add('iosTapClick', 'click', function(e) {
// when the target receives a click, do not trigger another click
if (iosTapTarget) js.eventListener(iosTapTarget).remove('iosTapClick', 'click');
iosTapTarget = null;
});
// after short time unset the target
window.setTimeout(function () {
if (iosTapTarget) js.eventListener(iosTapTarget).remove('iosTapClick', 'click');
iosTapTarget = null;
}, 600)
});
// on each input fields listen for blur event and trigger click event on element received touchstart before
var blurableElements = document.querySelectorAll('input[type=text],input[type=email],input[type=password],textarea');
for (var j = 0; j < blurableElements.length; ++j) {
js.eventListener(blurableElements[j]).remove('iosBlur', 'blur');
js.eventListener(blurableElements[j]).add('iosBlur', 'blur', function () {
window.setTimeout(function() {
if (iosTapTarget) {
js.eventListener(iosTapTarget).remove('iosTapClick', 'click');
js.triggerEvent(iosTapTarget, 'click');
}
}, 50);
});
}
}
PS: Event handling comes from my own JS "framework" js.js available here: https://github.com/JanST123/js.js
But you can use vanilla JS event handling or jQuery event handling too, of course.

How to differentiate dblclick, Right-click and mousewheel click on a shape dragged on to paper element JointJS Rappid

I am trying to implement code for different events on a shape which is dragged on to the paper element from stencil. pointerup event triggers a halo with options around the element. Double click event triggers some modal window and right click event triggers a custom context menu with click actions. How can i differentiate different events in Rappid like leftclick, rightclick, clicking on mouse wheel. I have code as below.
this.paper.on({
'element:pointerup': onElementClick,
//something like contextmenu
//'element:contextmenu': onElementRightClick,
});
This is a workaround i got from rappid for click and doubleclick.It is working but i am looking for rightclick functionality too. please, help.
paper.on({
'element:pointerdown': onElementClick
});
var clickTimerId;
function onElementClick(view) {
if (clickTimerId) {
// double click
window.clearTimeout(clickTimerId);
clickTimerId = null;
onElementDblClick(view);
} else {
// single click
clickTimerId = window.setTimeout(click, 200);
}
function click() {
clickTimerId = null;
// open halo and inspector here
}
}
function onElementDblClick(view) {
// open the modal window here
}
cell:contextmenu - triggered when the user right-clicks a cell in the paper.
from the jointjs api documentation
so please try the below
paper.on({
'element:contextmenu': onElementRightClick
});
function onElementRightClick(view) {
}

Click source in JavaScript and jQuery, human or automated?

We all know that you can simulate click or any other event on an element using one of these ways:
$('#targetElement').trigger('eventName');
$('#targetElement').click();
I have encountered a situation in which, I should know how an element is clicked. I should know if it's been clicked automatically via code, or by pressing mouse button. Is there anyway I can do it without hacks or workarounds? I mean, is there anything built into browsers' event object, JavaScript, or jQuery that can tell us whether click has been initiated by a human action or by code?
Try this:
$('#targetElement').click(function(event, generated) {
if (generated) {
// Event was generated by code, not a user click.
} else {
// Event was generated by a user click.
}
});
Then, to make this work, you have to trigger them like this:
$('#targetElement').trigger('click', [true]);
See this jsfiddle.
Check out event.which, it'll be undefined if triggered with code.
$(document).click(function(event) {
if (event.which) {
// Triggered by the event.
} else {
// Triggered with code.
}
});
jsFiddle.
Here's one way I have found (tested in Chrome)
$('#foo').click(function(e) {
if (e.originalEvent)
alert('Has e (manual click)');
else
alert('No e (triggered)');
});
See here for testing: http://jsfiddle.net/ZPD8w/2/
In your immediate event handler, provide an e parameter. If the click is automated (via code), this e would be undefined (no need to check e.target as #alex has said):
$('#targetElement').click(function(e){
if(e)
{
// Click is triggered by a human action
}
else
{
// Click is triggered via code
}
});

Categories