c# - WebBrowser 控件外部脚本不起作用

标签 c# com webbrowser-control

这是 HTML,存储在字符串资源中:

<!DOCTYPE html>
<html>
    <head></head>
    <body>
        <script>
           (function(){
               window.external.hello()
           })()
        </script>
    </body> 
</html>

这是Form1.cs的内容:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace JSIE
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            webBrowser1.Navigate("about:blank");
            webBrowser1.Document.Write(String.Empty);
            webBrowser1.Document.Write(Properties.Resources.DDocument);
            webBrowser1.ObjectForScripting = new JSCallbacks();
        }
    }
}

这是 JSCallbacks.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace JSIE
{
    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    [ComVisible(true)]

    public class JSCallbacks
    {
        public void hello() {
            MessageBox.Show("Hello, world!");
        }
    }
}

当我运行它时,它无法访问 JavaScript window.external 对象中的 hello() 方法,并给我一个脚本错误消息框。我尝试过使用 this 作为 ObjectForScripting,但它也不起作用。

最佳答案

明白了:在页面执行之前,您必须使用 DocumentText 属性加载 HTML。

关于c# - WebBrowser 控件外部脚本不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13130880/

相关文章:

c# - 如何将函数返回值编码到非托管 dll

c# - CefSharp.wpf Web 浏览器导航事件 (C# .Net)

c# - winforms webbrowser 浏览器时返回一组url地址

c# - 如何防止用户浏览 Web 浏览器控件中的某些网站?

c# - 如何使用 C# 脚本让我的角色进入 GTA 中车辆后座的汽车?

c# - 在 C# 中寻找可用的不可变 bool 数组

c# - 没有 I/O 的等待开销是多少?

c# - 从 DataTable 的列创建 HashSet

c# - MS Office Interop - 无法发布对 RCW 的引用

c# - 安装 .NET COM+ dll