cef研究

// Copyright (c) 2010 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 "include/cef.h"
#include "include/cef_runnable.h"
#include "include/cef_wrapper.h"
#include "cefclient.h"
#include "client_handler.h"
#include "binding_test.h"
#include "string_util.h"
#include "util.h"
#include <sstream>
#include <stdio.h>
#include <string>

CefRefPtr<ClientHandler> g_handler;

CefRefPtr<CefBrowser> AppGetBrowser()
{
  if(!g_handler.get())
    return NULL;
  return g_handler->GetBrowser();
}

CefWindowHandle AppGetMainHwnd()
{
  if(!g_handler.get())
    return NULL;
  return g_handler->GetMainHwnd();
}

static void ExecuteGetSource(CefRefPtr<CefFrame> frame)
{
  // Retrieve the current page source and display.
  std::string source = frame->GetSource();
  source = StringReplace(source, "<", "&lt;");
  source = StringReplace(source, ">", "&gt;");
  std::stringstream ss;
  ss << "<html><body>Source:" << "<pre>" << source
      << "</pre></body></html>";
  frame->LoadString(ss.str(), "http://tests/getsource");
}

void RunGetSourceTest(CefRefPtr<CefBrowser> browser)
{
  // Execute the GetSource() call on the UI thread.
  CefPostTask(TID_UI,
      NewCefRunnableFunction(&ExecuteGetSource, browser->GetMainFrame()));
}

static void ExecuteGetText(CefRefPtr<CefFrame> frame)
{
  std::string text = frame->GetText();
  text = StringReplace(text, "<", "&lt;");
  text = StringReplace(text, ">", "&gt;");
  std::stringstream ss;
  ss << "<html><body>Text:" << "<pre>" << text
      << "</pre></body></html>";
  frame->LoadString(ss.str(), "http://tests/gettext");
}

void RunGetTextTest(CefRefPtr<CefBrowser> browser)
{
  // Execute the GetText() call on the UI thread.
  CefPostTask(TID_UI,
      NewCefRunnableFunction(&ExecuteGetText, browser->GetMainFrame()));
}

void RunRequestTest(CefRefPtr<CefBrowser> browser)
{
	// Create a new request
  CefRefPtr<CefRequest> request(CefRequest::CreateRequest());

  // Set the request URL
  request->SetURL("http://tests/request");

  // Add post data to the request.  The correct method and content-
  // type headers will be set by CEF.
  CefRefPtr<CefPostDataElement> postDataElement(
      CefPostDataElement::CreatePostDataElement());
  std::string data = "arg1=val1&arg2=val2";
  postDataElement->SetToBytes(data.length(), data.c_str());
  CefRefPtr<CefPostData> postData(CefPostData::CreatePostData());
  postData->AddElement(postDataElement);
  request->SetPostData(postData);

  // Add a custom header
  CefRequest::HeaderMap headerMap;
  headerMap.insert(
      std::make_pair("X-My-Header", "My Header Value"));
  request->SetHeaderMap(headerMap);

  // Load the request
  browser->GetMainFrame()->LoadRequest(request);
}

void RunJavaScriptExecuteTest(CefRefPtr<CefBrowser> browser)
{
  browser->GetMainFrame()->ExecuteJavaScript(
      "alert(‘JavaScript execute works!‘);", "about:blank", 0);
}

void RunPopupTest(CefRefPtr<CefBrowser> browser)
{
  browser->GetMainFrame()->ExecuteJavaScript(
      "window.open(‘http://www.google.com‘);", "about:blank", 0);
}

void RunLocalStorageTest(CefRefPtr<CefBrowser> browser)
{
  browser->GetMainFrame()->LoadURL("http://tests/localstorage");
}

void RunAccelerated2DCanvasTest(CefRefPtr<CefBrowser> browser)
{
  browser->GetMainFrame()->LoadURL(
      "http://mudcu.be/labs/JS1k/BreathingGalaxies.html");
}

void RunAcceleratedLayersTest(CefRefPtr<CefBrowser> browser)
{
  browser->GetMainFrame()->LoadURL(
      "http://webkit.org/blog-files/3d-transforms/poster-circle.html");
}

void RunWebGLTest(CefRefPtr<CefBrowser> browser)
{
  browser->GetMainFrame()->LoadURL(
      "http://webglsamples.googlecode.com/hg/field/field.html");
}

void RunHTML5VideoTest(CefRefPtr<CefBrowser> browser)
{
  browser->GetMainFrame()->LoadURL(
      "http://www.youtube.com/watch?v=siOHh0uzcuY&html5=True");
}

void RunXMLHTTPRequestTest(CefRefPtr<CefBrowser> browser)
{
  browser->GetMainFrame()->LoadURL("http://tests/xmlhttprequest");
}

