简体   繁体   中英

Getting return value from Javascript in C# Webbrowser control WPF

I made JavaScript injection into WebBrowser control in C# (System.Windows.Controls.WebBrowser) such that, <C#>

IHTMLDocument2 webdoc = (IHTMLDocument2)webBrowser1.Document;
string var = File.ReadAllText("C:/.../Resources/script.txt");
object retVal = webdoc.parentWindow.execScript(var, "Jscript");

and the JavaScript file script.txt is,

var headID = document.getElementsByTagName('head')[0];
var newScript = document.createElement('script');
newScript.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js'
headID.appendChild(newScript)

$('body').bind('click',function(e){
    var domsArray = [];
    for (var i = 0; i < 15; i++){
        for (var j = 0; j < 15; j++){
            if (document.elementFromPoint(e.clientX+i, e.clientY+j) && (jQuery.inArray(document.elementFromPoint(e.clientX+i, e.clientY+j), domsArray) < 0)){
            domsArray.push(document.elementFromPoint(e.clientX+i, e.clientY+j));
            }if (document.elementFromPoint(e.clientX-i, e.clientY+j) && (jQuery.inArray(document.elementFromPoint(e.clientX-i, e.clientY+j), domsArray) < 0)){
            domsArray.push(document.elementFromPoint(e.clientX-i, e.clientY+j));
            }if (document.elementFromPoint(e.clientX+i, e.clientY-j) && (jQuery.inArray(document.elementFromPoint(e.clientX+i, e.clientY-j), domsArray) < 0)){
            domsArray.push(document.elementFromPoint(e.clientX+i, e.clientY-j));
            }if (document.elementFromPoint(e.clientX-i, e.clientY-j) && (jQuery.inArray(document.elementFromPoint(e.clientX-i, e.clientY-j), domsArray) < 0)){
            domsArray.push(document.elementFromPoint(e.clientX-i, e.clientY-j));
        }}}
for (var p = 0; p < domsArray.length; p++){
    alert(domsArray[p].href);
}});

What it does is, whenever a user clicks on any point in webbrowser page, it collects the href near around that point.

I wanted to return the href array, to my C# so that I can create buttons with those links.

However, when I tried,

Console.WriteLine(retVal);

It didn't print anything on console. Even after I cast them into things like string or int with other dummy return values, it didn't print anything. Am I getting correct return? Is there any way that I can test the output return from javascript?

I think this could be a scope issue. Have you tried moving the

var domsArray = [];

outside the (above) the

$('body').bind('click',function(e){  .... 

function? such as

var domsArray = [];
$('body').bind('click',function(e){

    for (var i = 0; i < 15; i++){  < ... etc ....>

also I think you are missing a couple of semicolons (lines 3 & 4 of script.txt) though that probably shouldn't make a difference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM