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).
Related
I am printing data from a new window after which I want to close the window. If I close the window straight away then it doesn't have enough time for the javascript function to run which writes data to the document.
I am using setTimeout to mimic this behaviour. However, I am wondering if there is a native way to do this.
For obvious reasons setting time out isn't an optimal solution as many things could block execution etc - perhaps a callback from the print function would do the trick, docs do not mention anything about it though.
Here's my code:
nw.Window.open('print.html', {show: false, new_instance: false}, function(new_win) {
new_win.on('loaded', function() {
this.print({autoprint: true, headerFooterEnabled: false});
});
});
And in the print.html:
var div = document.getElementById("orderBill");
div.innerHTML = '<h1>Header</h1><p>Some text</p>';
var win = nw.Window.get();
setTimeout(function(){ win.close(); }, 5000);
Move the window.close() to the onafterprint event?
https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onafterprint
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.
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
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>
I am currently building a browser extension that injects javascript/jquery into certain pages, and i am having a weird issue, where forcing .click() events are not working from my injected code. The strange bit is that it works completely fine if i make the call from my console js console.
I dont really understand what the problem is. It seems that all of my other calls are working fine. I can bind to click events using .click(function(){...}) (so clearly my jquery has been loaded properly), and call methods when things are clicked (so clearly my jquery has been loaded properly), but the second that i try to force a click, the call just does not go through.
Can anybody explain what is happening, or a way that i can get around it?
(i can not recreate this issue, because the problem clearly has to do with injecting the js in an extension)
this is the best i can do for recreation:
//I have tried all of these separately
console.log($("#this_is_an_id")) //This returns the correct element
$("#this_is_an_id").click() //This does not work at all
$("#this_is_an_id").trigger("click") //I have also tried this without success
$("#this_is_an_id").click(function(){ console.log("stuff") }) //This works fine.
Really, at this point, i am assuming it is not my fault, but something that is wrong with the browser's method of injecting script. I am sorta looking for really hackey ways to fix this, i also tried eval('$("#this_is_an_id").trigger("click")'). Does anybody have any other suggestions?
I finally found a very excellent answer/work around to this issue here:
Trigger events from Firefox browser extension?
From user cms:
First of all, for click events, you need to create an event object with type MouseEvents, not HTMLEvents, and use event.initMouseEvent instead of event.initEvent.
To access the document of the current tab of Firefox from a XUL overlay, you can use the content.document property, but since you already have access to the DOM element you want to click, you can use the Node.ownerDocument property, which will refer to the top-level document object for this node.
I have made a simple function to simulate MouseEvents:
function triggerMouseEvent(element, eventName, userOptions) {
var options = { // defaults
clientX: 0, clientY: 0, button: 0,
ctrlKey: false, altKey: false, shiftKey: false,
metaKey: false, bubbles: true, cancelable: true
// create event object:
}, event = element.ownerDocument.createEvent("MouseEvents");
if (!/^(?:click|mouse(?:down|up|over|move|out))$/.test(eventName)) {
throw new Error("Only MouseEvents supported");
}
if (typeof userOptions != 'undefined'){ // set the userOptions
for (var prop in userOptions) {
if (userOptions.hasOwnProperty(prop))
options[prop] = userOptions[prop];
}
}
// initialize the event object
event.initMouseEvent(eventName, options.bubbles, options.cancelable,
element.ownerDocument.defaultView, options.button,
options.clientX, options.clientY, options.clientX,
options.clientY, options.ctrlKey, options.altKey,
options.shiftKey, options.metaKey, options.button,
element);
// dispatch!
element.dispatchEvent(event);
}
Usage:
triggerMouseEvent(element, 'click');
Check a test usage here.
You can pass also an object as the third argument, if you want to change the values of the event object properties.
Thank you so much for this answer. O_O