Search code examples
dotnetbrowser

Execute javascript inside iframe document


I am trying to execute javascript which is inside an iframe document using Dotnetbrowser 1.11.

In the following code returnValue.IsFunction() returns false.

JSValue returnValue = browser.ExecuteJavaScriptAndReturnValue(FunctionName);

if (returnValue.IsFunction){//something}

ExecuteJavaScript works fine if the script is in the current loaded document. But when the script is loaded in an iframe document which is inside the current loaded document, the same is not found.

Please assist regarding the same.


Solution

  • ExecuteJavaScriptAndReturnValue() method has an override which allows executing JavaScript code in a specific frame by using its id number. To get a list of child frames ids on a currently loaded document you can use Browser.GetFramesIds() method. Here is a code sample:

    browser.FinishLoadingFrameEvent += (s, e) =>
    {
        if (e.IsMainFrame)
        {
            List<long> framesIds = e.Browser.GetFramesIds();
            JSValue returnValue =
                e.Browser.ExecuteJavaScriptAndReturnValue(framesIds.First(), FunctionName);
    
            if (returnValue.IsFunction){//something}
        }
    };
    

    Take into account that Browser.GetFramesIds() should be used after completely page loading, either the list will contain only already loaded ids.