0

I'm using CefSharp to build a web browser and I'm integrating some javascript on button click, etc.

I am trying to get the element by class name and then save its text to the clipboard.

It successfully finds an element and the text, but I can't set it to the clipboard no matter what.

Here is the code

private void button3_Click(object sender, EventArgs e)
    {
        CurBrowser.GetMainFrame().ExecuteJavaScriptAsync("var elems1 = document.getElementsByClassName('question-text')");
        CurBrowser.GetMainFrame().ExecuteJavaScriptAsync("textt = elems1[elems1.length - 1].innerText");
        CurBrowser.GetMainFrame().ExecuteJavaScriptAsync("navigator.clipboard.writeText(textt);");
}

It says that the document is not focused, but I tried to focus it using

textt.focus();

or

elems1.focus():

it returns "textt.focus(); is not a function" or "elems1.focus(): is not a function"

Renato Lulic
  • 200
  • 2
  • 18
  • Does this answer your question? [How do I copy to the clipboard in JavaScript?](https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript) – evolutionxbox Oct 23 '20 at 00:42
  • Unfortunately, no, they are using "function copyToClipboard(text)" etc, But I need it inside "CurBrowser.GetMainFrame().ExecuteJavaScriptAsync" – Renato Lulic Oct 23 '20 at 00:43
  • Is that impossible? `CurBrowser.GetMainFrame().ExecuteJavaScriptAsync("function copyToClipboard(text) { ... function content here ... }")` – evolutionxbox Oct 23 '20 at 00:45
  • Can you write it for my code if it's possible? I don't know how to do that – Renato Lulic Oct 23 '20 at 01:00
  • Why can't you get text and set it to clipboard? Why do you need such a convoluted JavaScript solution for it? (assuming post is not marked C# by mistake) – Alexei Levenkov Oct 23 '20 at 01:50

1 Answers1

1

Try running everything in on

CurBrowser.GetMainFrame().ExecuteJavaScriptAsync("const element = document.createElement('textarea'); element.value = document.getElementsByClassName('question-text')[0].innerText; document.body.appendChild(element); element.select(); document.execCommand('copy'); document.body.removeChild(element);");

If it still doesn't say its in focus, try adding the focus within that too.