문제

나는 이것을 시도했다 :

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) DoS는 Parses이며 STR로 작성된 내용을 실행합니다. 확인하다 W3Schools 참조.

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

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

당신이 정말로 원하는 것은 JavaScript를 실행하는 것입니다. 이것은 가장 쉬운 (vb .net)입니다.

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

나는 이것이 "주입"하지 않을 것이라고 생각하지만, 그것이 당신이 뒤 따르는 것이라면 당신의 기능을 실행할 것입니다. (문제를 과도하게 복제 한 경우를 대비하여) JavaScript를 주입하는 방법을 알아낼 수 있다면이를 기능의 본문에 넣고 JavaScript가 주입을하게하십시오.

HTML 문서의 관리 래퍼는 필요한 기능을 완전히 구현하지 않으므로 원하는 것을 달성하려면 MSHTML API에 담아야합니다.

1) MSHTML에 대한 참조를 추가하여 "Microsoft HTML Object Library"라고 불러옵니다. com 참조.

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

3) 스크립트 요소의 IHTMLELEMENT를 참조하십시오.

IHTMLElement iScriptEl = (IHTMLElement)scriptEl.DomElement;

4) "AfterBegin"의 첫 번째 매개 변수 값으로 InsertAdJacentText 메소드를 호출하십시오. 가능한 모든 값이 나열됩니다 여기:

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

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

HTH, 리차드

에 대한 후속 조치로 받아 들여진 답변, 이것은 최소한의 정의입니다 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; }
}

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

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"메소드를 호출하는 것입니다.

이 예에서는 JavaScript 코드가 글로벌 범위에서 주입 및 실행됩니다.

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

실행을 지연 시키려면 기능을 주입하고 다음에 전화하십시오.

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

이것은 Windows 양식 및 WPF Webbrowser 컨트롤에 유효합니다.

"execscript"는 IE 및 Chrome에서만 정의 되므로이 솔루션은 크로스 브라우저가 아닙니다. 그러나 문제는 Microsoft Webbrowser 컨트롤에 관한 것이며 IE는 유일한 지원입니다.

유효한 크로스 브라우저 방법으로 JavaScript 코드를 주입하려면 새 키워드로 기능 객체를 만듭니다. 이 예제는 주입 된 코드가있는 익명 함수를 생성하고이를 실행합니다 (JavaScript는 폐쇄를 구현하고 함수는 로컬 가변 오염없이 글로벌 공간에 액세스 할 수 있습니다).

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

물론 실행을 지연시킬 수 있습니다.

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

도움이되기를 바랍니다

나는 이것을 사용했다 : d

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

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

그런 다음 실행하고 결과를 얻을 수 있습니다.

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

도움이되기를 바랍니다

웹 브라우저 컨트롤에로드 된 페이지 내에서 변수 값을 검색하려는 경우 vb.net 예제입니다.

1 단계) 프로젝트에서 Microsoft HTML 객체 라이브러리에 COM 참조 추가

2 단계) 다음 으로이 vb.net 코드를 Form1에 추가하여 MSHTML 라이브러리를 가져옵니다.
MSHTML을 가져옵니다

3 단계) "Public Class Form1"라인 위에이 vb.net 코드를 추가하십시오.
u003CSystem.Runtime.InteropServices.ComVisibleAttribute(True)>

4 단계) 프로젝트에 웹 브라우저 컨트롤 추가

5 단계)이 vb.net 코드를 Form1_load 함수에 추가하십시오.
webbrowser1.objectforscripting = me

6 단계) 웹 페이지의 JavaScript에 "CallbackgetVar"함수를 주입하는이 vb.net sub를 추가하십시오.

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

7 단계) JavaScript가 호출 할 때 다음 vb.net 하위를 추가하십시오.

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

8 단계) 마지막으로 JavaScript 콜백을 호출하려면 버튼을 누르거나 원하는 곳 에서이 vb.net 코드를 추가하십시오.

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

9 단계) 이것이 효과가 있다는 것을 놀라게한다면, 6 단계에서 사용되는 JavaScript "Eval"함수를 읽을 수 있습니다. 이것이 가능합니다. 문자열이 필요하고 변수가 해당 이름에 존재하는지 여부를 결정하고 그렇다면 해당 변수의 값을 반환합니다.

언제든지 "DocumentSream"또는 "DocumentText"속성을 사용할 수 있습니다. HTML 문서로 작업하려면 a를 추천합니다 HTML 민첩성 팩.

당신이하고 싶은 것은 page.registerstartupscript (키, 스크립트)를 사용하는 것입니다.

자세한 내용은 여기를 참조하십시오. http://msdn.microsoft.com/en-us/library/aa478975.aspx

기본적으로하는 일은 JavaScript 문자열을 빌드하고 해당 방법으로 전달하고 고유 한 ID를 제공하는 것입니다 (페이지에 두 번 등록하려는 경우).

편집 : 이것은 당신이 Trigger Happy라고 부르는 것입니다. 자유롭게 다운하십시오. :)

나는 이것을 사용한다 :

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

전체 파일을 주입 해야하는 경우 다음을 사용할 수 있습니다.

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

가져 오는 것을 잊지 마십시오 System.IO 사용하기 위해 StreamReader. 이게 도움이 되길 바란다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top