Ad

Javascript - How To Click Any Link And Show Link Name In Alert Box

- 1 answer

I am kind of not pro in JavaScript Code. I want to do simple thing in plain JavaScript site.

Let's say any website on Internet, and whenever you click on any link in the page, automatically link name should be shown in an alert box.

It can be any link on loaded page. Can Someone help me with this logic which I can run on any site in my Browser console.

Thanks in advance.

Ad

Answer

Here is Madhan M's answer in pure JS:

var allAnchors = document.getElementsByTagName("a");

for (i=0; i < allAnchors.length; i++) {
    var element = allAnchors[i];
    element.addEventListener("click", function (event) {
    event.preventDefault();

    let ref = this.getAttribute("href");
    alert(ref);
  }.bind(element));
}

Please consider that "bind" is supported by newer browser, but not older ones.

An additional note: It is not allowed to run javascript on "any site in the internet". You can get the functionality that your asking with browser extensions, but that is kind of another question.

Ad
source: stackoverflow.com
Ad