首页 > 解决方案 > 从包含 c# 变量的文件中执行 JS 脚本

问题描述

我正在使用 CefSharp 创建一个软件,需要执行一些 JS 代码。我现在正在做的是只使用一行编写脚本,但这并不方便,并且很难应用修改。

这是我试图执行的文件中的 JS 脚本: console.log(size) //size.Text is the variable defined in C# 但是由于size变量是在 c# 中定义的,所以我得到的输出是undefined.

这是我用来加载文件的代码:

string size = "XL";
string testJs = Path.Combine(Environment.CurrentDirectory, @"Data\", "test.js");
string test = File.ReadAllText(testJs);
browser.ExecuteScriptAsyncWhenPageLoaded(test);

还有一个可行的(单行的):

browser.ExecuteScriptAsyncWhenPageLoaded("console.log(" + size + ");")

所以主要问题是将变量传递给XL浏览器的控制台作为输出。

标签: javascriptc#cefsharp

解决方案


考虑到它size是从 C# 代码传递的,您在 js 文件中需要的是一个占位符,以后可以替换它。

一种可能的解决方案可能是 -

JS文件

console.log('@{SIZE}@');// you can use any formatting for your placeholder

C# 代码

string size = "XL";
string testJs = Path.Combine(Environment.CurrentDirectory, @"Data\", "test.js");
string test = File.ReadAllText(testJs).Replace("@{SIZE}@", size);
browser.ExecuteScriptAsyncWhenPageLoaded(test);

这种方法将允许您在 js 文件中使用任意数量的占位符以及要使用它们的任意数量的位置。


推荐阅读