看了网上的一些博客和教程,还是有点迷糊。
再回头看官方文档https://bitbucket.org/chromiumembedded/cef/wiki/JavaScriptIntegration.md
还自己用例子来验证吧。
Qt工程中的目录结构,VS2017编译器(Qt用的是Qt5.14.2)
这里的文件都和之前的一样,我这里就不再赘述了,我会放到百度云上,大家下载下来看就一目了然了。
simple_app.h
#pragma once
#include "include/cef_app.h"
class SimpleApp
: public CefApp
, public CefBrowserProcessHandler
, public CefRenderProcessHandler
{
public:
SimpleApp(void);
virtual ~SimpleApp() OVERRIDE;
public:
virtual CefRefPtr<CefBrowserProcessHandler> GetBrowserProcessHandler() OVERRIDE;
virtual CefRefPtr<CefRenderProcessHandler> GetRenderProcessHandler() OVERRIDE;
virtual void OnContextCreated(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame,CefRefPtr<CefV8Context> context) OVERRIDE;
protected:
IMPLEMENT_REFCOUNTING(SimpleApp);
};
simple_app.cc
// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#include "simple_app.h"
#include <string>
#include "include/cef_browser.h"
#include "include/cef_command_line.h"
#include "include/views/cef_browser_view.h"
#include "include/views/cef_window.h"
#include "include/wrapper/cef_helpers.h"
#include "simple_handler.h"
SimpleApp::SimpleApp() {
}
SimpleApp::~SimpleApp()
{
}
CefRefPtr<CefBrowserProcessHandler> SimpleApp::GetBrowserProcessHandler()
{
return this;
}
CefRefPtr<CefRenderProcessHandler> SimpleApp::GetRenderProcessHandler()
{
return this;
}
void SimpleApp::OnContextCreated(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Context> context)
{
// The var type can accept all object or variable
CefRefPtr<CefV8Value> window = context->GetGlobal();
// bind value into window[or you can bind value into window sub node]
CefRefPtr<CefV8Value> strValue = CefV8Value::CreateString("say yes");
window->SetValue("say_yes", strValue, V8_PROPERTY_ATTRIBUTE_NONE);
}
simple_handler.h
// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#ifndef CEF_TESTS_CEFSIMPLE_SIMPLE_HANDLER_H_
#define CEF_TESTS_CEFSIMPLE_SIMPLE_HANDLER_H_
#include "include/cef_client.h"
#include <list>
class SimpleHandler : public CefClient,
public CefDisplayHandler,
public CefLifeSpanHandler,
public CefLoadHandler {
public:
explicit SimpleHandler(bool use_views);
~SimpleHandler();
// Provide access to the single global instance of this object.
static SimpleHandler* GetInstance();
// CefClient methods:
virtual CefRefPtr<CefDisplayHandler> GetDisplayHandler() OVERRIDE {
return this;
}
virtual CefRefPtr<CefLifeSpanHandler> GetLifeSpanHandler() OVERRIDE {
return this;
}
virtual CefRefPtr<CefLoadHandler> GetLoadHandler() OVERRIDE {
return this;