简体   繁体   中英

How to trigger click event in new browser tab

I opened a new browser tab using below code, In the new browser tab I have <span class="refresh-table-data"></span> element which work as a button and clicking on it trigger ajax which updates table with latest data, Now when I change the focus back to this tab I want to trigger click on that tab so that table data gets updated via ajax but it is not working.

    var newWin = window.open(url, '_blank');

    newWin.addEventListener('focus', function() {
      var refreshBtnList = newWin.document.getElementsByClassName('refresh-table-data');
      for (var idx=0; idx < refreshBtnList.length; idx++) {
        refreshBtnList[idx].click(); // Here I'm getting span element properly but click is not getting trigger by this code
      }
    });

I can see the element in the developer tools window as below.

在此处输入图片说明

Please suggest what I'm missing here?

Call trigger click everytime when window has focus, something like this ( to test it, just click outside of snippet and again on snippet container ).

PS: also you can try to play with document.hasFocus()

 $(document).ready(function(){ var window_focus; $(window).focus(function() { window_focus = true; $('button').trigger("click"); }).blur(function() { window_focus = false; }); $('button').click(function() { // call ajax here: $('body').append('has focus<br/>'); }); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> Click here to begin<br> <button> sdf </button> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM