Search code examples
javascriptc#htmlwinformscefsharp

Using CEFSharp to edit <textarea>


I am able to edit a regular textbox within an iFrame in CefSharp like so:

Browser1.GetBrowser().GetFrame("iFrame1").ExecuteJavaScriptAsync("document.getElementById('ElementID').value=" + '\'' + "1234" + '\'');

However, because a textarea doesn't have a value:

<iframe id="iFrame1" name="iFrame1">
    <textarea name="txtareaname" id="txtareaname1">sometexthere</textarea>
</iframe>

I am unable to execute a similar line of code to edit the text in the textarea:

textarea.Browser1.GetBrowser().GetFrame("iFrame1").ExecuteJavaScriptAsync("document.getElementById('txtareaname1').value=" + '\'' + "1234" + '\'');

I have also tried:

textarea.Browser1.GetBrowser().GetFrame("iFrame1").ExecuteJavaScriptAsync("document.getElementById('txtareaname1').innertext=" + '\'' + "1234" + '\'');

How do I adjust my code to edit this textarea?


Solution

  • OP: However, because a textarea doesn't have a value I am unable to execute a similar line of code to edit the text in the textarea.

    The assumption is wrong, setting value attribute works fine for teaxtarea.

    You should just make sure the document, including the iframe has been loaded and you have selected the correct iframe using correct name and then you have selected the correct textarea using correct id.

    Example

    Here is a minimal complete verifiable example which shows how you can find the iframe and set the value of a textarea inside the iframe.

    To make the example independent from externals sources and make verification easier, instead of initializing iframe using its src attribute, I've initialized iframe using script.

    protected override void OnLoad(EventArgs e) {
        base.OnLoad(e);
        var content = new HtmlString(@"
        <!DOCTYPE html>
        <html>
        <body>
        <iframe id=""iFrame1"" name=""iFrame1"" src=""about:blank""></iframe>
        <script>
            var doc = document.getElementById('iFrame1').contentWindow.document;
            doc.open();
            doc.write('<html><head><title></title></head><body>' + 
            'Address:<br>' +
            '<textarea id=""myTextarea"">342 Alvin RoadDucksburg</textarea>' +
            '</body></html>');
            doc.close();
        </script>
        </body>
        </html>
        ");
        var browser = new ChromiumWebBrowser(content)
        { Dock = DockStyle.None, Size = new Size(400, 200), Location = new Point(8, 42) };
        Controls.Add(browser);
    
        var button = new Button() { Text = "Click Me", Location = new Point(8, 8) };
        Controls.Add(button);
        button.Click += (obj, args) => {
            browser.GetBrowser().GetFrame("iFrame1")
                .ExecuteJavaScriptAsync("document.getElementById('myTextarea').value=" +
                "'Fifth Avenue, New York City'");
        };
    }