/*
* CEF JS调用C#组装类
*
* 使用方法(CefGlue为例):
* public class BrowserRenderProcessHandler : CefRenderProcessHandler
{
* //自定义Handler
private TestBrowserHandler _testHandler = null;
*
* protected override void OnWebKitInitialized()
* {
* _testHandler = new TestBrowserHandler();
* CefRuntime.RegisterExtension(_testHandler.GetType().Name, _testHandler.Javascript.Create(), _testHandler);
* }
* }
*
* /// <summary>
/// 测试Handler
/// </summary>
public class TestBrowserHandler : CefV8Handler
{
public GenerateJavascriptFull Javascript = null;
*
* public TestBrowserHandler()
{
Javascript = new GenerateJavascriptFull("plugins", "test");
* // getHello的参数数量,可进一步封装。表示接受一个参数
Javascript.AddMethod("gethello", "arg0");
* // getHello的参数数量,可进一步封装。表示接受二个参数
Javascript.AddMethod("sethello", "arg0","arg1");
* //表示无参
* Javascript.AddMethod("sethello");
Javascript.AddGetProperty("hello", "gethello");
Javascript.AddSetProperty("hello", "sethello", "arg0");
Javascript.AddMethod("start", "arg0");
Javascript.AddMethod("stop");
*
* //这里表示浏览器JS增加了: window.plugins.test 对象
* // window.plugins.test.gethello()
* // window.plugins.test.sethello("123")
* //断点在 Execute(**)中
}
*
* protected override bool Execute(string name, CefV8Value obj, CefV8Value[] arguments, out CefV8Value returnValue, out string exception)
{
try
{
returnValue = CefV8Value.CreateNull();
switch (name)
{
case "gethello":
//returnValue = CefV8Value.CreateString(GetHello());
if (arguments.Length == 1 && arguments[0].IsFunction)
{
CefV8Value[] args = new CefV8Value[1];
args[0] = CefV8Value.CreateString(GetHello());
returnValue = arguments[0].ExecuteFunction(null, args);
}
break;
case "sethello":
returnValue = CefV8Value.CreateBool(SetHello(arguments[0].GetStringValue()));
break; case "start":
if (arguments.Length == 1 && arguments[0].IsFunction)
{ CefV8Context context = CefV8Context.GetCurrentContext();
//这里定义异步调用方式
new Thread(new ThreadStart(delegate()
{
while (isStart)
{
System.Threading.Thread.Sleep(1000);
string timer = DateTime.Now.ToString();
* //TestTimerTask继承CefTask
CefRuntime.PostTask(CefThreadId.Renderer, new TestTimerTask(context as CefV8Context, arguments[0], new object[] { timer }));
}
})).Start();
returnValue = CefV8Value.CreateBool(true);
}
break;
case "stop":
isStart = false;
returnValue = CefV8Value.CreateBool(true);
break;
} exception = null;
return true;
}
catch (Exception e)
{
returnValue = null;
exception = e.Message;
return false;
}
}
* }
*
*
*
*
*
*/ using System;
using System.Collections.Generic;
using System.Text; namespace G.DeskCommon
{
/// <summary>
/// 组装JS
/// </summary>
public class GenerateJavascriptFull
{
string _extensionName = string.Empty;
string _functionName = string.Empty;
Dictionary<string, string[]> _methodName = new Dictionary<string, string[]>(); //
Dictionary<string, string> _getterPropertyName = new Dictionary<string, string>(); // 保存setter 名称 和参数。 与 _setterPropertyArgs 成对出现。
Dictionary<string, string> _setterPropertyName = new Dictionary<string, string>();
Dictionary<string, string[]> _setterPropertyArgs = new Dictionary<string, string[]>(); //自定义javascript代码
List<string> _customJavascript = new List<string>(); /// <summary>
///
/// </summary>
/// <param name="extensionName">
/// 插件方法作用域
/// e.g: window.plugin.test
/// 其中 plugin 为作用域. 如不设置,添加的js方法在window下.
/// </param>
/// <param name="functionName">
///
/// </param>
public GenerateJavascriptFull(string extensionName, string functionName)
{
_extensionName = extensionName;
_functionName = functionName;
} /// <summary>
/// 增加方法
/// </summary>
/// <param name="methodName">方法名称</param>
/// <param name="args">参数名:arg0,arg1,...arg20 (固定写死)</param>
public void AddMethod(string methodName, params string[] args)
{
//检测是否存在改方法
if (_methodName.ContainsKey(methodName))
return;
_methodName.Add(methodName, args);
} /// <summary>
/// 增加Getter属性
/// </summary>
/// <param name="propertyName">属性名称</param>
/// <param name="executeName">执行名称,CEF handler中execute的Name参数同名</param>
public void AddGetProperty(string propertyName, string executeName)
{
if (_getterPropertyName.ContainsKey(propertyName))
return; _getterPropertyName.Add(propertyName, executeName);
} /// <summary>
/// 增加Setter属性
/// </summary>
/// <param name="propertyName">属性名称</param>
/// <param name="executeName">执行名称,CEF handler中execute的Name参数同名</param>
/// <param name="args">参数名:arg0,arg1,...arg20 (固定写死)</param>
public void AddSetProperty(string propertyName, string executeName, params string[] args)
{
if (_setterPropertyName.ContainsKey(propertyName) || _setterPropertyArgs.ContainsKey(propertyName))
return; _setterPropertyName.Add(propertyName, executeName);
_setterPropertyArgs.Add(propertyName, args);
} /// <summary>
/// 增加自定义的javascript代码。
/// </summary>
/// <param name="javascriptCode">注意:functionName一定要大写。
/// 例如: TEST.__defineSetter__('hello', function(b) {
/// native function sethello();sethello(b);});</param>
public void AddCustomJavascript(string javascriptCode)
{
_customJavascript.Add(javascriptCode);
} /// <summary>
/// 组装本地JS的一个过程
/// </summary>
/// <returns>返回CEF识别的javascript</returns>
public string Create()
{
//System.Threading.Thread.Sleep(3000);
if (string.IsNullOrEmpty(_functionName)) throw new Exception("JavascriptFull函数名不能为空!"); StringBuilder sb = new StringBuilder(); //头部
if (!string.IsNullOrEmpty(_extensionName))
{
sb.Append(string.Format("if (!{0}) var {0} = {{ }}; ", _extensionName));
}
if (!string.IsNullOrEmpty(_functionName))
{
sb.Append(string.Format("var {0} = function () {{ }}; ", _functionName.ToUpper()));
if (!string.IsNullOrEmpty(_extensionName))
sb.Append(string.Format("if (!{0}.{1}) {0}.{1} = {2};", _extensionName, _functionName, _functionName.ToUpper()));
else
sb.Append(string.Format("if (!{0}) var {0} = {1};", _functionName, _functionName.ToUpper()));
} //开始
sb.Append("(function () {"); //方法
foreach (KeyValuePair<string, string[]> item in _methodName)
{
sb.Append(string.Format("{0}.{1} = function ({2}) {{", _functionName.ToUpper(), item.Key, string.Join(",", item.Value)));
sb.Append(string.Format("native function {0}({1}); return {0}({1});", item.Key, string.Join(",", item.Value)));
sb.Append("};");
} //GET属性
foreach (KeyValuePair<string, string> item in _getterPropertyName)
{
sb.Append(string.Format("{0}.__defineGetter__('{1}', function () {{", _functionName.ToUpper(), item.Key));
sb.Append(string.Format("native function {0}(); return {0}();", item.Value));
sb.Append("});");
} //SET属性
if (_setterPropertyArgs.Count == _setterPropertyName.Count)
{
foreach (KeyValuePair<string, string> item in _setterPropertyName)
{
sb.Append(string.Format("{0}.__defineSetter__('{1}', function ({2}) {{", _functionName.ToUpper(), item.Key, string.Join(",", _setterPropertyArgs[item.Key])));
sb.Append(string.Format("native function {0}({1}); return {0}({1});", item.Value, string.Join(",", _setterPropertyArgs[item.Key])));
sb.Append("});");
}
} //自定义javascript
for (int i = ; i < _customJavascript.Count; i++)
{
sb.Append(_customJavascript[i]);
} //结尾
sb.Append("})();"); return sb.ToString();
}
}
}

