• c#: WebBrowser控件注入js代码的三种方案


    聊做备忘。

    假设js代码为:

    string jsCode = @"function showAlert(s) {{ alert('hello, world! ' + s);}}; showAlert('{0}');";
    

      

    那么,在WebBrowser文档加载完成后,两种方法可以执行它:

    1、常规方法,追加script元素:

    var script = browser.Document.CreateElement("script");
    script.SetAttribute("type", "text/javascript");
    script.SetAttribute("text", "function _func() {" + string.Format(jsCode, "method 1") + "}");
    browser.Document.Body.AppendChild(script);
    browser.Document.InvokeScript("_func");

    这种方法,可以传参及取得返回值,用的多些。缺点是因为注入html页面中,会影响html源码。 

    如果禁止browser报script错误,其即便运行出错也无提示。

    2、DomDocument法。此方法,须在程序中引用MSHTML对象。

    ar doc = this.browser.Document.DomDocument as IHTMLDocument2;
    var win = doc.parentWindow as IHTMLWindow2;
    jsCode = string.Format(jsCode, "method 2"); 
    win.execScript(jsCode, "javascript");

    此方案不能传参没有返回值,还要引用MSHTML对象,用的少些。 其与下面方案一样,不影响页面html源码结构。

    若js代码运行出错,即有提示。

    3、最简方案:

    browser.Document.InvokeScript("execScript", new Object[] { string.Format(jsCode, "method 3"), "javascript" });

    这种省事,是我最喜欢的方法!

    这三种方法,都 能成功执行js代码:

    参考资料:

    webBrowser调用外部js文件和js函数 - SDYWCD--阿达阿达 - ITeye博客

    在 C# 中执行 js · Issue #9 · jinhailang/blog

  • 相关阅读:
    POJ1006(中国剩余定理)
    Ubuntu16.04安装jupiter
    OpenGL.tutorial06键盘和鼠标
    OpenGL.教程
    OpenGL.Qt532.cube
    Qt551.主窗体Margin
    Qt551.窗口滚动条
    Qt551.OpenGL.ZC简单例子
    Qt5OpenGL.顶点像素大小设置
    OpenGL.Tutorial03_Matrices_测试
  • 原文地址:https://www.cnblogs.com/crwy/p/11275245.html
Copyright © 2020-2023  润新知