GMail - Flag mail as important via JQuery/Javascript - 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.

Related

dispatchEvent not working in firefox

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);
}

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).

How to synthesize key presses in Javascript

I would like to write some tests for some input filtering code in a text box. For most tests, I can just call setValue and trigger the change event, which is easy to do. However, in this case, because I want to test that the input gets filtered out (or not), I can't just setValue() directly.
I tried dispatching keydown, keyup, keypress, textinput events. I can see that the handlers for them are being called, but the text doesn't actually show in the text box Note that this only "works" in Firefox, I understand the code would look different for other browsers.
function dispatch(target, eventType, charCode) {
var evt = document.createEvent("KeyboardEvent");
evt.initKeyEvent(
eventType,
true,
true,
window,
false,
false,
false,
false,
charCode,
0
);
target.dispatchEvent(evt);
}
var id = document.getElementById('id');
id.onkeydown = id.onkeyup = id.onkeypress = function() {console.log(arguments)}
dispatch(id, 'keydown', 65);
dispatch(id, 'keyup', 65);
dispatch(id, 'keypress', 65);
dispatch(id, 'textinput', 65);
// I can see the handlers were called but it doesn't display in the text box
I understand this has restrictions because we don't want web apps to just pretend like they are acting for the user. However, this is for testing my own application and I could launch Firefox with a specific profile and install plugins, or even write my own if I know it will help.
What I am after is to avoid using Selenium, I want to keep Java out of my JS tests because not only is it slow, but I have to re-implement a lot of the DOM querying in Java.
After all this, the question is, does anybody know how to get that code to actually modify the input? Tweaking settings, installing plugins?
List of questions that don't answer my question
Simulating user input for TDD JavaScript
Definitive way to trigger keypress events with jQuery
How to send a key to an input text field using Javascript?
Is it possible to simulate key press events programmatically?
I just found out that the following code does work in Chrome at least. No go in firefox or IE http://jsfiddle.net/D2s5T/14/
function dispatch(target, eventType, char) {
var evt = document.createEvent("TextEvent");
evt.initTextEvent (eventType, true, true, window, char, 0, "en-US");
target.focus();
target.dispatchEvent(evt);
}
dispatch(el, "textInput", "a");

JQuery injecting click()

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

Categories