CEF js调用C#封装类含注释的更多相关文章

  1. JS调用JCEF方法

    坐下写这篇文章的时候,内心还是有一点点小激动的,折腾了一个多星期,踩了一个又一个的坑,终于找到一条可以走通的路,内心的喜悦相信经历过的人都会明白~~~~~今儿个老百姓啊,真呀个真高兴啊,哈哈,好了,废 ...

  2. JS调用OC方法并传值,OC调用JS方法并传值////////////////////////zz

     iOS开发-基于原生JS与OC方法互相调用并传值(附HTML代码)     最近项目里面有有个商品活动界面,要与web端传值,将用户在网页点击的商品id 传给客户端,也就是js交互,其实再说明白一点 ...

  3. Google V8编程详解(五)JS调用C++

    http://blog.csdn.net/feiyinzilgd/article/details/8453230 最近由于忙着解决个人单身的问题,时隔这么久才更新第五章. 上一章主要讲了Google ...

  4. Phonegap 之 iOS银联在线支付(js调用ios端银联支付控件)

    Phonegap项目,做支付的时候,当把网站打包到ios或android端成app后,在app上通过wap调用银联在线存在一个问题: 就是当从银联支付成功后,再从服务器返回到app客户端就很难实现. ...

  5. Xilium.CefGlue利用XHR实现Js调用c#方法

    防外链 博客园原文地址在这里http://www.cnblogs.com/shen6041/p/3442499.html 引 Xilium CefGlue是个不错的cef扩展工程,托管地址在这里 ht ...

  6. JS调用webservice服务

    webservice服务 webservice服务代码 using System; using System.Collections.Generic; using System.Linq; using ...

  7. [Winform]CefSharp ——js调用c#方法

    摘要 有时我们在winform中嵌入浏览器,需要在页面上读取电脑上的一些信息,这个时候就需要用到CefSharp的RegisterJsObject进行注册方法然后供js进行调用了. 一个例子 我们在w ...

  8. cocos2d-js 3.0 RC0 手动绑定 C++调用js,js调用C++ jsbinding

    参考:http://www.tairan.com/archives/4902 参考文章是2.x版本的,对于3.0也许不合适了,没有深究. 代码:https://github.com/kenkozhen ...

  9. asp.net 练习 js 调用webservice

    using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.We ...

