[英]JavaScript with WebBrowser control C#
最近,我一直在遇到C#中的Web瀏覽器控件問題。
導航到其中實現了JavaScript的網頁會使WebBrowser崩潰-它聲稱該網頁中的JS代碼中存在語法錯誤。 (它提供了該行,並且char是什么錯誤,所以我去看看是什么引起了錯誤)。
錯誤示例:
function validate_fen(fen) {
var errors = {
0: 'No errors.',
1: 'FEN string must contain six space-delimited fields.',
2: '6th field (move number) must be a positive integer.',
3: '5th field (half move counter) must be a non-negative integer.',
4: '4th field (en-passant square) is invalid.',
5: '3rd field (castling availability) is invalid.',
6: '2nd field (side to move) is invalid.',
7: '1st field (piece positions) does not contain 8 \'/\'-delimited rows.',
8: '1st field (piece positions) is invalid [consecutive numbers].',
9: '1st field (piece positions) is invalid [invalid piece].',
10: '1st field (piece positions) is invalid [row too large].',
};
錯誤所在的行是3977字符5,或更具體地說是該代碼在字符5中的最后一行(這意味着它可能是最后一個逗號,如果我輸入錯誤,請糾正我)。
該錯誤的更具體的代碼:
10: '1st field (piece positions) is invalid [row too large].',
};
鑒於其他瀏覽器確實可以正確加載包括IE的網站(我知道webBrowser和IE不同),我將如何解決這些問題?
我的想法是:
我不確定,但是我認為如果出現錯誤導致以后出現更多錯誤,則webBrowser控件不會加載腳本。
如何成功加載特定網頁? 在運行時是否可以編輯腳本(腳本不在HTML的標題中,而是在服務器上)? 如果可能的話,怎么辦?
如何在C#中加載和修復腳本:
從網站復制非加載腳本並修復語法錯誤,然后將其復制到您的代碼中。
重要說明:將腳本的所有代碼放入函數中,以便稍后使用
使用以下代碼將腳本添加到站點:
HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
HtmlElement scriptEl = webBrowser1.Document.CreateElement("script");
IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
element.text = script;//script is your script which you defined
head.AppendChild(scriptEl);
將InvokeScript調用到您創建的函數。
如果您修復了所有語法錯誤,應該沒問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.