使用C# 的webBrowser写模拟器时的javascript脚本调用问题
感觉很久不写模拟器代码了,昨天调试的时候碰了点壁,记录下来,避免大家再跟我犯同样的错误。
加入Javascript脚本的地方:
HtmlElementjsElement=webBrowser1.Document.CreateElement("script");
jsElement.SetAttribute("type","text/javascript");
jsElement.SetAttribute("text","showMeAction=function(e){window.alert(e);}");
webBrowser1.Document.Body.AppendChild(jsElement);
调用的地方:
string[]args=newstring[1];
args[0]="Helloelement!";
webBrowser1.Document.InvokeScript("showMeAction",args);
大家特别注意的是后面脚本调用的时候,只能出现函数名与参数值列表,不能增加其他内容,否则调用就不会成功。
使用的脚本代码:(这里的脚本代码模拟了鼠标移动的基础需求,通过Js直接发鼠标事件的方式来实现自动机器人)
functioncreateEvent(eventName,ofsx,ofsy)
{
varevt=document.createEvent('MouseEvents');
evt.initMouseEvent(eventName,true,false,null,0,0,0,ofsx,ofsy,false,false,false,false,0,null);
returnevt;
}
functionmoveElement(pxToMove)
{
varsliderKnob=document.getElementsByClassName("gt_slider_knob")[0];
varboxRect=sliderKnob.getBoundingClientRect();
varmove=createEvent('mousemove',boxRect.left+sliderKnob.offsetLeft+pxToMove,boxRect.top+sliderKnob.offsetTop);
vardown=createEvent('mousedown',boxRect.left+sliderKnob.offsetLeft,boxRect.top+sliderKnob.offsetTop);
varup=createEvent('mouseup');
sliderKnob.dispatchEvent(down);
document.dispatchEvent(move);
sliderKnob.dispatchEvent(up);
}
以上所述是小编给大家介绍的使用C#的webBrowser写模拟器时的javascript脚本调用问题,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!