How do I send keystrokes to Firefox using Test::WWW::Selenium? - javascript

I have tried:
$sel->type_keys_ok("//fieldset[2]/input", "KEYS");
No results. Nothing changed.
Also tried:
$sel->send_keys_ok("//fieldset[2]/input", "KEYS");
Not implemented.
Tried also:
my $res = $sel->get_eval('
function simulateKeyEvent(character) {
var evt = document.createEvent("KeyboardEvent");
(evt.initKeyEvent || evt.initKeyboardEvent)("keypress", true, true, window,
0, 0, 0, 0,
0, character.charCodeAt(0))
var canceled = !body.dispatchEvent(evt);
if(canceled) {
// A handler called preventDefault
alert("canceled");
} else {
// None of the handlers called preventDefault
alert("not canceled");
}
};
simulateKeyEvent("K");' );
Then I got this ERROR: 'initKeyEvent' called on an object that does not implement interface KeyboardEvent. Thanks.

version 1:
my $element = $sel->find_element("//input[\#name='q']");
$element->send_keys("KEYS");
$element->submit();
version 2 using WDKeys:
use Selenium::Remote::WDKeys;
my $element = $sel->find_element("//input[\#name='q']");
$element->send_keys("KEYS");
$sel->send_keys_to_active_element(KEYS->{'enter'});
for more information look at CPAN Selenium::Remote::Driver

Related

How to trigger an element by id? (".click();" doesn't work)

I want to trigger this element in Google Translate, so that it would always auto-correct everything I type.
https://i.snag.gy/NRsWFB.jpg
The element's id is "spelling-correction".
I tried this:
document.getElementById('spelling-correction').click();
And this:
function clickLink(link) {
var cancelled = false;
if (document.createEvent) {
var event = document.createEvent("MouseEvents");
event.initMouseEvent("click", true, true, window,
0, 0, 0, 0, 0,
false, false, false, false,
0, null);
cancelled = !link.dispatchEvent(event);
}
else if (link.fireEvent) {
cancelled = !link.fireEvent("onclick");
}
if (!cancelled) {
window.location = link.href;
}
}
setInterval(function copyText() {
var correction123 = document.getElementById("spelling-correction");
correction123.clickLink();
}, 100);
But they don't work unfortunately. I would like to somehow trigger this "spelling-correction", so that whatever I write would be auto-corrected.
Thank you in advance!
The issue is you're clicking on a div. Divs do nothing when clicked (unless otherwise specified).
Since what you want seems to be clicking on the link itself, you should try something like this instead:
childAnchors = document.querySelectorAll("#spelling-correction > a");
childAnchors[0].click();

Simulate User-Agent click in browser with JS [duplicate]

I'm just wondering how I can use JavaScript to simulate a click on an element.
Currently I have:
function simulateClick(control) {
if (document.all) {
control.click();
} else {
var evObj = document.createEvent('MouseEvents');
evObj.initMouseEvent('click', true, true, window, 1, 12, 345, 7, 220, false, false, true, false, 0, null );
control.dispatchEvent(evObj);
}
}
test 1<br>
<script type="text/javascript">
simulateClick(document.getElementById('mytest1'));
</script>
But it's not working :(
Any ideas?
What about something simple like:
document.getElementById('elementID').click();
Supported even by IE.
[Edit 2022] The answer was really outdated. Modernized it. The original answer is at the bottom.
Use element.dispatchEvent with a freshly created Event of the desired type.
Here's an example using event delegation.
Fork this stackblitz project to play around with it.
// Note: {bubbles: true} because of the event delegation ...
document.addEventListener(`click`, handle);
document.addEventListener(`virtualhover`, handle);
// the actual 'trigger' function
const trigger = (el, etype, custom) => {
const evt = custom ?? new Event( etype, { bubbles: true } );
el.dispatchEvent( evt );
};
// a custom event ;)
const vHover = new CustomEvent(`virtualhover`,
{ bubbles: true, detail: `red` });
setTimeout( _ =>
trigger( document.querySelector(`#testMe`), `click` ), 1000 );
function handle(evt) {
if (evt.target.id === `clickTrigger`) {
trigger(document.querySelector(`#testMe`), `click`);
}
if (evt.type === `virtualhover`) {
evt.target.style.color = evt.detail;
return setTimeout( _ => evt.target.style.color = ``, 1000 );
}
if (evt.target.id === `testMe`) {
document.querySelector(`#testMeResult`)
.insertAdjacentHTML(`beforeend`, `<p>One of us clicked #testMe.
It was <i>${evt.isTrusted ? `<b>you</b>` : `me`}</i>.</p>`);
trigger(
document.querySelector(`#testMeResult p:last-child`),
`virtualhover`,
vHover );
}
}
body {
font: 1.2rem/1.5rem verdana, arial;
margin: 2rem;
}
#testMe {
cursor: pointer;
}
p {
margin: 0.2rem 0;
}
<div id="testMe">
Test me can be clicked
</div>
<p><button id='clickTrigger'>Click #testMe</button></p>
<div id="testMeResult"></div>
The old answer:
Here's what I cooked up. It's pretty simple, but it works:
function eventFire(el, etype){
if (el.fireEvent) {
el.fireEvent('on' + etype);
} else {
var evObj = document.createEvent('Events');
evObj.initEvent(etype, true, false);
el.dispatchEvent(evObj);
}
}
Have you considered using jQuery to avoid all the browser detection? With jQuery, it would be as simple as:
$("#mytest1").click();
var elem = document.getElementById('mytest1');
// Simulate clicking on the specified element.
triggerEvent( elem, 'click' );
/**
* Trigger the specified event on the specified element.
* #param {Object} elem the target element.
* #param {String} event the type of the event (e.g. 'click').
*/
function triggerEvent( elem, event ) {
var clickEvent = new Event( event ); // Create the event.
elem.dispatchEvent( clickEvent ); // Dispatch the event.
}
Reference
https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events
https://codepen.io/felquis/pen/damDA
You could save yourself a bunch of space by using jQuery. You only need to use:
$('#myElement').trigger("click")
The top answer is the best! However, it was not triggering mouse events for me in Firefox when etype = 'click'.
So, I changed the document.createEvent to 'MouseEvents' and that fixed the problem. The extra code is to test whether or not another bit of code was interfering with the event, and if it was cancelled I would log that to console.
function eventFire(el, etype){
if (el.fireEvent) {
el.fireEvent('on' + etype);
} else {
var evObj = document.createEvent('MouseEvents');
evObj.initEvent(etype, true, false);
var canceled = !el.dispatchEvent(evObj);
if (canceled) {
// A handler called preventDefault.
console.log("automatic click canceled");
} else {
// None of the handlers called preventDefault.
}
}
}
Simulating an event is similar to creating a custom event. To simulate a mouse event
we gonna have to create MouseEvent using document.createEvent().
Then using initMouseEvent(), we've to set up the mouse event that is going to occur.
Then dispatched the mouse event on the element on which you'd like to simulate an event.
In the following code, I've used setTimeout so that the button gets clicked automatically after 1 second.
const div = document.querySelector('div');
div.addEventListener('click', function(e) {
console.log('Simulated click');
});
const simulatedDivClick = document.createEvent('MouseEvents');
simulatedDivClick.initEvent(
'click', /* Event type */
true, /* bubbles */
true, /* cancelable */
document.defaultView, /* view */
0, /* detail */
0, /* screenx */
0, /* screeny */
0, /* clientx */
0, /* clienty */
false, /* ctrlKey */
false, /* altKey */
false, /* shiftKey */
0, /* metaKey */
null, /* button */
null /* relatedTarget */
);
// Automatically click after 1 second
setTimeout(function() {
div.dispatchEvent(simulatedDivClick);
}, 1000);
<div> Automatically click </div>
In javascript grab element by its id or class name and then apply .click() to make click happens
like:
document.getElementById("btnHandler").click();
document.getElementById('elementId').dispatchEvent(new MouseEvent("click",{bubbles: true, cancellable: true}));
Follow this link to know about the mouse events using Javascript and browser compatibility for the same
https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent#Browser_compatibility
Honestly none of the answers here worked for my specific case. jquery was out of the question so all those answers are untested. I will say I built this answer up from #mnishiguchi answer above but this was the only thing that actually ended up working.
// select the element by finding the id of mytest1
const el = document.querySelector('#mytest1');
// pass the element to the simulateClick function
simulateClick( el );
function simulateClick(element){
trigger( element, 'mousedown' );
trigger( element, 'click' );
trigger( element, 'mouseup' );
function trigger( elem, event ) {
elem.dispatchEvent( new MouseEvent( event ) );
}
}
Use timeout if the event is not getting triggered
setTimeout(function(){ document.getElementById('your_id').click(); }, 200);
This isn't very well documented, but we can trigger any kinds of events very simply.
This example will trigger 50 double click on the button:
let theclick = new Event("dblclick")
for (let i = 0;i < 50;i++){
action.dispatchEvent(theclick)
}
<button id="action" ondblclick="out.innerHTML+='Wtf '">TEST</button>
<div id="out"></div>
The Event interface represents an event which takes place in the DOM.
An event can be triggered by the user action e.g. clicking the mouse
button or tapping keyboard, or generated by APIs to represent the
progress of an asynchronous task. It can also be triggered
programmatically, such as by calling the HTMLElement.click() method of
an element, or by defining the event, then sending it to a specified
target using EventTarget.dispatchEvent().
https://developer.mozilla.org/en-US/docs/Web/API/Event
https://developer.mozilla.org/en-US/docs/Web/API/Event/Event
document.getElementById("element").click()
Simply select the element from the DOM. The node has a click function, which you can call.
Or
document.querySelector("#element").click()
The solution that worked for me....
Click event can be called on clicking the button or do it from JavaScript file.
In this code either click on the button to show alert or simply call it on some condition or without condition
function ss(){
alert('dddddddddddddddddddddddd');
}
var mybtn=document.getElementById('btn');
mybtn.click();
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
<button id="btn" onclick="ss()">click to see </button>
</body>
</html>
const Discord = require("discord.js");
const superagent = require("superagent");
module.exports = {
name: "hug",
category: "action",
description: "hug a user!",
usage: "hug <user>",
run: async (client, message, args) => {
let hugUser = message.mentions.users.first()
if(!hugUser) return message.channel.send("You forgot to mention somebody.");
let hugEmbed2 = new Discord.MessageEmbed()
.setColor("#36393F")
.setDescription(`**${message.author.username}** hugged **himself**`)
.setImage("https://i.kym-cdn.com/photos/images/original/000/859/605/3e7.gif")
.setFooter(`© Yuki V5.3.1`, "https://cdn.discordapp.com/avatars/489219428358160385/19ad8d8c2fefd03fa0e1a2e49a2915c4.png")
if (hugUser.id === message.author.id) return message.channel.send(hugEmbed2);
const {body} = await superagent
.get(`https://nekos.life/api/v2/img/hug`);
let hugEmbed = new Discord.MessageEmbed()
.setDescription(`**${message.author.username}** hugged **${message.mentions.users.first().username}**`)
.setImage(body.url)
.setColor("#36393F")
.setFooter(`© Yuki V5.3.1`, "https://cdn.discordapp.com/avatars/489219428358160385/19ad8d8c2fefd03fa0e1a2e49a2915c4.png")
message.channel.send(hugEmbed)
}
}

Simulate a click on 'a' element using javascript/jquery

I am trying to simulate a click on on an element.
HTML for the same is as follows
<a id="gift-close" href="javascript:void(0)" class="cart-mask-close p-abs" onclick="_gaq.push(['_trackEvent','voucher_new','cart',$(this).attr('rel')+'-mask_x_button-inaction']);" rel="coupon"> </a>
How can i simulate a click on it. I have tried
document.getElementById("gift-close").click();
But its not doing anything
Using jQuery: $('#gift-close').trigger('click');
Using JavaScript: document.getElementById('gift-close').click();
Using jQuery:
$('#gift-close').click();
Try to use document.createEvent described here https://developer.mozilla.org/en-US/docs/Web/API/document.createEvent
The code for function that simulates click should look something like this:
function simulateClick() {
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
var a = document.getElementById("gift-close");
a.dispatchEvent(evt);
}
The code you've already tried:
document.getElementById("gift-close").click();
...should work as long as the element actually exists in the DOM at the time you run it. Some possible ways to ensure that include:
Run your code from an onload handler for the window. http://jsfiddle.net/LKNYg/
Run your code from a document ready handler if you're using jQuery. http://jsfiddle.net/LKNYg/1/
Put the code in a script block that is after the element in the source html.
So:
$(document).ready(function() {
document.getElementById("gift-close").click();
// OR
$("#gift-close")[0].click();
});
Code snippet underneath!
Please take a look at these documentations and examples at MDN, and you will find your answer. This is the propper way to do it I would say.
Creating and triggering events
Dispatch Event (example)
Taken from the 'Dispatch Event (example)'-HTML-link (simulate click):
function simulateClick() {
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
var cb = document.getElementById("checkbox");
var canceled = !cb.dispatchEvent(evt);
if(canceled) {
// A handler called preventDefault
alert("canceled");
} else {
// None of the handlers called preventDefault
alert("not canceled");
}
}
This is how I would do it (2017 ..) :
Simply using MouseEvent.
function simulateClick() {
var evt = new MouseEvent("click");
var cb = document.getElementById("checkbox");
var canceled = !cb.dispatchEvent(evt);
if (canceled) {
// A handler called preventDefault
console.log("canceled");
} else {
// None of the handlers called preventDefault
console.log("not canceled");
}
}
document.getElementById("button").onclick = evt => {
simulateClick()
}
function simulateClick() {
var evt = new MouseEvent("click");
var cb = document.getElementById("checkbox");
var canceled = !cb.dispatchEvent(evt);
if (canceled) {
// A handler called preventDefault
console.log("canceled");
} else {
// None of the handlers called preventDefault
console.log("not canceled");
}
}
<input type="checkbox" id="checkbox">
<br>
<br>
<button id="button">Check it out, or not</button>
Use this code to click:
$("#gift-close").click();
Try adding a function inside the click() method.
$('#gift-close').click(function(){
//do something here
});
It worked for me with a function assigned inside the click() method rather than keeping it empty.
Here, try this one:
$('#gift-close').on('click', function () {
_gaq.push(['_trackEvent','voucher_new','cart',$(this).attr('rel')+'-mask_x_button-inaction']);
});

How to make a click over a button inside a dynamically loaded iframe

The title say it all. I am working with a iframe whose the only thing I know is part of their src attribute. Until now I can reach the target element (an anchor) by their (known) id:
var f = $('iframe[src^="url"]', newTabBrowser.contentDocument);
if ( ! f.length)
return;
var b = f.contents().find('#button');
if ( ! b.length)
return;
At this point I have the desired anchor element into the jQuery variable b, but I can't click it. The anchor is like this:
I have tried:
b.click();
and:
simulateClick(b);
function simulateClick(elm) {
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
var canceled = !elm.dispatchEvent(evt);
if(canceled) {
return false;
} else {
return true;
}
}
None of both works. Any idea about how to proceed or another technique to try?
OBS: This is part of a FF addon. That's why I use newTabBrowser.contentDocument
Does this work for you:
$(document).ready(function() {
var frame = $('#iframeID').get(0).contentDocument;
$('#button', frame).click(function() {
alert("Clicked me..!");
});
});
Hope it helps in some sense.

Simulate scroll event using Javascript

I am trying to Simulate a scroll event using Javascript for Mobile Safari.
I am using the following code
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("scroll", true, true, window,0, 0, 0, 0, 0, false, false, false, false, 0, null);
The above code is part of a jQuery plugin jQuery.UI.Ipad which basically maps touch events like touchstart, touchmove, touchend to mouse events like mouseover, mousedown, etc
However for some reasons the code for simulating a scroll event is not working... Please help me. So essentially my question is how do I simulate the scroll event.
I think people are confused as to why you would overide the scroll control. I can see why you want to imitate mouse events, but scroll maybe should not be one of them.
Usually for scroll changes you can just get the scroll with:
var top = document.body.scrollTop;
And set with:
document.body.scrollLeft = sX;
document.body.scrollTop = sY;
So, I know I' need to simulate it too. for me it's when you have a lightbox with a overflow box that you would need it. Just one case of many I can think of. looking to for an answer. Just thought I'd share where I'm at, thou not with the jQuery.Ui.Ipad I will Google that.. but here is what I got so far and does work but not perfectly.
var inTouch=false;
var timers_arr = new Array();
var c=0;
var t;
var timer_is_on=0;
//-------------------------------------------------------------------------------------------------------------------------------------------------------------
// jeremy's timer functions
//-------------------------------------------------------------------------------------------------------------------------------------------------------------
function clearCount(timer){
/// clear the time from timer
clearTimeout(timers_arr[timer]);
/// Make sure it's clear
timers_arr[''+timer+'']=0;
delete timers_arr[''+timer+''];
}
function setCount(timer,time,func){
clearCount(timer);
if(timers_arr[timer]==0||typeof(timers_arr[timer]) === 'undefined'){
timers_arr[timer]=setTimeout(function(){
func();
},time);
}
}
function updatePos(evt,startY){
setCount('touchmove',1,function(){
var orig = evt.originalEvent;
var curY = orig.changedTouches[0].pageY;
var y = curY - startY;
var sliderVal = $("#slider-vertical").slider("value");
sliderVal += (y*.008);
$("#slider-vertical").slider("value", sliderVal);
updatePos(evt,startY);
});
setCount('touchmove_anitMotion',200,function(){
clearCount('touchmove');
clearCount('touchmove_anitMotion');
});
}
var startX=0;
var startY=0;
var x=0;
var y=0;
var direction='';
$('body').bind("onorientationchange", updateOrientation, false);
$('#scroll-pane').live("touchstart", function(evt){
inTouch=true;
startX = event.targetTouches[0].pageX;
startY = event.targetTouches[0].pageY;
});
$('#scroll-pane').live("touchmove", function(evt){
evt.stopPropagation();
evt.preventDefault();
updatePos(evt,startY);
});
$('#scroll-pane').live("touchend", function(evt){
startX=0;
startY=0;
clearCount('touchmove');
inTouch=false;
});
$('#scroll-pane').live("touchcancel", function(evt){
startX=0;
startY=0;
clearCount('touchmove');
inTouch=false;
});
Again not perfect and looking to fix it.. but it's at the least working. Now note, this is a div that is using the jQuery UI slider for a scroll bar as (thou in mine it's vertical) shown in
http://jqueryui.com/demos/slider/#side-scroll
Hope that spurs some ideas. If I get a super stable answer I'll get back.
Cheers -Jeremy
I needed this to write a unit test , for which i need to simulate a scroll event
function dispatchScroll(target,newScrollTop) {
target.scrollTop = newScrollTop;
var e = document.createEvent("UIEvents");
// creates a scroll event that bubbles, can be cancelled,
// and with its view and detail property initialized to window and 1,
// respectively
e.initUIEvent("scroll", true, true, window, 1);
target.dispatchEvent(e);
}
For more details : https://developer.mozilla.org/en-US/docs/Web/API/event.initUIEvent
The event that worked for me was mousewheel, and the 5th parameter needs to be positive for scrolldown and negative for scrollup.
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("mousewheel", true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
Note that the event type is DOMMouseScroll for FireFox.
Events should now be created with CustomEvent as such new CustomEvent("wheel", { detail: { deltaY: 1 } }). document.createEvent is deprecated
https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent
I built this utility function that scrolls by 1 pixel every frame
const startFakeScrolling = (container: HTMLDivElement) => {
const cb = () => {
container.dispatchEvent(
new CustomEvent("wheel", { detail: { deltaY: 1 } })
);
window.requestAnimationFrame(cb);
};
window.requestAnimationFrame(cb);
};
You will also need to modify the event listener to use detail, as deltaY will be undefined
const delta = e.deltaY != null ? e.deltaY : (e.detail as any).deltaY;

Categories