dispatchEvent not working in firefox - javascript

I was trying to open a new tab inside my JavaScript. It works as expected in Chrome, but when it comes to Firefox it does nothing.I know window.open() can be used to open a tab, but my intention is to keep the focus on the current page. I have spent my entire day searching for a fix for this, but all I could see is people claiming it is a bug in Firefox. I wanted to know if there is any work around for this. Here is the piece of code I am using.
var a = document.createElement("a");
a.href = popup_url;//this comes from the function's argument
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0,
true, false, false, false, 0, null);
a.dispatchEvent(evt);

Here is the working function (see):
function click(node){
var evt=new MouseEvent('click',
{'view':window,'bubbles':true,'cancelable':true});
node.dispatchEvent(evt);
}

Related

GMail - Flag mail as important via JQuery/Javascript

I'm creating a Chrome Extension that should take some actions inside GMail webmail interface.
One of the actions is to mark an e-mail as important, but I'm really struggling to simulate the click() event on the elements needed to achieve this.
To reproduce the problem easier, we can forget the "chrome extension", and just focus on browser console. Inside GMail interface, with an email message opened, simply try to click on "More" icon, and "Mark as Important". I tried many elements (parent, children, eq(0), eq(1), etc...) around the main ones, but nothing seem to trigger the "Mark as important" option.
Right now, what I found that works for the More menu, is:
function clickSimulate(element)
{
var down = new MouseEvent('mousedown');
var up = new MouseEvent('mouseup');
element.dispatchEvent(down);
element.dispatchEvent(up);
}
clickSimulate($("div[data-tooltip='More']")[0]);
The mark as important option still unsuccessful. Anybody has a solution?
I still considering the use of IMAP or GMail API(not sure what this is) to solve this problem. But some specific actions needed would be better fitted inside a javascript code running into webmail interface. That's why I still insist trying to fix this specific problem (mark as important) using the same solution.
I got it working by doing:
function clickSimulate(element)
{
var evt = document.createEvent('MouseEvents');
evt.initMouseEvent('mousedown', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
element.dispatchEvent(evt);
var evt = document.createEvent('MouseEvents');
evt.initMouseEvent('mouseup', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
element.dispatchEvent(evt);
}
Calling this function 2 times on the Mark as Important element, works.

How can i open a new tab using protractor and Chrome browser

Here is a code (new tab doesn't open):
//open new tab in Chrome
browser.actions().sendKeys(protractor.Key.CONTROL +'t').perform();
If we used code with 'a' - everything is fine:
//select all on the page
browser.actions().sendKeys(protractor.Key.CONTROL +'a').perform();
protractor v.1.3.1
Chrome v.37
ChromeDriver v.2.10
WebDriver v.2.43
If you really don't want to add an element to your DOM, then you can try this:
let url = https://google.com;
return browser.executeScript("return window.open(arguments[0], '_blank')", url);
//opens google.com in a new tab (works fine with Chrome. P.S. have only tested
// Chrome with Protractor).
I had tried the above statement with a browser.wait(), see if you really need the wait as browser.executeScript() returns a promise itself, can just utilize the promise's success.
Also, I have observed that although it seems that the focus of the browser has changed to the newly opened tab, I was unable to access the elements of the new tab. To do that:
browser.getAllWindowHandles().then((handles) => {
browser.switchTo().window(handles[1]); // pass the index, here assuming that
// there are only two tabs in the browser
})
To know more about window.open(), you can visit this.
Selenium doesn't provide a way to do this so a workaround seems to be the only way.
Assuming you're in Windows or Linux, your CTRL+T idea should be written as below, however that hack failed for me:
browser.actions().keyDown(protractor.Key.CONTROL).sendKeys('t').perform();
Even attempting to do it on an element:
$$('input').first().sendKeys(protractor.Key.chord(protractor.Key.CONTROL, "t"));
Good news is the following hack does seem to work, feel free to replace location.href with the url you want to open:
browser.driver.executeScript(function() {
(function(a){
document.body.appendChild(a);
a.setAttribute('href', location.href);
a.dispatchEvent((function(e){
e.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, true, false, false, false, 0, null);
return e;
}(document.createEvent('MouseEvents'))))}(document.createElement('a')));
});
This piece of code works for me in TypeScript with protractor.
import {browser} from 'protractor';
export class Browser {
public async openPageInNewTab(url: string) {
await this.createNewBrowserTab();
await this.switchToTabNumber(1);
await browser.get(url);
}
public createNewBrowserTab() {
browser.executeScript('window.open()');
}
public async switchToTabNumber(number: number) {
return browser.getAllWindowHandles().then(function (handles) {
const newWindowHandle = handles[number];
browser.switchTo().window(newWindowHandle);
});
}
}
I think problem with "open a new tab" in ChromeDriver, I found a bug like this:
https://code.google.com/p/chromedriver/issues/detail?id=903&q=new%20tab&colspec=ID%20Status%20Pri%20Owner%20Summary

why hyperlinks are not working in IE 11?

I have a form. It contains some hyperlinks. I can click on them and get another page in browsers like Google Chrome and Mozila Firefox but instead, I am unable to open them in IE9, IE10,..
What might be the problem? and whats the solution? help me.
In dev-tool(console), I am getting
un-terminated string constant error
.
Apart from any coding this could be the reason:
A previously installed browser or add-in might be interfering with ie browser on your computer.
or it might be a result of bad DCOM.
If bad DCOM is the problem you can get solution here:- http://www.techsupportall.com/links-are-not-working/
Jay,
This might happen due to incorrect concatenations or omission of the semicolon(;) at the end of statement.
Or may be any server variable that is not being populated. Like:
var var1 ='<% = someServerVariable %>'
someCode
It is possible that some someServerVariable is not being populated and the browser compiler would read the code as
var1 = someCode
Please look into your code and find out if there is any similar issue with your code. Or the best is to share your code snippet to point out the exact issue.
I ran into this same exact problem. For me, whenever I was embedding links in an ul / li list format, it just wouldn't let me click the first link (happens a lot navigation menus).It would only let me click the embedded ones. My work around for this was using java-script to create a force the click and pass.
Put this script in your head
<script>
function fakeClick(event, anchorObj) {
if (anchorObj.click) {
anchorObj.click()
} else if(document.createEvent) {
if(event.target !== anchorObj) {
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
var allowDefault = anchorObj.dispatchEvent(evt);
// you can check allowDefault for false to see if
// any handler called evt.preventDefault().
// Firefox will *not* redirect to anchorObj.href
// for you. However every other browser will.
}
}
}
</script>
And then in the body you can use this convention for any link you need to be forced clicked.
<a id="link" href="#YourDestinationLinkHere" onclick="fakeClick((event.target || event.srcElement).innerHTML)">Destination</a>

Open multiple tabs with jQuery

Ok, I feel I have done my due diligence here... JSFIddle - http://jsfiddle.net/taytayevanson/8BpHw/5/
I am trying to create a page that will pop multiple tabs. I understand that using this code...
New Tab
will pop 1 new tab. However, as explained in this stackoverflow q/a, it needs to be a "user initiated event" for Chrome to pop a new tab and not a window. Because of this requirement, a loop will pop 1 new tab and then new windows for each following link.
jQuery("a.site").each(function(){
var string = jQuery(this).attr("href") + "/" + jQuery("#arguments").val();
jQuery(this).attr("href",string);
jQuery(this).trigger('click');
});
I have tried programmatically creating links and clicking them, with different plugins, timeouts, methods, and I even tried "daisy-chaining" the process and firing it on a page load (a huge PHP/GET variable/page load trigger thing) but it would still pop windows because the event was not user initiated.
I tried 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;
}
}
and although I can read it, I don't understand it well enough to comprehend what i'm supposed to pass into this function. I tried something like this...
jQuery("a.site").each(function(){
var string = jQuery(this).attr("href") + "/" + jQuery("#launcher").val();
jQuery(this).attr("href",string);
clickLink(jQuery(this));
});
But I get a "object has no method 'dispatchEvent'" console error. I tried using that same "var event" and just calling...
link.trigger(event);
but there was a console error there as well. The only thing I have not tried is in this Q/A (using jQuery.get() to open a tab and write to it) but seeing as it still calls window.open(), I feel like i'll still run into the exact same loop issue.
Ok. Got all that out of the way... Is there a real answer for this besides "it's controlled by your browser" ? I feel like there must be a way. Thank you, sorry for the novel :)
See using dispatchEvent to open new tab: {tested on chrome}
DEMO
$('a.site').each(function () {
var clk = document.createEvent("MouseEvents");
clk.initMouseEvent("click", false, true, window, 0, 0, 0, 0, 0, true, false, false, true, 0, null);
this.dispatchEvent(clk);
});
I wouldn't rely on using a triggered click to open a link, not all browsers will support it the same as if user clicks on it ( for obvious security reasons)
Would just loop through the elements and and grab the href, manipulate it the way you want, and pass result to window.open(url).

