简体   繁体   中英

Detect if a tab/download has finished loading in JavaScript

I'm generating a pdf on Grails using the following pattern:

Optional Step: The user will choose either he wants to download the *.pdf or to open it on another tab, the default is to open it to another tab.

Main Step:

  1. Click the Generate Report button.
  2. The button will change its text to Generating Report, please wait...
  3. It will run a block of JavaScript something like this:

     var generate = "<sample url>" // some amazing processing goes here that appends data to the // query string. window.open(generate,'_blank'); 
  4. Then it will open a new tab (or start downloading, depending on the option he had chosen).

    Note: The opened tab is not an ordinary html markup, but rather a *.pdf that is rendered on a browser tab.

  5. The tab (or the download) will load for at least five seconds to 1 minute or so.
  6. The pdf on that tab will finish loading and the user can now navigate the pdf (scroll down, save, print etc); or if it is a download, he can now open that file.
  7. The button on the calling tab will change its text to Report has been generated .

I already generated the reports successfully (both the new tab and the download approach), however my problem is I don't know how to detect if that tab has finished loading , and I cannot do step 7. Can anyone help me how to implement this?

You can use Spring Websocket to send the status of the generation back to the JavaScript, like this

<script type="text/javascript">
    $(function () {
        var socket = new SockJS("${createLink(uri: '/stomp')}");
        var client = Stomp.over(socket);

        client.connect({}, function () {
            client.subscribe("/topic/generatePdf", function (message) {
                console.log(message);
                $("#bnt").value(JSON.parse(message.body));
            });
        });
        $("#bnt").click(function() {
            client.send("/app/generatePdf", {}, JSON.stringify({
                'type': 'foo',
                'id':2
            }));
        });
    });
</script>

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