1

I am writing a javascript script from which I am detecting user activities in current site. So in that site user can click on box which throws them to new tab with a link . that link is dynamic.

i need to record that link in my DB which is opened in new tab,Also i don't know whether it opened from clicking on or any other function..in my case a function is called on click of button then new tab is opened with link i.e window.open(data.link) is called on the function click

Is there any way to call a function whenever a new tabs open from current page?

Update

below answer did help me for tracking links with target _blank but it didnt work when target is not present. Also, in my case as i've deccribed that tab is opening from functions too so i solve it by overiding window.open function i.e

    window.open = function(url, name, features, replace) {
    alert("opening a window");
    // do other stuff here}

this event is called whenever new tab is opened from window.open function!!

Hope it helps other too!

  • 1
    Please refer this link https://stackoverflow.com/questions/20087368/how-to-detect-if-user-it-trying-to-open-a-link-in-a-new-tab – Abdul Hoque Nuri Jan 04 '19 at 13:43
  • 2
    Possible duplicate of [How to detect if user it trying to open a link in a new tab?](https://stackoverflow.com/questions/20087368/how-to-detect-if-user-it-trying-to-open-a-link-in-a-new-tab) – Ludovit Mydla Jan 04 '19 at 13:53
  • 1
    i disagree for duplication link..as in my case i want to detect pure windows new tab functionality not need to track @LudovitMydla –  Jan 05 '19 at 06:06

1 Answers1

2

Use JavaScript to add an EventListener to all a elements.

If the element has target="_blank", or a shortcut key such as ctrl is pressed, you can safely assume that the link clicked is going to open in a new tab/window.

event.target.href is the URL you need to add to your database using AJAX.

// loop all `a` elements, adding click event listeners
document.querySelectorAll("a").forEach(element => {
  element.addEventListener("click", event => {

    // is `target="_blank"`
    const isTargetBlank = event.target.target === "_blank";

    // is shortcut key held
    const isShortcutKeyPressed = event.ctrlKey || event.shiftKey || event.metaKey;

    // If target is blank or shortcut key pressed or middle mouse button pressed
    if (isTargetBlank || isShortcutKeyPressed) {
      alert(`Opened in new tab: ${event.target.href}`);

      // ...
      // Save `event.target.href` URL using AJAX
    }
  });
});
<a href="https://www.stackoverflow.com">Same Tab</a>
<a target="_blank" href="https://www.google.com">New Tab</a>
Gary Thomas
  • 2,291
  • 1
  • 9
  • 21
  • hi gary thanks for your response..i have edited my question please check it –  Jan 05 '19 at 04:50