void RunWebURLRequestTest(CefRefPtr<CefBrowser> browser)
{
  class RequestClient : public CefWebURLRequestClient
  {
  public:
    RequestClient(CefRefPtr<CefBrowser> browser) : browser_(browser) {}

    virtual void OnStateChange(CefRefPtr<CefWebURLRequest> requester,
                               RequestState state)
    {
      REQUIRE_UI_THREAD();
      if (state == WUR_STATE_DONE) {
        buffer_ = StringReplace(buffer_, "<", "&lt;");
        buffer_ = StringReplace(buffer_, ">", "&gt;");
        std::stringstream ss;
        ss << "<html><body>Source:<pre>" << buffer_ << "</pre></body></html>";

        browser_->GetMainFrame()->LoadString(ss.str(),
            "http://tests/weburlrequest");
      }
    }

    virtual void OnRedirect(CefRefPtr<CefWebURLRequest> requester,
                            CefRefPtr<CefRequest> request,
                            CefRefPtr<CefResponse> response)
    {
      REQUIRE_UI_THREAD();
    }

    virtual void OnHeadersReceived(CefRefPtr<CefWebURLRequest> requester,
                                   CefRefPtr<CefResponse> response)
    {
      REQUIRE_UI_THREAD();
    }

    virtual void OnProgress(CefRefPtr<CefWebURLRequest> requester,
                            uint64 bytesSent, uint64 totalBytesToBeSent)
    {
      REQUIRE_UI_THREAD();
    }

    virtual void OnData(CefRefPtr<CefWebURLRequest> requester,
                        const void* data, int dataLength)
    {
      REQUIRE_UI_THREAD();
      buffer_.append(static_cast<const char*>(data), dataLength);
    }

    virtual void OnError(CefRefPtr<CefWebURLRequest> requester,
                         ErrorCode errorCode)
    {
      REQUIRE_UI_THREAD();
      std::stringstream ss;
      ss << "Load failed with error code " << errorCode;
      browser_->GetMainFrame()->LoadString(ss.str(),
          "http://tests/weburlrequest");
    }

  protected:
    CefRefPtr<CefBrowser> browser_;
    std::string buffer_;

    IMPLEMENT_REFCOUNTING(CefWebURLRequestClient);
  };

  CefRefPtr<CefRequest> request(CefRequest::CreateRequest());
  request->SetURL("http://www.google.com");

  CefRefPtr<CefWebURLRequestClient> client(new RequestClient(browser));
  CefRefPtr<CefWebURLRequest> requester(
      CefWebURLRequest::CreateWebURLRequest(request, client));
}

void RunDOMAccessTest(CefRefPtr<CefBrowser> browser)
{
  class Listener : public CefDOMEventListener
  {
  public:
    Listener() {}
    virtual void HandleEvent(CefRefPtr<CefDOMEvent> event)
    {
      CefRefPtr<CefDOMDocument> document = event->GetDocument();
      ASSERT(document.get());

      std::stringstream ss;

      CefRefPtr<CefDOMNode> button = event->GetTarget();
      ASSERT(button.get());
      std::string buttonValue = button->GetElementAttribute("value");
      ss << "You clicked the " << buttonValue.c_str() << " button. ";

      if (document->HasSelection()) {
        std::string startName, endName;

        // Determine the start name by first trying to locate the "id" attribute
        // and then defaulting to the tag name.
        {
          CefRefPtr<CefDOMNode> node = document->GetSelectionStartNode();
          if (!node->IsElement())
            node = node->GetParent();
          if (node->IsElement() && node->HasElementAttribute("id"))
            startName = node->GetElementAttribute("id");
          else
            startName = node->GetName();
        }

        // Determine the end name by first trying to locate the "id" attribute
        // and then defaulting to the tag name.
        {
          CefRefPtr<CefDOMNode> node = document->GetSelectionEndNode();
          if (!node->IsElement())
            node = node->GetParent();
          if (node->IsElement() && node->HasElementAttribute("id"))
            endName = node->GetElementAttribute("id");
          else
            endName = node->GetName();
        }

        ss << "The selection is from " <<
            startName.c_str() << ":" << document->GetSelectionStartOffset() <<
            " to " <<
            endName.c_str() << ":" << document->GetSelectionEndOffset();
      } else {
        ss << "Nothing is selected.";
      }

      // Update the description.
      CefRefPtr<CefDOMNode> desc = document->GetElementById("description");
      ASSERT(desc.get());
      CefRefPtr<CefDOMNode> text = desc->GetFirstChild();
      ASSERT(text.get());
      ASSERT(text->IsText());
      text->SetValue(ss.str());
    }

    IMPLEMENT_REFCOUNTING(Listener);
  };

  class Visitor : public CefDOMVisitor
  {
  public:
    Visitor() {}
    virtual void Visit(CefRefPtr<CefDOMDocument> document)
    {
      // Register an click listener for the button.
      CefRefPtr<CefDOMNode> button = document->GetElementById("button");
      ASSERT(button.get());
      button->AddEventListener("click", new Listener(), false);
    }

    IMPLEMENT_REFCOUNTING(Visitor);
  };

  // The DOM visitor will be called after the path is loaded.
  CefRefPtr<CefClient> client = browser->GetClient();
  static_cast<ClientHandler*>(client.get())->AddDOMVisitor(
      "http://tests/domaccess", new Visitor());

  browser->GetMainFrame()->LoadURL("http://tests/domaccess");
}

