C#webbrowser无法正确运行javascript代码

时间:2016-01-24 10:38:11

标签: javascript c# webbrowser-control youtube-javascript-api

我的问题是我的webbrowser组件无法运行javascript代码。如果我使用IE,脚本可以正常工作。 (我使用.net 4.0框架)

我的Javascript代码:

<div id="player"></div>
<script src="http://www.youtube.com/player_api"></script>
<script>
    var player;
    function onYouTubePlayerAPIReady() {
        player = new YT.Player('player', {
          height: '200',
          width: '400',
          videoId: '9eh0rAUwZSQ',
          events: {
            'onReady': onPlayerReady,
            'onStateChange': onPlayerStateChange
          }
        });
    }
    function onPlayerReady(event) {
        event.target.playVideo();
    }
    function onPlayerStateChange(event) {      
        if(event.data === 0) {        
            alert('done');
        }
    }
</script>

C#代码:

using System;
using System.Windows.Forms;
using System.Security.Permissions;
using System.IO;

namespace two_channel_test
{
  [System.Runtime.InteropServices.ComVisibleAttribute(true)]
  [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]

  public partial class Form1 : Form
  {
      public WebBrowser webBrowser1 = new WebBrowser();

  public Form1()
      {
          InitializeComponent();

          webBrowser1.Dock = DockStyle.Fill;
          Controls.Add(webBrowser1);
          Load += new EventHandler(Form1_Load);
      }

      private void Form1_Load(object sender, EventArgs e)
      {
          webBrowser1.AllowWebBrowserDrop = false;
          webBrowser1.IsWebBrowserContextMenuEnabled = false;
          webBrowser1.WebBrowserShortcutsEnabled = false;
          webBrowser1.ObjectForScripting = this;
          webBrowser1.ScriptErrorsSuppressed = true;

          StringReader sr;
          sr = new StringReader(System.IO.File.ReadAllText(@"c:\something\javascriptcode.txt"));        // this is my javascript code what I wrote
          webBrowser1.DocumentText = sr.ReadToEnd();
      }

      public void Test()
      {
          MessageBox.Show("Working...", "client code");
      }
  }
}

您知道我的代码有什么问题吗?

0 个答案:

没有答案