随机推荐

  1. <Chapter 2>2-1-2.安装Java SDK

    Java运行时环境的App Engine SDK运行在任何运行了Java SE开发工具(JDK)的电脑上.Java SDK App Engine 支持JDK 6,并且当运行App Engine的时候, ...

  2. Downloading the Google Cloud Storage Client Library

    Google Cloud Storage client是一个客户端库,与任何一个生产环境使用的App Engine版本都相互独立.如果你想使用App Engine Development server ...

  3. UINavigationController切换controller动画设置

    http://blog.csdn.net/dabiaoyanjun/article/details/7774775 uinavigationcontrolleranimation在pushViewCo ...

  4. Codeforces Round #250 (Div. 1) D. The Child and Sequence (线段树)

    题目链接:http://codeforces.com/problemset/problem/438/D 给你n个数,m个操作,1操作是查询l到r之间的和,2操作是将l到r之间大于等于x的数xor于x, ...

  5. 使用 DllImport 属性

    本主题说明 DllImport 属性的常见用法.第一节讨论使用 DllImport 从托管应用程序调用本机代码的优点.第二节集中讨论封送处理和 DllImport 属性的各个方面. 从托管应用程序调用 ...

  6. AxWindowsMediaPlayer创建、添加播放列表(C#)

    // 创见打开对话框对象实例            OpenFileDialog openFileDialog = new OpenFileDialog(); //设置为可以打开多个文件        ...

  7. SQL NULL Values

    NULL代表缺失的.未知的数据.表的列值默认是NULL.如果某个表的某个列不是NOT NULL的,那么当我们插入新纪录.更新已存在的记录时,可以不用为此列赋值,这意味着那个列保存为NULL值. NUL ...

  8. ServletContext2

    ------------ContextServlet.java--------------节选-- protected void doGet(HttpServletRequest request, H ...

  9. DataSource , DataSink, DataSourceLoop

    Script assertion in login:

  10. Spark1.0.0新特性

            Spark1.0.0 release于2014-05-30日正式公布,标志Spark正式进入1.X的时代.Spark1.0.0带来了各种新的特性,并提供了更好的API支持:Spark1 ...