【发布时间】:2012-10-29 22:59:18
【问题描述】:
这是存储在字符串资源中的 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,但它也不起作用。
【问题讨论】:
-
对于那些不熟悉
ObjectForScripting的人:msdn.microsoft.com/en-us/library/… -
好吧,这很奇怪。出于某种原因,当我从
<script>标签调用它时,hello()函数并不“存在”,但如果我从事件属性(onclick=""等)调用它。 -
哦,这可能是因为在您调用该代码时您的 DOM 尚未初始化。在解析 DOM 的其余部分之前,您的代码正在运行。
-
您能否在表单加载后捕获 DOM 的实时输出? (抱歉,我也不是 100% 熟悉这个对象,也从未使用它写过任何东西。假设您可以在加载后捕获实时 DOM 元素)
-
您有一种奇怪的方式来加载文档。设置 ObjectForScripting 后如何设置 DocumentText 属性?
标签: c# com webbrowser-control