Request: Provide a Way Test for Existence of a Link or XPath in a Web Page

Recently, I really enjoyed playing with this action :point_right: actions:Browser Form Actions [Keyboard Maestro Wiki]. But it seems that there’s no way for me to verify if a link / button exist in the front browser. What a pity.

I agree that would be a handy KM enhancement.

Meanwhile, you can easily do this with a JavaScript in Browser with just a few lines of script. For example:


'use strict';
(function run() {      // this will auto-run when script is executed
var xPath = document.kmvar.DLE__XPath
var nodes = document.evaluate(xPath, document, null, XPathResult.ANY_TYPE, null)
var result = nodes.iterateNext();

var statusStr = (result) ? "[FOUND]" : "[NOT-FOUND]"

return statusStr;

}  // END of function run()
)();

To use this, you need to first have set the KM Variable "DLE__XPath" in a prior action:

image

You can test this particular XPath on this page:
https://forum.keyboardmaestro.com/latest

2 Likes

@Alice_Shi, I hope you don’t mind that I have revised your topic title to better reflect the question you have asked.

FROM:
It seems that there’s no way to test if a link exist in the web page

TO:
Request: Provide a Way Test for Existence of a Link or XPath in a Web Page

This will greatly help you attract more experienced users to help solve your problem, and will help future readers find your question, and the solution.

Request noted.

Thank you! I made something similar with Document.getElementById() to check if a specific field exists. But it’s better and more efficient with XPath…

Thanks.

If both XPath and document.get are using the element id, I’d think there would not be much difference in performance.

But where XPath really comes into play is when you have to search for something using other than the element id. XPath is a very complex tool, having many, many options and methods of configuring it.

So the point of my point was to demonstrate how to XPath in general, whether or not you have an id.

This is exactly what I mean :wink:

@JMichaelTX Thank you sooo much! Before this I gotta use a bunch of pictures as conditions to verify if a link/button exists, and it has to consider the zoom of webpage first. Now it’s so much efficient!

1 Like

For the next version, I have added a JavaScript in Front Browser variant to the Script Condition to allow this sort of thing to be done directly in a condition. For example:

4 Likes

Many thanks for this, Peter. Having a Pause Until with a JavaScript condition will be very helpful/valuable. :+1:

1 Like