JavaScript simulate right click through code

I am writing some UI tests using Selenium and i have a JavaScript Tree control, using the Dojo toolkit.
I have implemented a context menu for each node of the tree using the examples that Dojo provide, but I need the Selenium test to "invoke" the right click on the tree node, but I cannot get this to work. The tests simply do not simulate the right-click event through JavaScript, and the context menu does not show up.
Has anyone had any experience in invoking the right click on a context menu using Dojo and Selenium? Or have any ideas as to how to do it?
try this instead, reason what things didn't quite work is that the context menu is in fact bound to the oncontextmenu event.
function contextMenuClick(element){
var evt = element.ownerDocument.createEvent('MouseEvents');
var RIGHT_CLICK_BUTTON_CODE = 2; // the same for FF and IE
evt.initMouseEvent('contextmenu', true, true,
element.ownerDocument.defaultView, 1, 0, 0, 0, 0, false,
false, false, false, RIGHT_CLICK_BUTTON_CODE, null);
if (document.createEventObject){
// dispatch for IE
return element.fireEvent('onclick', evt)
}
else{
// dispatch for firefox + others
return !element.dispatchEvent(evt);
}
}
Just for good measure, here is a bit of doco on the parameters:
var myEvt = document.createEvent('MouseEvents');
myEvt.initMouseEvent(
'click' // event type
,true // can bubble?
,true // cancelable?
,window // the event's abstract view (should always be window)
,1 // mouse click count (or event "detail")
,100 // event's screen x coordinate
,200 // event's screen y coordinate
,100 // event's client x coordinate
,200 // event's client y coordinate
,false // whether or not CTRL was pressed during event
,false // whether or not ALT was pressed during event
,false // whether or not SHIFT was pressed during event
,false // whether or not the meta key was pressed during event
,1 // indicates which button (if any) caused the mouse event (1 = primary button)
,null // relatedTarget (only applicable for mouseover/mouseout events)
);
Great question!
I did some research, and it seems like you can fire a mouse event like is shown here, and make it a right-click by setting the button or which property to 2 (documented here).
Perhaps this code will work:
function rightClick(element){
var evt = element.ownerDocument.createEvent('MouseEvents');
var RIGHT_CLICK_BUTTON_CODE = 2; // the same for FF and IE
evt.initMouseEvent('click', true, true,
element.ownerDocument.defaultView, 1, 0, 0, 0, 0, false,
false, false, false, RIGHT_CLICK_BUTTON_CODE, null);
if (document.createEventObject){
// dispatch for IE
return element.fireEvent('onclick', evt)
}
else{
// dispatch for firefox + others
return !element.dispatchEvent(evt);
}
}
Here is a more correct version if you do not care about where the context menu gets fired up
function fireContextMenu(el) {
var evt = el.ownerDocument.createEvent("HTMLEvents")
evt.initEvent('contextmenu', true, true) // bubbles = true, cancelable = true
if (document.createEventObject) {
return el.fireEvent('oncontextmenu', evt)
}
else {
return !el.dispatchEvent(evt)
}
}
If you do, we may have to use the previous one, fix up it's behaviour in IE, and populate the screenX, screenY, clientX, clientY etc appropriately
I am trying this in firefox and chrome, but dispatching the contextmenu event doesn't make browser to open context menu. Event is triggered because my callback for oncontextmenu is fired, but context menu is still missing. Anybody have an idea, because I used all code samples from above?

Categories