WebBrowser控件外部脚本不起作用

时间:2012-10-29 22:59:18

标签: 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 hello()对象中的window.external方法,并为我提供了一个脚本错误消息框。我尝试使用this作为ObjectForScripting,但它也不起作用。

1 个答案:

答案 0 :(得分:2)

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