You can create an AJAX request that will be calling the wp_get_attachment_image_srcset on an attachment ID and return the result.
This example uses jQuery from the default "Twenty Seventeen" theme
Inside the child theme functions.php we define the AJAX WP method:
add_action("wp_ajax_get_attachment_image_srcset", "get_attachment_image_srcset");
add_action("wp_ajax_nopriv_get_attachment_image_srcset", "get_attachment_image_srcset");
function get_attachment_image_srcset() {
// Get attachment ID from the request
$attachment_id = $_REQUEST['attachment_id'];
// Get attachment srcset
$srcset = wp_get_attachment_image_srcset($attachment_id);
// Return JSON with the srcset and the attachment_id
wp_send_json([
'srcset' => $srcset,
'attachment_id' => $attachment_id
]);
}
Inside Block Editor, you can add a custom HTML block using AJAX to fetch the attachment srcset using an attachment ID.
Block Editor custom HTML code block:
jQuery(function($) {
// On a button click
$('.get-srcset a').on('click', function() {
// Get the value of a text input to pass as attachment ID
let attachmentId = $('#attachmentid').val();
// Make the AJAX call
jQuery.ajax({
type : "post",
dataType : "json",
url : '/wp-admin/admin-ajax.php',
data : {
action: "get_attachment_image_srcset",
attachment_id : attachmentId
},
success: function(response) {
// If we got an srcset
if(response.srcset) {
// Update the result element text with trhe srcset value or use srcset
$('#result').text(response.srcset);
}
else {
alert("No srcset")
}
}
});
});
});
This will update the #result element text to something like this:
https://wp.lytrax.net/wp-content/uploads/2020/04/3_ser_conv07-300x225.jpg 300w,
https://wp.lytrax.net/wp-content/uploads/2020/04/3_ser_conv07-768x576.jpg 768w,
https://wp.lytrax.net/wp-content/uploads/2020/04/3_ser_conv07.jpg 832w
You can check this working on this demo WP site: https://wp.lytrax.net/test-attachment-srcset/ (Valid attachment IDs are 5, 6, 7, 8, 9, 10)