感覺很久不寫模擬器代碼了,昨天調試的時候碰了點壁,記錄下來,避免大家再跟我犯同樣的錯誤。
加入Javascript腳本的地方:
HtmlElement jsElement = 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 = new string[1];
args[0] = "Hello element!";
webBrowser1.Document.InvokeScript("showMeAction", args);
大家特別注意的是后面腳本調用的時候,只能出現函數名與參數值列表,不能增加其他內容,否則調用就不會成功。
使用的腳本代碼:(這里的腳本代碼模擬了鼠標移動的基礎需求,通過Js直接發鼠標事件的方式來實現自動機器人)
function createEvent(eventName, ofsx, ofsy)
{
var evt = document.createEvent('MouseEvents');
evt.initMouseEvent(eventName, true, false, null, 0, 0, 0, ofsx, ofsy, false, false, false, false, 0, null);
return evt;
}
function moveElement(pxToMove)
{
var sliderKnob = document.getElementsByClassName("gt_slider_knob")[0];
var boxRect = sliderKnob.getBoundingClientRect();
var move = createEvent('mousemove', boxRect.left + sliderKnob.offsetLeft + pxToMove, boxRect.top + sliderKnob.offsetTop);
var down = createEvent('mousedown', boxRect.left + sliderKnob.offsetLeft, boxRect.top + sliderKnob.offsetTop);
var up = createEvent('mouseup');
sliderKnob.dispatchEvent(down);
document.dispatchEvent(move);
sliderKnob.dispatchEvent(up);
}
以上所述是小編給大家介紹的使用C# 的webBrowser寫模擬器時的javascript腳本調用問題,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對html5模板網網站的支持!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!