c# WebBrowser运行Javascript -返回空白页面与Javascript的结果-为什么



当我尝试在web浏览器中运行javascript时,代码运行,但在它被执行后,我在一个白色页面上,右上角有一个数字值(在本例中为"1000"),带我离开我以前所在的网站

HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
HtmlElement scriptEl = webBrowser1.Document.CreateElement("script");
IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
element.text = "function ScrollDown() { document.getElementsByClassName('scrollableitemclass').scrollTop = 1000 }";
head.AppendChild(scriptEl);
webBrowser1.Document.InvokeScript("ScrollDown");

谢谢你的帮助

你可以使用HtmlElement.ScrollIntoView滚动到你的Html元素。

请看下面的例子:

 public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            webBrowser1.DocumentText = "<html><body><span class="cls" id="el"> </body></html>";
        }
        void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            //for element with id
            webBrowser1.Document.GetElementById("el").ScrollIntoView(true);
            //for element with spesific
            foreach (HtmlElement el in webBrowser1.Document.All)
            {
                if (el.GetAttribute("ClassName") == "cls")
                {
                    el.ScrollIntoView(true);
                }
            }
        }

    }

最新更新