Pass dynamic value to HTML tag using Javascript function in Java

Hello Stackoverflow community, I have been struggling with below issue for last few days. I have browsed dozens of Stack questions, dev blogs and asked collegues – yet still I am stuck. I am forced to ask a question here. What is the issue?

I am adding several Base64 encoded images to HTML test execution report in Java. I want to open on click them in new tab / popup in full size. Here is code:

String Base64StringofScreenshot = "data:image/png;base64," + Base64.getEncoder().encodeToString(data);

return "<br><a href='' onclick='openImage()'><img src=" + Base64StringofScreenshot
       + " style='height:200px; width:350px; padding:0;'></img></a>"
       + "<script>"
       + "function openImage() {var newTab = window.open(); "
       + "newTab.document.body.innerHTML = "<img src='" + Base64StringofScreenshot
       + "' style='max-height: 100%; max-width: 100%'>";rn"         
       + " return false; }rn"
       + "</script>"; 

I have made some custom formatting here so it may not be perfectly working when copied (missed ” or two “”).

Thing is, that no matter which image I click, the most recent one is opened AND HTML page is reloaded. I think there must be added parameter to JS function which for its every execution sets right img source. Unfortunately this is way beyond my skill to handle JS scripts within Java Strings.

I am kindly asking you for help with right implementation and help me understand what am I doing wrong.

When pressing RMB and selecting “Open image in new window” – right image opens and page does not reload

Answer

If you iterates through images or have several images to return, you can just add onclick trigger to your img tag

String Base64StringofScreenshot = "data:image/png;base64," + Base64.getEncoder().encodeToString(data);

return "</br><img src="" + Base64StringofScreenshot + "" onclick="debugBase64("" + Base64StringofScreenshot + "")">"

and at the end of a page, where you put images, write this script:

<script>
    function debugBase64(base64URL){
        var win = window.open();
        win.document.write('<iframe src="' + base64URL  + '" frameborder="0" style="border:0; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%;" allowfullscreen></iframe>');
    }
</script>

it prevent “Not allowed to navigate top frame to data URL:” error in Chrome browser (It’s Security Update). In other browsers you can use – "onclick="window.open(this.src)"