How can i invoke right/middle mouse click on web browser
I'm try for simulate right click on a link in web browser with javascript and using from this code for simulation right click but all not work!
HtmlElementCollection links = webBrowser1.Document.GetElementsByTagName("A");
foreach (HtmlElement link in links)
object[] args = { link };
HtmlElement script1 = webBrowser1.Document.CreateElement("script");
HtmlElement script2 = webBrowser1.Document.CreateElement("script");
HtmlElement script3 = webBrowser1.Document.CreateElement("script");
HtmlElement script4 = webBrowser1.Document.CreateElement("script");
script1.SetAttribute("rightc1", "function rightc1(thiselements)
{var element = thiselements;var e = element.ownerDocument.createEvent('MouseEvents');
e.initMouseEvent('contextmenu', true, true,element.ownerDocument.defaultView,
1, 0, 0, 0, 0, false,false, false, false,2, null);
return !element.dispatchEvent(e);}");
script2.SetAttribute("rightc2", "function rightc2(thiselements){$('#thiselements').trigger({type: 'mousedown',which: 3});}");
script3.SetAttribute("rightc3", "function rightc3(thiselements){$('#thiselements').trigger({type: 'mouseup',which: 3});}");
script4.SetAttribute("rightc4", "function rightc4(thiselements)
{$('#thiselements').trigger({type: 'mousedown',which: 3}).
trigger({type: 'mouseup',which: 3});}");
link.AppendChild(script1);
webBrowser1.Document.InvokeScript("rightc1", args);
link.AppendChild(script2);
webBrowser1.Document.InvokeScript("rightc2", args);
link.AppendChild(script3);
webBrowser1.Document.InvokeScript("rightc3", args);
link.AppendChild(script4);
webBrowser1.Document.InvokeScript("rightc4", args);
also i know i can simulate left click with these code link.InvokeMember("Click");
but i want right click and i don't know how can i simulate that.
also i dont want to move mouse and simulate click.
Related
I am writing an IT test in selenium to click on a button that appears only when we hover over another button. Attached recording
I have the below function, but for some reason, it is not hovering. The function is wrapped in a java method.
function moveNodeCenter(canvasParent, nodeIndex){
var canvas = go.Diagram.fromDiv(canvasParent);
var nodeDataArray = getAllNodes(canvasParent);
var targetNodeKey = nodeDataArray[nodeIndex].key;
var targetNodeObj = canvas.findNodeForKey(targetNodeKey);
var robot = new Robot(canvas);
robotMove(robot,targetNodeObj.x,targetNodeObj.y);
}
public void moveNodeCenter(int nodeIndex) throws IOException, InterruptedException {
WebElement canvasParent = this.getCanvasParent();
String script = ResourceUtilities.getResource(DESIGNER_SCRIPT_PATH);
script += "\n moveNodeCenter(arguments[0], arguments[1])";
js.executeScript(script, canvasParent, nodeIndex);
}
can someone help? or is there any away i could do this.
i do see mouseMove event here: https://gojs.net/latest/extensions/Robot.js
EDIT #1 with connexo’s solution
Within the following HTML, I want to click in the parent 'li' to play the child 'audio'
The problem is noted in the alert calls within the JS; i.e., trying to compare a HTMLLIElement with a HTMLAudioElement.
How can I successfully do that?
HTML:
I have several:
<li>
text here<br>
<audio controls preload="auto">
<source src="aSong.mp3">
</audio>
</li>
JS:
$('li:has(audio)').on("click", function(evt) {
var m, theSongInArray,
// thisSong = $(this)[0]; // HTMLLIElement
// now a HTMLAudioElement thanks to connexo
$thisLI = $(this);
thisSong = $thisLI.find('audio')[0];
// itsAllSongs defined elsewhere
for (m=0; m < itsAllSongs.length; m++)
{
// HTMLAudioElement
theSongInArray = itsAllSongs[m];
if (thisSong == theSongInArray)
{
if ( thisSong.paused )
thisSong.play();
else
{
thisSong.pause();
thisSong.currentTime = 0;
}
}
}
});
Note: connexo's solution is perfect - but now I have a new problem =
My intent above, which connexo has solved, was to be able to click anywhere within 'li:has(audio)' and have the toggling effect between .play() and .pause() .. and it now does that.
BUT, now the anywhere within 'li:has(audio)' seems to not include the play icon of:
If I click on the slider, the progress bar, the time-stamp, or anywhere else on the long <audio> control it works great, but not on the play icon on the far left of the above control.
SUPER wierd - this 2nd challenge goes away (I can then click just on the play icon) if I remove:
$('li:has(audio)').on("click", function(evt) {
})
Hopefully, connexo has another brilliant solution.
EDIT #2 = solution of the current problem:
Now, I can click on either the li area surrounding the <audio> element, or on just the <audio> element itself. As a matter of interest, when I click on just the play icon of <audio>, the song will play and, if I click on the position slider, the slider will move without playing/pausing the song itself:
/*
alert(evt.target); // = HTMLLIElement, or HTMLAudioElement
*/
if (evt.target.id.length == 0)
thisSong = $(this).find('audio')[0]; // HTMLLIElement -> HTMLAudioElement
else // >= 3, e.g., = "SSB" or "AIRFORCE"
thisSong = $(this)[0]; // [object HTMLAudioElement]
I can't seem to get preventDefault or stopPropagation to work on some types of links. I'd like to write a program to highlight an element on a webpage and save that element as I click it. I'd like to be able to click multiple elements on the page so the program should avoid navigate out of the page. The program fails in some cases. For examples, if I go to https://www.yahoo.com, past the program in the console log and click the ads image, it will open the link. The same happens when I visit https://www.amazon.com and click on the image above "Ad Feedback". It appears it just doesn't work on the ads links.
I tried this program on both firefox and chrome browser. The program works on majority of the links but fails on Ads link. By viewing the HTML source I can't figure out why it fails and how it can be fixed. The program is shown below. Just copy it to run in console.
var highlightDiv = document.createElement('div');
highlightDiv.id = 'testeditor123abc';
document.body.insertBefore(highlightDiv, document.body.firstChild);
var mouseX;
var mouseY;
document.addEventListener('mouseover', processElement, true);
document.addEventListener('click', captureElement, true);
function processElement(e) {
let elem = e.target;
let elemRect = elem.getBoundingClientRect();
highlightDiv.style.top = elemRect.top+'px';
highlightDiv.style.left = elemRect.left+'px';
highlightDiv.style.width = elemRect.width+'px';
highlightDiv.style.height = elemRect.height+'px';
highlightDiv.style.transition = '0.1s';
highlightDiv.style.background = 'rgba(0, 0, 255, 0.2)';
highlightDiv.style.borderColor = 'rgba(255, 0, 0, 0.8)';
highlightDiv.style.borderWidth = '2px';
highlightDiv.style.borderStyle = 'dashed';
highlightDiv.style.position = 'fixed';
highlightDiv.style.zIndex = '999999999999999';
highlightDiv.style.pointerEvents = 'none';
}
function captureElement(e) {
console.log('Mouse X: ', mouseX);
console.log('Mouse Y: ', mouseY);
let element = e.target;
let viewportDimensions = {};
viewportDimensions.height = document.documentElement.clientHeight;
viewportDimensions.width = document.documentElement.clientWidth;
let command = {};
console.log('Element:');
console.log(element);
e.preventDefault();
e.stopPropagation();
}
I hope the program would stop sending me to other page for any element I click on the page. I greatly appreciate any suggestion. Thanks.
I'm writing a Greasemonkey script to automatically delete my notifications from a site, based on words I enter into a search box.
The delete "button" is basically a link, so I'm trying to open the first link in a new tab. Then, after it loads enough, open the rest of the links, one by one, in that same tab.
I figured out how to get the links I needed and how to loop and manipulate them. I was able to grab the first delete-link and open it in a new tab. I added an event listener to make sure the page was loaded before going to the next link.
I finally made that work so added my search box and button. Then I had to figure out how to wrap the whole thing in the event listener again.
So, I now have the whole thing working, except only the last link loads.
All links are going to my waitFor function so they should open, so it seems the event listener isn't working so it goes through the loop too fast and only the last link loads.
How do I make this script not continue the loop until the previous loaded page is fully loaded?
Complete code except for box and button creation:
var mytable = document.getElementById ('content').getElementsByTagName ('table')[0]
var myrows = mytable.rows
//function openLinkInTab () {
//mywin2.close ();
//}
var mywin2;
mywin2 = window.open ("http://www.aywas.com/message/notices/test/", "my_win2");
var links;
var waitFor = function (i) {
links = myrows[i].cells[1].getElementsByTagName ("a");
mywin2 = window.open (links[0].href, "my_win2");
}
var delnotifs = function () {
var matching;
var toRemove;
toRemove = document.getElementById ('find').value;
alert (toRemove)
for (i = 0; i < 10; i++) {
matching = myrows[i].cells[0].innerHTML;
if (matching.indexOf (toRemove) > 0) {
mywin2.addEventListener ('load', waitFor (i), false);
}
}
}
searchButton.addEventListener ('click', delnotifs, true);
So, why isn't it waiting for `mywin2.addEventListener('load', waitFor(i), false);`? I have a feeling it's something extremely simple that I'm missing here, but I just can't see it.
I also tried mywin2.addEventListener('load', function(){waitFor(i)}, false); and it still does the same thing, so it's not a problem of being a call instead of a pointer.
Swapping mywin2.addEventListener('load', waitFor(i), false); for
if (mywin2.document.readyState === "complete") { waitFor(i)} doesn't work either.
And while I'm at it... every time I see code looping through a list like this it uses
for(i=1;i < myrows.length;i++)
Which was skipping the first link in the list since arrays start at zero. So my question is, if I switch 'i' to zero, and the loop only goes while 'i' is < length, doesn't that mean it won't go through the whole list? Shouldn't it be
for(i=0;i != myrows.length;i++)
When you open a popup (or tab) with window.open, the load event only fires once -- even if you "open" a new URL with the same window handle.
To get the load listener to fire every time, you must close the window after each URL, and open a new one for the next URL.
Because popups are asynchronous and you want to load these links sequentially, don't use a for() loop for that. Use the popup load status to "chain" the links.
Here is the code to do that. It pushes the links onto an array, and then uses the load event to grab and open the next link. You can see the code in action at jsFiddle. :
var searchButton = document.getElementById ('gmPopUpBtn');
var mytable = document.getElementById ('content').getElementsByTagName ('table')[0];
var myrows = mytable.rows;
var linksToOpen = [];
var mywin2 = null;
function delnotifs () {
var toRemove = document.getElementById ('find').value;
for (var J = 0, L = myrows.length; J < L; J++) {
var matching = myrows[J].cells[0].innerHTML;
if (matching.indexOf (toRemove) > 0) {
var links = myrows[J].cells[1].getElementsByTagName ("a");
linksToOpen.push (links[0].href); //-- Add URL to list
}
}
openLinksInSequence ();
};
function openLinksInSequence () {
if (mywin2) {
mywin2.close ();
mywin2 = null;
}
if (linksToOpen.length) {
var link = linksToOpen.shift ();
mywin2 = window.open (link, "my_win2");
mywin2.addEventListener ('load', openLinksInSequence, false);
}
}
searchButton.addEventListener ('click', delnotifs, true);
See https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener.
The second argument of the addEventLister function must be a pointer to a function and not a call.
thank you all for helping me previously with my Javascripting problems. My current problem is that I need to open & close a new window on an image's onMouseOver & onMouseOut, respectively, but if the new window onMouseOver == true then I don't want the new window to close.
I am sure there is a simple solution, but I can't seem to figure out a way to cancel the image's onMouseOut="closeDetails();" if the user hovers over the New Window. Below is most of the code I am dealing with. Thanks in advance for your help.
<body>
<img name="img1" id="img1" onMouseOver="windowDelay(this);"
onMouseOut="closeDetails();" src="images/127.jpg" height="240" width="166"/>
</body>
<script language="JavaScript" type="text/javascript">
// This opens the movie details pop-up after an
// half second interval.
function windowDelay(thatImg)
{
winOpenTimer = window.setTimeout(function() {openDetails(thatImg);}, 2000);
}
// This is the function that will open the
// new window when the mouse is moved over the image
function openDetails(thatImg)
{
// This creates a new window and uses the hovered image name as the window
// name so that it can be used in the that window's javascript
newWindow = open("", thatImg.name,"width=400,height=500,left=410,top=210");
// open new document
newWindow.document.open();
// Text of the new document
// Replace your " with ' or \" or your document.write statements will fail
newWindow.document.write("<html><head><title>Movies</title>");
newWindow.document.write("<script src='myDetails.js' type='text/javascript'>");
newWindow.document.write("</script></head>");
newWindow.document.write("<body bgcolor='white' onload='popUpDetails();'>");
newWindow.document.write("... SOME OTHER HTML....");
newWindow.document.write("</body></html>");
// close the document
newWindow.document.close();
}
// This is the function that will call the
// closeWindow() after 2 seconds
// when the mouse is moved off the image.
function closeDetails()
{
winCloseTimer = window.setTimeout("closeWindow();", 2000);
}
// This function closes the pop-up window
// and turns off the Window Timers
function closeWindow()
{
// If popUpHover == true then I do not want
// the window to close
if(popUpHover == false)
{
clearInterval(winOpenTimer);
clearInterval(winCloseTimer);
newWindow.close();
}
}
function popUpDetails()
{
// This will be used to prevent the Details Window from closing
popUpHover = true;
// Below is some other javascript code...
}
</script>
I would recommend against using a new browser window for this task. Try something like this:
var popup = {
open = function () {
if (this.element == null) {
// create new div element to be our popup and store it in the popup object
this.element = document.createElement('div');
this.element.id = "myPopup";
// you don't need a full html document here. Just the stuff you were putting in the <body> tag before
this.element.innerHTML = "<your>html</here>";
// Some bare minimum styles to make this work as a popup. Would be better in a stylesheet
this.element.style = "position: absolute; top: 50px; right: 50px; width: 300px; height: 300px; background-color: #fff;";
}
// Add it to your <body> tag
document.body.appendChild(this.element);
// call whatever setup functions you were calling before
popUpDetails();
},
close = function () {
// get rid of the popup
document.body.removeChild(this.element);
// any other code you want
}
};
// The element you want to trigger the popup
var hoverOverMe = document.getElementById("hoverOverMe");
// set our popup open and close methods to the proper events
hoverOverMe.onmouseover = popup.open;
hoverOverMe.onmouseout = popup.close;
That should do it. It's much easier to control than a new browser window. You will want to tweak the CSS yourself.
EDIT:
Here are instructions to do this with an actual window. To reiterate, using an actual window is not the best way to accomplish this task. A stylized div tag to look like a window is better because it offers more control, as well as standardized functionality across browsers. However, if you must use a window, here it is:
// You can use many principles from the example above, but I'll give the quick version
var popup;
var hoverOverMe = document.getElementById("hoverOverMe");
hoverOverMe.onmouseover = function () {
popup = window.open("path_to_content", "popup");
};
hoverOverMe.onmouseout = function () {
popup.close();
};
It works, but not very well (IMHO). If the user has their settings such that new windows open in new tabs (as I do), then a tab will open up. Javascript has no control over that. In Firefox, the new tab will open and gain focus, at which point it immediately closes because hoverOverMe had its onmouseout event fired (which obviously closes the window). I imagine you'd have this same problem with an actual window, too.