Nice programing

WebBrowser 컨트롤에 Javascript를 삽입하는 방법은 무엇입니까?

nicepro 2020. 10. 8. 18:58
반응형

WebBrowser 컨트롤에 Javascript를 삽입하는 방법은 무엇입니까?


나는 이것을 시도했다 :

string newScript = textBox1.Text;
HtmlElement head = browserCtrl.Document.GetElementsByTagName("head")[0];
HtmlElement scriptEl = browserCtrl.Document.CreateElement("script");
lblStatus.Text = scriptEl.GetType().ToString();
scriptEl.SetAttribute("type", "text/javascript");
head.AppendChild(scriptEl);
scriptEl.InnerHtml = "function sayHello() { alert('hello') }";

scriptEl.InnerHtml 및 scriptEl.InnerText 모두 오류가 발생합니다.

System.NotSupportedException: Property is not supported on this type of HtmlElement.
   at System.Windows.Forms.HtmlElement.set_InnerHtml(String value)
   at SForceApp.Form1.button1_Click(Object sender, EventArgs e) in d:\jsight\installs\SForceApp\SForceApp\Form1.cs:line 31
   at System.Windows.Forms.Control.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
   at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ButtonBase.WndProc(Message& m)
   at System.Windows.Forms.Button.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

DOM에 스크립트를 삽입하는 쉬운 방법이 있습니까?


어떤 이유로 Richard의 솔루션이 내 쪽에서 작동하지 않았습니다 (insertAdjacentText가 예외로 실패했습니다). 그러나 이것은 작동하는 것 같습니다.

HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
HtmlElement scriptEl = webBrowser1.Document.CreateElement("script");
IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
element.text = "function sayHello() { alert('hello') }";
head.AppendChild(scriptEl);
webBrowser1.Document.InvokeScript("sayHello");

이 답변IHTMLScriptElement 은 프로젝트에 인터페이스 를 가져 오는 방법을 설명합니다 .


HtmlDocument doc = browser.Document;
HtmlElement head = doc.GetElementsByTagName("head")[0];
HtmlElement s = doc.CreateElement("script");
s.SetAttribute("text","function sayHello() { alert('hello'); }");
head.AppendChild(s);
browser.Document.InvokeScript("sayHello");

(.NET 4 / Windows Forms 앱에서 테스트 됨)

편집 : 기능 세트의 케이스 문제를 수정했습니다.


이 작업을 마치고 찾은 가장 쉬운 방법은 다음과 같습니다.

string javascript = "alert('Hello');";
// or any combination of your JavaScript commands
// (including function calls, variables... etc)

// WebBrowser webBrowser1 is what you are using for your web browser
webBrowser1.Document.InvokeScript("eval", new object[] { javascript });

전역 JavaScript 함수 eval(str)가하는 일은 str에 작성된 모든 것을 구문 분석하고 실행하는 것입니다. 여기에서 w3schools ref를 확인 하십시오 .


또한 .NET 4에서는 dynamic 키워드를 사용하면 더 쉽습니다.

dynamic document = this.browser.Document;
dynamic head = document.GetElementsByTagName("head")[0];
dynamic scriptEl = document.CreateElement("script");
scriptEl.text = ...;
head.AppendChild(scriptEl);

정말로 원하는 것이 자바 스크립트를 실행하는 것이라면 이것이 가장 쉬울 것입니다 (VB .Net).

MyWebBrowser.Navigate("javascript:function foo(){alert('hello');}foo();")

나는 이것이 그것을 "주입"하지 않을 것이라고 생각하지만 그것이 당신이 추구하는 것이라면 당신의 기능을 실행할 것입니다. (문제를 지나치게 복잡하게 만든 경우를 대비하여.) 그리고 자바 스크립트에서 주입하는 방법을 알아낼 수 있다면이를 "foo"함수의 본문에 넣고 자바 스크립트가 자동으로 주입하도록하십시오.


