3

Following to my question at this thread, now I'm stuck with a problem on how to simulate typing in a contenteditable div.

The div tag is like below:

<div tabindex="-1" class="input-emoji">
    <div class="input-placeholder" style="visibility: visible;">Type a message</div>
    <div class="input" contenteditable="true" data-tab="1" dir="auto" spellcheck="true"></div>
</div>

And in order to simulate typing, my code in js is like below:

setTimeout(() => {
    try {
        let inputContainerEl = chatPanelEl[0].getElementsByClassName('input-container');
        let input = inputContainerEl[0].getElementsByClassName('input');

        let message = 'Something to type';
        console.log('MESSAGE: ' + message);
        let chars = message.split('');
        for (let n = 0; n < chars.length; n++) {
            let charCode = chars[n].charCodeAt(0);
            console.log('CHAR: ' + chars[n] + ' => CODE: ' + charCode);

            let keypressEvent = document.createEvent('KeyboardEvent');
            keypressEvent.initKeyboardEvent('keypress', true, true, window, false, false, false, false, charCode, charCode);
            input[0].dispatchEvent(keypressEvent);

            let keydownEvent = document.createEvent('KeyboardEvent');
            keydownEvent.initKeyboardEvent('keydown', true, true, window, false, false, false, false, charCode, charCode);
            input[0].dispatchEvent(keydownEvent);

            let keyupEvent = document.createEvent('KeyboardEvent');
            keyupEvent.initKeyboardEvent('keyup', true, true, window, false, false, false, false, charCode, charCode);
            input[0].dispatchEvent(keyupEvent);
        }
    } catch(err) {
        console.log('ERROR: ' + err);
    }
}, 1000);

I checked some threads here already, regarding performing keydown, keypress and keyup events from vanilla javascript. But nothing seems to works.

I tried using selenium based solution and it works like charm (read the code below)

public void run() {
    try {
        WebElement container = driver.findElement(By.className("input-container"));
        if (container != null) {
            WebElement input = container.findElement(By.className("input"));
            if (input != null) {
                input.sendKeys("ECHO: " + this.echo);
                Thread.sleep(2000);
                WebElement submitBtn = driver.findElement(By.className("compose-btn-send"));
                if (submitBtn != null) {
                    submitBtn.click();
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

But since I'm not able to use selenium (due to project's requirement), I'm forced to use Cefsharp instead.

So if anybody knows on how to perform selenium "sendKeys" method in vanilla javascript, please help me.

Thanks.

Kunto Fullstack
  • 405
  • 6
  • 16
  • Do you just want to get/set the contents of the `contenteditable` `div`? Something like `document.getElementById("input").innerHTML` or `document.getElementById("input").textContent` will do that. Both of these examples are properties that you can also assign to. Or must it be key events? – TEK Aug 26 '17 at 16:35
  • Yes ... but I need to trigger keypress so the button for submission could appears ... its a whatsapp web by the way, and I can't just use innerText or append text .... you need to simulate typing... – Kunto Fullstack Aug 26 '17 at 21:06

3 Answers3

4

This solution works for me:

element.dispatchEvent(new InputEvent('textInput', {data: keyChar, bubbles: true}));

where element is contenteditable div and keyChar is of course key character ;)

pawelbylina
  • 1,387
  • 10
  • 17
0

I have a java code as below which can perfrom sendKeys using JavascriptExecutor :-

System.setProperty("webdriver.chrome.driver","E:\\Selenium\\Workplace\\Selenium\\src\\libs\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.co.in/");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
WebElement dd= driver.findElement(By.xpath("//input[@id='lst-ib' and @name='q']"));
JavascriptExecutor rightexecutor = (JavascriptExecutor)driver;
rightexecutor.executeScript("arguments[0].setAttribute('value','yahoo')", dd);

Replace your locator(i.e. xpath) in above JavascriptExecutor code and convert it into your javascript.

OR

I have found a solution

private void OnIsBrowserInitializedChanged(object sender,

IsBrowserInitializedChangedEventArgs args)
{
    if(args.IsBrowserInitialized)
    {
        browser.ExecuteScriptAsync("alert('test');");
    }
}

Source :-

cefsharp execute javascript

check this out. It having many method :-

https://github.com/cefsharp/CefSharp/wiki/Frequently-asked-questions

Hope it will help you :)

Shubham Jain
  • 16,610
  • 15
  • 78
  • 125
0

I was able to get good results by doing

input [0]. textContent = "my text";
dougalg
  • 529
  • 4
  • 14