void RunDragDropTest(CefRefPtr<CefBrowser> browser)
{
  browser->GetMainFrame()->LoadURL("http://html5demos.com/drag");
}

void RunModalDialogTest(CefRefPtr<CefBrowser> browser)
{
  browser->GetMainFrame()->LoadURL("http://tests/modalmain");
}
时间: 2024-10-10 04:25:48

cef研究的相关文章

qt cef嵌入web

原文http://blog.sina.com.cn/s/blog_9e59cf590102vnfc.html 最近项目需要,研究了下libcef库. Cef(Chromium Embedded Framework)简述 嵌入式Chromium框架(简称CEF) 是一个由Marshall Greenblatt在2008建立的开源项目,它主要目的是开发一个基于Google Chromium的Webbrowser控件.CEF支持一系列的编程语言和操作系统,并且能很容易地整合到新的或已有的工程中去. 它

Chromium与CEF的多进程模型及相关参数

CEF基于Chromium,也是多进程模型.关于进程模型,参考这里:https://www.chromium.org/developers/design-documents/process-models.我还看到一篇韩国人写的renderer process的文章,也很不错,在这里:http://chromium-kr.blogspot.com/2012/06/about-renderer-process.html. CEF的进程模型,这里也有一部分描述:https://bitbucket.or

CEF Windows开发环境搭建

CEF,Chromium Embedded Framework的缩写.CEF 的官网介绍的很简洁:A simple framework for embedding chromium browser windows in other applications.具体地说就是一个可以将浏览器功能(页面渲染,JS 执行)嵌入到其他应用程序的框架.感兴趣的看这里:https://bitbucket.org/chromiumembedded/cef. 用CEF的好处是开发Web和Native混合的应用非常方

Duilib嵌入CEF禁止浏览器响应拖拽事件

在开发中有一个需求,拖拽外部文件到客户端,然后客户端响应WM_DROPFILES消息,在拖拽消息里处理一下业务,最后把处理结果显示到客户区html中,但实际中发现当拖拽文件到客户区,浏览器首先处理了拖拽事件,外层的Win32窗口无法捕捉到拖拽消息,因此要想实现此操作,刚开始我想了一个本办法,在客户区最外层罩了一个透明的Win32原生窗口,这样拖拽文件时,在最外层透明窗口的WM_DROPFILES消息中处理具体业务,最后用C++调用js函数,在页面显示处理结果. 方法一: 透明窗口 Layered

从今天起,记录CEF使用开发心得经验

已经使用CEF来呈现桌面程序界面大半年了,从来没有写过相关博文.发现网上的中文资料甚至英文已经无法满足我的开发需求,不少问题只得自己探索.在此先谢过网络上各位CEF使用开发博文的贡献者,没有你们我也难易快速入手.实在惭愧,由于精力有限,自己捣鼓出来的东西一直没有贡献出来.好吧,从今天开始,面朝大海,春暖花开. 原先公司的C++程序界面用GDI+来做,甚是麻烦.后来客户想要类似豌豆荚那样的风格,小清新.研究了下豌豆荚,发现它的界面八成是JavaScript,用CEF来嵌入Web页面.此前也听一朋友

Google帝国研究——Google的产业构成

                                                                                    Google帝国研究--Google的产业构成 摘要:Google帝国研究  产业构成 作者:魏春颖 文章来源:网络整理 Google产业的构成: 1.    业务板块: 包括互联网搜索.云计算.广告技术,开发并提供大量基于互联网的产品与服务,开发线上软件.应用软件,还涉及移动设备的Android操作系统以及操作系统谷歌Chrom

今天研究了一下手机通信录管理系统(C语言)

题目:手机通信录管理系统 一.题目要求 二.需求分析 三.设计步骤/编写代码 四.上机/运行结果 五.总结 一.题目要求 模拟手机通信录管理系统,实现对手机中的通信录进行管理操作.功能要求: (1)查看功能:A:办公,B:个人,C:商务 (2)增加联系人:录入新数据(姓名,电话,分类,邮箱:weiyang,153********,个人,[email protected]) (3)修改功能:选中某人的姓名,可对其数据进行修改操作 (4)删除功能:选中某人姓名,可对此人的相应数据进行删除,并自动调整

tablib.Dataset()操作exl类型数据之“类方法”研究

#tablib.Dataset()操作exl类型数据之“类方法”研究 import tablib #初始化 data=tablib.Dataset() #设置列标题 data.headers=('name','where') some_collector=[('xiaodeng','enshi'),('xiaoming','hubei'),('xiaodong','enshi')] #写入数据 for key,value in some_collector: data.append((key,v

.NET4.5中WCF中默认生成的basicHttpsBinding的研究

起因: 使用.net4.5建立了一个空白的WCF服务.默认使用的绑定配置是basicHttpsBinding. 问题发现: 1.用客户端进行服务引用,生成了默认的配置文件,其中绑定配置是basicHttpBinding. 2.因为需要单次传递大批量数据,所以修改绑定配置,如下: <basicHttpBinding> <binding name="BasicHttpBinding_IService" closeTimeout="00:10:00" r