HTML 문서에 대한 관리되는 래퍼는 필요한 기능을 완전히 구현하지 않으므로 원하는 작업을 수행하려면 MSHTML API를 살펴 봐야합니다.

1) COM 참조 에서 "Microsoft HTML Object Library"라고하는 MSHTML에 대한 참조를 추가합니다 .

2) 'using mshtml;'추가 네임 스페이스에.

3) 스크립트 요소의 IHTMLElement에 대한 참조를 가져옵니다.

IHTMLElement iScriptEl = (IHTMLElement)scriptEl.DomElement;

4) "afterBegin"의 첫 번째 매개 변수 값을 사용하여 insertAdjacentText 메소드를 호출하십시오. 가능한 모든 값은 다음과 같습니다 .

iScriptEl.insertAdjacentText("afterBegin", "function sayHello() { alert('hello') }");

5) 이제 scriptEl.InnerText 속성에서 코드를 볼 수 있습니다.

Hth, Richard


허용되는 답변에 대한 후속 조치로 추가 형식 라이브러리를 포함 할 필요가없는 IHTMLScriptElement인터페이스 의 최소 ​​정의입니다 .

[ComImport, ComVisible(true), Guid(@"3050f28b-98b5-11cf-bb82-00aa00bdce0b")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)]
[TypeLibType(TypeLibTypeFlags.FDispatchable)]
public interface IHTMLScriptElement
{
    [DispId(1006)]
    string text { set; [return: MarshalAs(UnmanagedType.BStr)] get; }
}

따라서 WebBrowser 컨트롤 파생 클래스 내의 전체 코드는 다음과 같습니다.

protected override void OnDocumentCompleted(
    WebBrowserDocumentCompletedEventArgs e)
{
    base.OnDocumentCompleted(e);

    // Disable text selection.
    var doc = Document;
    if (doc != null)
    {
        var heads = doc.GetElementsByTagName(@"head");
        if (heads.Count > 0)
        {
            var scriptEl = doc.CreateElement(@"script");
            if (scriptEl != null)
            {
                var element = (IHTMLScriptElement)scriptEl.DomElement;
                element.text =
                    @"function disableSelection()
                    { 
                        document.body.onselectstart=function(){ return false; }; 
                        document.body.ondragstart=function() { return false; };
                    }";
                heads[0].AppendChild(scriptEl);
                doc.InvokeScript(@"disableSelection");
            }
        }
    }
}

이것은 mshtml을 사용하는 솔루션입니다.

IHTMLDocument2 doc = new HTMLDocumentClass();
doc.write(new object[] { File.ReadAllText(filePath) });
doc.close();

IHTMLElement head = (IHTMLElement)((IHTMLElementCollection)doc.all.tags("head")).item(null, 0);
IHTMLScriptElement scriptObject = (IHTMLScriptElement)doc.createElement("script");
scriptObject.type = @"text/javascript";
scriptObject.text = @"function btn1_OnClick(str){
    alert('you clicked' + str);
}";
((HTMLHeadElementClass)head).appendChild((IHTMLDOMNode)scriptObject);

C #에서 WebBrowser Control HTML 문서에 Javascript를 삽입하는 가장 간단한 방법은 인수로 삽입 할 코드를 사용하여 "execStrip"메서드를 호출하는 것입니다.

이 예에서 자바 스크립트 코드는 전역 범위에서 삽입되고 실행됩니다.

var jsCode="alert('hello world from injected code');";
WebBrowser.Document.InvokeScript("execScript", new Object[] { jsCode, "JavaScript" });

If you want to delay execution, inject functions and call them after:

var jsCode="function greet(msg){alert(msg);};";
WebBrowser.Document.InvokeScript("execScript", new Object[] { jsCode, "JavaScript" });
...............
WebBrowser.Document.InvokeScript("greet",new object[] {"hello world"});

This is valid for Windows Forms and WPF WebBrowser controls.

This solution is not cross browser because "execScript" is defined only in IE and Chrome. But the question is about Microsoft WebBrowser controls and IE is the only one supported.

