user3364652
user3364652

Reputation: 510

How to get the URL of an image inside a canvas element with Selenium in Java, and how to use JavascriptExecutor?

My specific goal is to get the image URL from a canvas container, here is what is did:

JavascriptExecutor jse = (JavascriptExecutor) driver;

Object imageURL = jse.executeScript("arguments[0].toDataURL('image/png');",canvas);

I'm getting a return value of null.

Then I've tried to do something more basic, like getting the width attribute of the canvas.

JavascriptExecutor jse = (JavascriptExecutor) driver;
Object width= jse.executeScript("arguments[0].getAttribute('width');",canvas);

Again I'm getting null. The canvas WebElement is well identified by Selenium and it's "width" attribute is exists - I can retrieve it with WebDriver's getAttribute method.

I guess I'm using it wrong.

Thanks for the help!

Upvotes: 1

Views: 2477

Answers (3)

Razor
Razor

Reputation: 457

JavascriptExecutor jse = (JavascriptExecutor) driver;
Object imageURL = jse.executeScript("return arguments[0].toDataURL('image/png').substring(22);",canvas);

With this code you get the string of base64 Image

Upvotes: 0

JeffC
JeffC

Reputation: 25596

For your original code, you just need to add return to get a value back. You can also cast the Object return as string, if you want.

String imageURL = (String) jse.executeScript("return arguments[0].toDataURL('image/png');", canvas);
System.out.println(imageURL);

For the width portion, you don't even need JSE.

WebElement canvas = driver.findElement(...);
System.out.println(canvas.getAttribute("width"));

Upvotes: 3

Incepter
Incepter

Reputation: 2958

Add return keyword to your script.

PS: let me know if it's resolved, else we can try something else.

Upvotes: 4

Related Questions