本人测试了3种方法,只有第三种有效(间接append)
注:皆在Gecko_DocumentCompleted 中使用
第一种(无效,直接报document is not defined) 估计是加载问题
try
{
using (AutoJSContext context = new AutoJSContext(browser.Window.JSContext))
{
MessageBox.Show("开始加载");
var theAppendJQ = @"var aoq_script=document.createElement(""script"");
aoq_script.type = ""text/javascript"";
aoq_script.src = ""https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"";
document.getElementsByTagName('head')[0].appendChild(aoq_script); ";
context.EvaluateScript(theAppendJQ);
string result;
context.EvaluateScript(theAppendJQ, out result);
MessageBox.Show(result);
}
}
catch (Exception ex)
{
MessageBox.Show("方式1:"+ ex.Message);
}
第二种(无效,没报错,但是在运行jquery时提示$ is not defined) 就是没加载上jquery
try
{
GeckoHtmlElement scriptJQ = (GeckoHtmlElement)browser.Document.CreateElement("div");
scriptJQ.InnerHtml = @"<script> var aoq_script=document.createElement(""script"");
aoq_script.type = ""text/javascript"";
aoq_script.src = ""https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"";
document.getElementsByTagName('head')[0].appendChild(aoq_script); </script> ";
var bodyDC = browser.Document.GetElementsByTagName("body")[0];
bodyDC.AppendChild(scriptJQ);
}
catch (Exception ex)
{
MessageBox.Show("方式2:" + ex.Message);
}
第三种(有效) 通过查找资料只能曲线救国,使用SetAttribute设置click,并且通过自动点击来使页面动态引入jquery,后续就可以通过jquery 脚本操作了
try
{
string jqFun= @"var aoq_script=document.createElement('script');
aoq_script.type = 'text/javascript';
aoq_script.src = 'https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js';
document.getElementsByTagName('head')[0].appendChild(aoq_script);";
var bodyDC = browser.Document.GetElementsByTagName("body")[0];
bodyDC.SetAttribute("onclick", ""+ jqFun);
bodyDC.Click();
}
catch (Exception ex)
{
MessageBox.Show("方式3:" + ex.Message);
}
经过第三种附加jquery后,就可以使用自己的jquery脚本了
var executor = new Gecko.JQuery.JQueryExecutor(browser.Window);
if (!string.IsNullOrEmpty(backJqsrcipt))
{
executor.ExecuteJQuery(backJqsrcipt);
}