感覺很久不寫模擬器代碼了,昨天調試的時候碰了點壁,記錄下來,避免大家再跟我犯同樣的錯誤。
加入Javascript腳本的地方:
1
2
3
4
|
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); |
調用的地方:
1
2
3
|
string[] args = new string[1]; args[0] = "Hello element!" ; webBrowser1.Document.InvokeScript( "showMeAction" , args); |
大家特別注意的是后面腳本調用的時候,只能出現函數名與參數值列表,不能增加其他內容,否則調用就不會成功。
使用的腳本代碼:(這里的腳本代碼模擬了鼠標移動的基礎需求,通過Js直接發鼠標事件的方式來實現自動機器人)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
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腳本調用問題,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:http://blog.csdn.net/jackxinxu2100/article/details/74905348?utm_source=tuicool&utm_medium=referral