简体   繁体   中英

Laravel Dusk - execute javascript script and wait for promise to be resolved to return the value

I want to run a script that will wait for the promise to return the value.

$dusk->script('return //something');

The javascript function I want to run is a promise.

fetch(url).then(r => r.blob()).then(blob => {
    var reader = new FileReader();
    reader.onload = function() {
        var b64 = reader.result.replace(/^data:.+;base64,/, '');
        console.log(b64); // I want to return this value
    };
    reader.readAsDataURL(blob);
});

I want to return the b64 variable, but this won't happen.

$b64 = $dusk->script("
    var b64;

    fetch(url).then(r => r.blob()).then(blob => {
        var reader = new FileReader();
        reader.onload = function() {
            b64 = reader.result.replace(/^data:.+;base64,/, ''); 
        };
        reader.readAsDataURL(blob);
    });        

    // When `b64` is ready, I want to return it
    return b64;
");

This is one possibility. I would assume it works with dusk/selenium as well. The clue is that the onload function is basically a callback, so we want to use that callback to resolve the promise. If you want sync-looking code, async/await could do that for you as well, but the end result is the same, a promise gets returned so you can continue the promise chain.

fetch(url)
    .then(r => r.blob())
    .then(blob => new Promise(( resolve ) => {
        var reader = new FileReader();
        reader.onload = function() {
            var b64 = reader.result.replace(/^data:.+;base64,/, '');
            resolve( b64 );
        };
        reader.readAsDataURL(blob);
    })
    .then( b64 => {
        // do something with b64
    });

This does imply that you can't return it to the outer $b64 = though.

Edit: So instead of

$b64 = fetch(url)
  .then( response => ... )
  .then( blob => ... )
  .then( image => ... );
renderImage( $b64 );

You would want to do

fetch(url)
  .then( response => ... )
  .then( blob => ... )
  .then( image => ... )
  .then( renderImage );

Or:

var $b64 = fetch(url)
  .then( response => ... )
  .then( blob => ... )
  .then( image => ... );
$b64.then( renderImage );

Edit 2:

Do not wait for the actual Promise, wait for the result of the promise to show up on the screen, so as per the dusk docs, you give the promise 5 seconds to resolve before dusk throws an error.

If the Promise would render the result on the page, try detecting a change in the image tag the image will be rendered to.

$dusk->script("
    fetch(url).then(r => r.blob()).then(blob => {
        var reader = new FileReader();
        reader.onload = function() {
            var b64 = reader.result.replace(/^data:.+;base64,/, '');
            document.querySelector( 'body' ).classList.add( 'loaded_image' );
        };
        reader.readAsDataURL(blob);
    });        
");

$dusk->waitUntil('body.loaded_image');

Solution:

$dusk->script('
     var url = document.getElementById("img_file").getAttribute("src");

     fetch(url)
         .then(r => r.blob())
         .then(blob => new Promise(( resolve ) => {
             var reader = new FileReader();
             reader.onload = function() {
                 var b64 = reader.result.replace(/^data:.+;base64,/, "");
                 resolve( b64 );
             };
             reader.readAsDataURL(blob);
         }))
        .then( b64 => {
            $("body").append(`<input id="b64string" value="${b64}">`);
         });
');

// wait until ajax to be finished
$dusk->waitUntil("!$.active", 30);

$b64Img = $dusk->script("return document.getElementById('b64string').value;"); // this returns array

dd($b64Img[0]); // works!

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