Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

533
Views
CEF - how to call callback c++ form JS-code

How can I call a C++ function using JavaScript?

For example, I am executing js code in a browser window using the method CefFrame::ExecuteJavaScript like this:

(*frame).GetMainFrame()).ExecuteJavaScript("const elem = document.getElementsByClassName("my_class")[0];const rect = elem.getBoundingClientRect(); alert(rect.x + \":\" + rect.y)", "", 1);

Is it possible to somehow call a C++ function for the place of the JS alert() function?

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

It can be done in two ways. They are almost equal: you can create several native functions at once with CefRegisterExtension, and you can create a single native function with CefV8Value::CreateFunction. The example bellow is just a sketch, nowhere can test it, small issues are possible, but the idea is clear:

class MyAlertHandler : public CefV8Handler {
 public:
  bool Execute(const CefString& name,
               CefRefPtr<CefV8Value> object,
               const CefV8ValueList& arguments,
               CefRefPtr<CefV8Value>& retval,
               CefString& exception) override {
    if (!arguments.empty()) {
      // arguments[0]->GetStringValue();
    }
    return true;
  }
};

CefRefPtr<CefV8Handler> handler = new MyAlertHandler;

CefRefPtr<CefV8Context> v8_context = frame->GetMainFrame()->GetV8Context();
if (v8_context.get() && v8_context->Enter()) {
  CefRefPtr<CefV8Value> global = v8_context->GetGlobal();
  CefRefPtr<CefV8Value> my_alert = CefV8Value::CreateFunction("my_alert", handler);
  global->SetValue("my_alert", my_alert, V8_PROPERTY_ATTRIBUTE_READONLY);
  v8_context->Exit();
}

Calling Enter() and Exit() on a V8 context can be omitted if CefV8Value::CreateFunction is called from CefRenderProcessHandler functions.

frame->GetMainFrame()->ExecuteJavaScript(R"(
  const elem = document.getElementsByClassName("my_class")[0];
  const rect = elem.getBoundingClientRect();
  my_alert(rect.x + ":" + rect.y);)", "", 1);
about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!