16
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C#でWebBrowserを使用し、JavaScriptとデータをやり取りする

Posted at

C#のWebBrowserコントロールを使用した場合、ハードウェア制御の処理はC#で行い結果表示はjsで表示したいことがあります。
WebBrowser.InvokeScriptメソッドを使用することでC#とjsとでデータのやり取りを行うことができます。

sample.cs
public partial class Form1 : Form
	{

		public Form1()
		{
			InitializeComponent();

			webBrowser1.ObjectForScripting = new TestClasss();
			MainForm_Load();

		}

		private void MainForm_Load()
		{

			var indexPath = "http://127.0.0.1:80/sample.html";
			System.Text.Encoding encoding = System.Text.Encoding.UTF8;
			webBrowser1.Navigate(indexPath);

		}


		[ComVisible(true)]
		public class TestClasss
		{
			public void TestFunc(string str)
			{
				MessageBox.Show(str, "戻り値", MessageBoxButtons.OK);
			}
		}

		private void button1_Click(object sender, EventArgs e)
		{
			webBrowser1.Document.InvokeScript("sample", new string[] { "あいうえお", "さしすせそ" });
		}
	}

forward.html
<html>
<head>
    <meta charset="utf-8">
    <title>タイトル</title>
</head>
<body>
    <script>
        function sample(arg1, arg2) {
            window.external.TestFunc(arg1 + ",かきくけこ," + arg2);
        }
    </script>
</body>
</html>

C#のボタンを押すとjsのsample関数が実行されます。その際objectで引数を渡しています
webBrowser1.Document.InvokeScript("sample", new string[] { "あいうえお", "さしすせそ" });

jsのsampleは受け取った値(「あいうえお」と「さしすせそ」)の文字列をに「かきくけこ」を追加し、C#側のTestFuncを呼び出します。
window.external.TestFunc(arg1 + ",かきくけこ," + arg2);

これでC#とjsとでデータの受け渡しが完了です。

16
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?