javascript - 从包含 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
浏览器的控制台作为输出。
解决方案
考虑到它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 文件中使用任意数量的占位符以及要使用它们的任意数量的位置。
推荐阅读
- angular6 - 将多个值推送到 FormArray
- python-3.x - 使用 Pandas 对 CSV 进行数据清理
- php - 使用 PHP 从 URL 中提取 ID 或特定部分
- android - 将一个类的 RecyclerList 数据加载到另一个类的 RecyclerList
- python - 使用 Pandas 进行反向二进制编码
- sql-server - 'CREATE USER [user_name] FOR LOGIN [login_name]' 和 'CREATE USER [user_name] FROM LOGIN [login_name]' 有什么区别
- javascript - React Native onPress 功能不起作用
- oracle - 从平均 Oracle SQL 中减去
- javascript - 取消选中复选框时如何删除数组的一项(角度4)
- pandas - 将 hour_index 数据帧与 day_index 数据帧合并,并使用 day_index 数据帧中的相同值填充所有行