Retrieving JavaScript return values in a C# WebBrowser control within a WPF application

I utilized JavaScript injection into WebBrowser control in C#

(System.Windows.Controls.WebBrowser)
to achieve, <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);
}});

This functionality triggers when a user clicks on any point within the webbrowser page, capturing the href links situated around that location.

The intention was to retrieve the href array back to my C# code to generate buttons with those URLs.

However, upon testing,

Console.WriteLine(retVal);

No output was displayed on the console. Regardless of attempts to convert them into string or int and use other placeholder values, there was no result printed. Is the return value being obtained correctly? Are there any methods available to inspect the JavaScript return output?

Answer №1

It appears there may be a scope issue at play here. Have you considered relocating the

var elementsArray = [];

outside of the (above) mentioned

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

function? Perhaps something like

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

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

Additionally, don't forget to add semicolons in a few places (lines 5 & 6 of script.js), although it may not affect the outcome significantly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Strategies for transferring information to a different component in a React application

Building a movie site where users can search for films, click on a card, and access more details about the film is proving challenging. The problem lies in transferring the film details to the dedicated details page once the user clicks on the card. An onc ...

What is the process for removing an added message using jQuery after it has been appended by clicking the same button?

https://i.stack.imgur.com/YsmKZ.pnghttps://i.stack.imgur.com/dW2lo.pngI have searched extensively through previously asked questions without success. My goal is to remove the previous appended message when the submit button is clicked again. This functiona ...

Leveraging the power of Map and Sort to display the items containing image URLs alongside their respective timestamps

I'm diving into firebase and utilizing react, and currently I've come across this snippet of code: {photos.map(url => ( <div key={url} style={card}> <img src={url} style={image} /> <div s ...

What is the most effective way to implement a single modal throughout my web application without having to duplicate HTML code on each page?

After realizing I was repetitively adding the same div to every page for a modal dialog, I decided to place a single div in the site.master page and call it when needed. This method worked fine until I began implementing ajax with partial page updates. H ...

Having trouble getting Firebase phone number authentication to work with Vue.js

I am currently in the process of developing a new Vue.js application using the Webpack template. Within this app, I have implemented a /sign-in route that displays a component named SignIn. To authenticate users, I am utilizing Firebase Phone Number authen ...

What are effective ways to eliminate script tags from a webpage?

I have implemented tags on my website that users can use to interact with the site. My goal is to figure out how to make the browser only read text from a specific file I write, without any HTML. This should be restricted to certain sections of my websit ...

Displaying that the response from ajax is experiencing issues

I am currently attempting to update the td elements in a table but my current method is not yielding successful results. Here's what I have tried: <table id="job1"> <tr><td></td></tr> <tr id="Jobstatus1"> ...

Japanese Character File Naming Convention

When dealing with certain Japanese characters, the content disposition header appears as follows: Content-Disposition: attachment; filename=CSV_____1-___.csv; filename*=UTF-8''CSV%E3%82%A8%E3%83%93%E3%83%87%E3%83%B3%E3%82%B91-%E3%82%B3%E3%83%94%E ...

Using regular expressions to extract the value of a specific key from a JavaScript object

After scraping a webpage with BeautifulSoup and requests, I came across this snippet of code within the HTML content: $create(Web.Scheduler, { "model": '{"apt":[0]}', "timeZone": "UTC", "_uniqueI ...

Having trouble importing a package into my React boilerplate

Having trouble importing the react-image-crop package with yarn and integrating it into a react boilerplate. Encountered an error after installing the package: Module parse failed: /Users/...../frontend/node_modules/react-image-crop/lib/ReactCrop.js Unex ...

Ways to retrieve a concealed DOM element from a background window

I have been struggling to display a button that is located in the background window using the jQuery code below, but unfortunately it's not functioning as expected. On my webpage, I have a hidden button that should only be visible when a user adds a ...

Help me understand how to display the data in a JSON array

{ "entries": [ { "id": 23931763, "url": "http://www.dailymile.com/entries/23931763", "at": "2013-07-15T21:05:39Z", "message": "I ran 3 miles and walked 2 miles today.", "comments": [], "likes": [], ...

Error in D3: stream_layers function is not defined

Utilizing nvd3.js to construct a basic stacked bar chart as detailed here I inserted the code provided in the link into an Angular directive like this: app.directive('stackBar', function() { return { restrict: 'A', ...

What is the process for updating the URL for specific functions within $resource in Angular?

Check out this code snippet: angular.module('app.posts.services', []).factory('Post', ['$resource', 'API_ENDPOINT', ($resource, API_ENDPOINT) => $resource(API_ENDPOINT, { id: '@id' }, { updat ...

Unraveling Vue Async Components - Harnessing the power of emitted events to resolve

I am looking to create a Vue async component that stays in a loading state until a custom event is triggered. This means it will render a specified loading component until the event occurs. Here's an example of how I want it to work: const AsyncComp ...

Learning how to toggle default snippet keywords on and off based on specific scenarios within the Angular Ace Editor

Within the Ace editor, I have incorporated custom snippets alongside the default ones. However, there are certain scenarios where I would like to exclusively display the custom snippets and hide the default ones. Is there a way to disable or conceal the ...

Spreading an object to remove a key may result in the returned value being

When creating a Radio Button object, each object in the array consists of {value: 1, text: 'Sometext'}. If a radio button is selected, 'selected: true' is added to that specific object and removed from the others. const onChoiceChange ...

What is causing .then() to not wait for the promise to resolve?

I'm currently delving into an Angular project, and I must admit, it's all quite new to me. My confusion lies in the fact that the .then() function doesn't seem to be waiting for the promises to resolve. Could this have something to do with ...

The JQuery CSS function is unable to alter the height of the element

I am working with a grid that contains various elements, each with the class item. When I click on one of these elements, I toggle the class expand to resize the element. <body> <div class="grid"> <a href="#"> < ...

Steps for organizing a particular key in a map

I need assistance sorting my map based on the "time" value, but so far, I haven't been successful in finding a solution after searching online extensively. If anyone has any insights or recommendations, please share them with me. This is how my Map ...