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!