For a valid cross browser method to inject javascript code, create a Function object with the new Keyword. This example creates an anonymous function with injected code and executes it (javascript implements closures and the function has access to global space without local variable pollution).

var jsCode="alert('hello world');";
(new Function(code))();

Of course, you can delay execution:

var jsCode="alert('hello world');";
var inserted=new Function(code);
.................
inserted();

Hope it helps


I used this :D

HtmlElement script = this.WebNavegador.Document.CreateElement("SCRIPT");
script.SetAttribute("TEXT", "function GetNameFromBrowser() {" + 
"return 'My name is David';" + 
"}");

this.WebNavegador.Document.Body.AppendChild(script);

Then you can execute and get the result with:

string myNameIs = (string)this.WebNavegador.Document.InvokeScript("GetNameFromBrowser");

I hope to be helpful


Here is a VB.Net example if you are trying to retrieve the value of a variable from within a page loaded in a WebBrowser control.

Step 1) Add a COM reference in your project to Microsoft HTML Object Library

Step 2) Next, add this VB.Net code to your Form1 to import the mshtml library:
Imports mshtml

Step 3) Add this VB.Net code above your "Public Class Form1" line:
<System.Runtime.InteropServices.ComVisibleAttribute(True)>

Step 4) Add a WebBrowser control to your project

Step 5) Add this VB.Net code to your Form1_Load function:
WebBrowser1.ObjectForScripting = Me

Step 6) Add this VB.Net sub which will inject a function "CallbackGetVar" into the web page's Javascript:

Public Sub InjectCallbackGetVar(ByRef wb As WebBrowser)
    Dim head As HtmlElement
    Dim script As HtmlElement
    Dim domElement As IHTMLScriptElement

    head = wb.Document.GetElementsByTagName("head")(0)
    script = wb.Document.CreateElement("script")
    domElement = script.DomElement
    domElement.type = "text/javascript"
    domElement.text = "function CallbackGetVar(myVar) { window.external.Callback_GetVar(eval(myVar)); }"
    head.AppendChild(script)
End Sub

Step 7) Add the following VB.Net sub which the Javascript will then look for when invoked:

Public Sub Callback_GetVar(ByVal vVar As String)
    Debug.Print(vVar)
End Sub

Step 8) Finally, to invoke the Javascript callback, add this VB.Net code when a button is pressed, or wherever you like:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    WebBrowser1.Document.InvokeScript("CallbackGetVar", New Object() {"NameOfVarToRetrieve"})
End Sub

Step 9) If it surprises you that this works, you may want to read up on the Javascript "eval" function, used in Step 6, which is what makes this possible. It will take a string and determine whether a variable exists with that name and, if so, returns the value of that variable.


You can always use a "DocumentStream" or "DocumentText" property. For working with HTML documents I recommend a HTML Agility Pack.


What you want to do is use Page.RegisterStartupScript(key, script) :

See here for more details: http://msdn.microsoft.com/en-us/library/aa478975.aspx

What you basically do is build your javascript string, pass it to that method and give it a unique id( in case you try to register it twice on a page.)

EDIT: This is what you call trigger happy. Feel free to down it. :)


i use this:

webBrowser.Document.InvokeScript("execScript", new object[] { "alert(123)", "JavaScript" })

If you need to inject a whole file then you can use this:

With Browser.Document
   Dim Head As HtmlElement = .GetElementsByTagName("head")(0)
   Dim Script As HtmlElement = .CreateElement("script")
   Dim Streamer As New StreamReader(<Here goes path to file as String>)
   Using Streamer
       Script.SetAttribute("text", Streamer.ReadToEnd())
   End Using
   Head.AppendChild(Script)
   .InvokeScript(<Here goes a method name as String and without parentheses>)
End With

Remember to import System.IO in order to use the StreamReader. I hope this helps.

참고URL : https://stackoverflow.com/questions/153748/how-to-inject-javascript-in-webbrowser-control

반응형