简体   繁体   中英

Call function after page was loaded in new tab

After clicking on the button i need to open some link in new tab, and than after the page would be loaded, I need to programmatically perform some actions on this page (like clicking on proper GUI elements etc).

For example this code should open in new tab http://stackoverflow.com and after that click on "Tags":

<button type=\"button\"
    onclick="window.open('http://stackoverflow.com', '_blank');
    document.getElementById('nav-tags').click();">Click Me!
</button>

but the function document.getElementById('nav-tags').click() does not call.

As I said in comment, there is no way to directly communicate between tabs/windows.

There are way around this however:

  1. when opening another tab, send data you need in url (like i suggested in comments stackoveflow.com/tags)
  2. communicate using cookies ( https://stackoverflow.com/a/4079423/3600886 )
  3. communicate using local storage ( http://dev.w3.org/html5/webstorage/ ) - there is a library for that: https://github.com/diy/intercom.js/

If your usage is to just show some data upon page load, I'd say go with first option, it will work across all browsers, free of any other restrictions.

With other options you will need pages to be on same domain or have same parent window, plus local storage is not supported by older browsers.

Create the tab from JavaScript and you can access the tab with JavaScript and place a onload function

var w = window.open();
w.onload = function(){

};

You can also put the onload function in the tab:

window.onload = function(){
}

You need to write your JS in .ready event. So it will be called when whole page DOM is ready:

$(document).ready(function () {
      document.getElementById('nav-tags').click();
});

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