Error returning a JS function

Asked

Viewed 46 times

0

I’m trying to store an image with JS and is giving an error in return.

Error message:

VM85:8 Uncaught Syntaxerror: Illegal Return statement

I’m doing it for Selenium with C, follow my code:

IJavaScriptExecutor Lobj_JS = (IJavaScriptExecutor)Navegador;

            var Lstr_TagImgBase64 = Lobj_JS.ExecuteScript($@"
                var canvas = document.createElement('canvas');
                var ctx = canvas.getContext('2d');
                var img = document.evaluate('//html/body/div/div[@id='content']/form/div/div/span/div/div/img', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
                canvas.height=img.height;
                canvas.width=img.width;
                ctx.drawImage(img, 0, 0,img.width, img.height);
                var base64String = canvas.toDataURL();
                return base64String;") as string;

I cannot handle this error, when running in Chrome I obviously replace the single quotes, staying in the console this way:

[@id="content"]

1 answer

1


The Return is illegal because the code you are presenting is not a method or Function that where there should be a return. Your content is available in the variable base64String.

var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var img = document
    .evaluate('//html/body/div/div[@id="content"]/form/div/div/span/div/div/img', 
              document, 
              null, 
              XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
              canvas.height = img.height;
              canvas.width = img.width;
              ctx.drawImage(img, 0, 0, img.width, img.height);

var base64String = canvas.toDataURL();
//return base64String;

If you want this script block to return the value at the end, you need to convert it to a Function and run it right away. However other treatments may be necessary to ensure the loading of the DOM before the execution of its procedure.

IJavaScriptExecutor Lobj_JS = (IJavaScriptExecutor)Navegador;

var Lstr_TagImgBase64 = Lobj_JS.ExecuteScript(@"
    var getBase64String = () => {
        var canvas = document.createElement('canvas');
        var ctx = canvas.getContext('2d');
        var img = document.evaluate('//html/body/div/div[@id=""content""]/form/div/div/span/div/div/img', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
        canvas.height=img.height;
        canvas.width=img.width;
        ctx.drawImage(img, 0, 0,img.width, img.height);
        var base64String = canvas.toDataURL();
        return base64String;
    };
    getBase64String();") as string;
  • Now it makes sense, I don’t have much experience with JS now cleared the mind.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.