webbrowser和js交互小结
一、实现WebBrowser内部跳转,阻止默认打开IE
1、引用封装好的WebBrowserLinkSelf.dll实现
public partial class MainWindow : Window
{
private WebBrowser webBrowser = new WebBrowser(); public MainWindow()
{
InitializeComponent(); this.webBrowser.LoadCompleted += new LoadCompletedEventHandler(webBrowser_LoadCompleted); //使webbrowser寄宿于Label上,实现webborwser内部跳转,不用IE打开
Label lb = new Label { Content = webBrowser };
WebBrowserHelper webBrowserHelper = new WebBrowserHelper(webBrowser);
HelperRegistery.SetHelperInstance(lb, webBrowserHelper);
webBrowserHelper.NewWindow += WebBrowserOnNewWindow;
this.lbBrowserHost.Content = lb; // this.webBrowser.Navigate(new Uri("http://www.baidu.com", UriKind.RelativeOrAbsolute));
} private void WebBrowserOnNewWindow(object sender, CancelEventArgs e)
{
dynamic browser = sender;
dynamic activeElement = browser.Document.activeElement;
var link = activeElement.ToString();
this.webBrowser.Navigate(new Uri(link, UriKind.RelativeOrAbsolute));
e.Cancel = true;
}
}
2、引用com:Microsoft Internet Controls实现(参考MSDN:http://msdn.microsoft.com/en-us/library/system.windows.controls.webbrowser.aspx public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.webBrowser1.Navigate(new Uri("http://www.baidu.com", UriKind.RelativeOrAbsolute));
this.webBrowser1.LoadCompleted += new LoadCompletedEventHandler(webBrowser1_LoadCompleted);
}
private IServiceProvider serviceProvider;
void webBrowser1_LoadCompleted(object sender, NavigationEventArgs e)
{
if (this.serviceProvider == null)
{
serviceProvider = (IServiceProvider)webBrowser1.Document;
if (serviceProvider != null)
{
Guid serviceGuid = new Guid("0002DF05-0000-0000-C000-000000000046");
Guid iid = typeof(SHDocVw.WebBrowser).GUID;
var webBrowserPtr = (SHDocVw.WebBrowser)serviceProvider
.QueryService(ref serviceGuid, ref iid);
if (webBrowserPtr != null)
{
webBrowserPtr.NewWindow2 += webBrowser1_NewWindow2;
}
}
}
}
private void webBrowser1_NewWindow2(ref object ppDisp, ref bool Cancel)
{
dynamic browser = this.webBrowser1;
dynamic activeElement = browser.Document.activeElement;
var link = activeElement.ToString();
this.webBrowser1.Navigate(new Uri(link, UriKind.RelativeOrAbsolute));
Cancel = true;
}
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("6d5140c1-7436-11ce-8034-00aa006009fa")]
internal interface IServiceProvider
{
[return: MarshalAs(UnmanagedType.IUnknown)]
object QueryService(ref Guid guidService, ref Guid riid);
}
}
二、WebBrowser与JS的交互
1、与页面标签的交互
//引用Microsoft.mshtml
//1、添加一个html标签到id为lg的div中
HTMLDocument doc = (HTMLDocument)this.webBrowser.Document;
IHTMLElement lbelem = doc.createElement("button");
lbelem.innerText = "test";
lbelem.style.background = "red";
IHTMLDOMNode node = doc.getElementById("lg") as IHTMLDOMNode;
node.appendChild(lbelem as IHTMLDOMNode);
//2、设置id为su的标签value值和style
//2.1 使用setAttribute
HTMLDocument doc = (HTMLDocument)this.webBrowser.Document;
IHTMLElement search = doc.getElementById("su");
IHTMLDOMAttribute att = search.getAttribute("value") as IHTMLDOMAttribute;
search.setAttribute("value", "百度一下");
//search.click();
search.style.display = "none";
//2.2 使用outerHtml
search.outerHTML = "<input id=\"su\" value=\"百度一下\" class=\"bg s_btn\" type=\"submit\" onclick=\"alert('百度一下');\" />";
//2.3 使用IHTMLDOMAttribute
IHTMLAttributeCollection attributes = (search as IHTMLDOMNode).attributes as IHTMLAttributeCollection;
foreach (IHTMLDOMAttribute attr in attributes)
{
if (attr.nodeName == "value")
{
attr.nodeValue = "百度一下";
}
}
//3、替换应用了类样式mnav的a标签
HTMLDocument doc = (HTMLDocument)this.webBrowser.Document;
IHTMLElementCollection collect = doc.getElementsByTagName("a");
foreach (IHTMLElement elem in collect)
{
if (!(elem is IHTMLUnknownElement) && elem.className != null)
{
if (elem.className.Equals("mnav", StringComparison.OrdinalIgnoreCase))
{
elem.outerHTML = "<a href='#' title='替换标签' >替换</a>";
}
}
}
//4、删除节点
HTMLDocument doc = (HTMLDocument)this.webBrowser.Document;
IHTMLElement search = doc.getElementById("su");
IHTMLDOMNode node = search as IHTMLDOMNode;
node.parentNode.removeChild(node);
//5、JS事件
//5.1 添加JS
HTMLDocument doc = (HTMLDocument)this.webBrowser.Document;
IHTMLElement search = doc.getElementById("su");
search.outerHTML = "<input id=\"su\" value=\"百度一下\" class=\"bg s_btn\" type=\"submit\" onclick=\"onClick();\" />";
IHTMLScriptElement scriptErrorSuppressed = (IHTMLScriptElement)doc.createElement("script");
scriptErrorSuppressed.type = "text/javascript";
scriptErrorSuppressed.text = "function onClick(){ alert('添加js'); }";
IHTMLElementCollection nodes = doc.getElementsByTagName("head");
foreach (IHTMLElement elem in nodes)
{
var head = (HTMLHeadElement)elem;
head.appendChild((IHTMLDOMNode)scriptErrorSuppressed);
}
//5.2 删除JS
IHTMLElementCollection scripts = (IHTMLElementCollection)doc.getElementsByName("script");
foreach (IHTMLElement node in scripts)
{
if (!(node is IHTMLUnknownElement))
{
IHTMLScriptElement script = node as IHTMLScriptElement;
//删除所有js文件引用
if (string.IsNullOrEmpty(script.text))
{
IHTMLDOMNode remove = script as IHTMLDOMNode;
remove.parentNode.removeChild(remove);
}
}
}
//6、write new html
mshtml.IHTMLDocument2 doc2 = this.webBrowser.Document as mshtml.IHTMLDocument2;
doc2.clear();
doc2.writeln("<HTML><BODY>write new html</BODY></HTML>");
2、数据交互
public MainWindow()
{
InitializeComponent();
this.webBrowser.ObjectForScripting = new ScriptEvent();
this.webBrowser.NavigateToString(@"<html><head><title>Test</title></head><body><input type=""button"" value=""点击"" onclick=""window.external.ShowMessage('百度一下');"" /></body></html>");
} [System.Runtime.InteropServices.ComVisible(true)]
public class ScriptEvent
{
//供JS调用
public void ShowMessage(string message)
{
MessageBox.Show(message);
}
}
源码:http://files.cnblogs.com/NotAnEmpty/wpf_WebBorwser.rar
webbrowser和js交互小结的更多相关文章
- WinForm程序执行JS代码的多种方法以及使用WebBrowser与JS交互
方法一 使用微软官方组件Interop.MSScriptControl 1.msscript.ocx下载的地址 http://www.microsoft.com/downloads/details ...
- Winform 通过 WebBrowser 与 JS 交互
Winform 通过 WebBrowser 与 JS 交互 魏刘宏 2019.08.17 之前在使用 Cef (可在 Winform 或 WPF 程序中嵌入 Chrome 内核的网页浏览器的组件)时, ...
- C#中webbrowser与javascript(js)交互的方法
今天在做一个项目的时候需要用c#搞一个webbrowser,然后有些地方还需要与js交互.所以就查了一下资料,发现很多博客提到了但是却没有说下具体的操作.所以我就写一下. 开发环境是Visual St ...
- C#和JS交互 WebBrowser实例
本文实现了WebBrowser的简单例子 1.引用System.Windows.Froms.dll 2.引用WindowsFormsIntegration.dll 代码如下: public parti ...
- 第4章-Vue.js 交互及实例的生命周期
一.学习目标 了解实例生命周期的过程 理解钩子函数的作用 掌握Vue.js过滤器的使用方法 (重点) 能够使用网络请求进行前后端交互 (重点.难点) 二.交互的基本概念 2.1.前端和后端的概念 说明 ...
- WPF内嵌CEF控件,与JS交互
1)安装cefsharp.winform包 打开VS2017,打开nuget,找到cefsharp.winform,安装 问:为什么wpf程序不使用cefsharp.wpf? 答:因为cefwpf 4 ...
- 关于JS交互--调用h5页面,点击页面的按钮,分享到微信朋友圈,好友
关于js交互,在iOS中自然就想到了调用代理方法 另外就是下面的,直接上代码了: 如果你的后台需要知道你的分享结果,那么,就在回调里面调用上传到服务器结果的请求即可
- webView和js交互
与 js 交互 OC 调用 JS // 执行 js - (void)webViewDidFinishLoad:(UIWebView *)webView { NSString *title = [web ...
- 李洪强iOS经典面试题147-WebView与JS交互
李洪强iOS经典面试题147-WebView与JS交互 WebView与JS交互 iOS中调用HTML 1. 加载网页 NSURL *url = [[NSBundle mainBundle] UR ...
随机推荐
- 转-centos7下安装apache服务器httpd的yum方式安装
转自Clement-Xu的csdn博客 http://blog.csdn.net/clementad/article/details/41620631 Apache在Linux系统中,其实叫“ht ...
- SEM竞价数据基本分析方法
今天我们从账户数据表现来看一看怎样通过数据分析,判断账户出现的问题及解决思路.也欢迎大家提出意见,共同讨论进步. 首先我们从关键词报告来分析数据: 以上图数据为例.(设定该行业CPC均价为8) 先说下 ...
- HTTP与HTTPS有什么区别?
HTTP协议传输的数据都是未加密的,也就是明文的,因此使用HTTP协议传输隐私信息非常不安全,为了保证这些隐私数据能加密传输,于是网景公司设计了SSL(Secure Sockets Layer)协议用 ...
- linux基础(10)-导航菜单
导航菜单实战 例:编写一个shell脚本,包含多个菜单,其中需要一个退出选项:可单选也可多选:根据序号选择后,显示所选菜单名称. #!/bin/bash ####################### ...
- DATEDIFF 的用法
DECLARE @date DATETIME = '2017-12-26 00:00:00';DECLARE @date2 DATETIME = DATEADD(DAY, 1, @date);DECL ...
- 语音01_TTS
1.http://blog.csdn.net/u010176014/article/details/47428595 2.家里 Win7x64 安装“微软TTS5.1语音引擎(中文).msi”之后,搜 ...
- keystone v2/v3
Changing from APIv2.0 to APIv3 in Keystone - Openstack Juno on Ubuntu 1. 更换v3 的policy文件 mv /etc/keys ...
- Apache虚拟主机配置模板
/////////////////////////////////写在前头////////////////////////////////////////1.Apache HTTP 服务器2.4文档: ...
- 平衡二叉树--java
package com.test.tree; /** * 带有平衡条件的二叉查找树 * */ public class AVLBinarySearchTree<T extends Compara ...
- 写hibernate.cfg.xml时报错The content of element type "property" must match "(meta*,(column|formula)*,type?)".
原配置文件是这样的 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-ma ...