Informat
Informat

Reputation: 858

cefSharp ChromiumWebBrowser size to page content

Do you know how to make it so that when the ChromiumBrowser is opened, the browser sizes to contents? Right now this xaml is found in the body of a Window. When someone clicks on the text of MyTextBox, the ChromiumBrowser opens to show more information.

Edit: The chromium window doesn't show without the fixed width and height.

....
<Canvas Panel.ZIndex="99" Visibility="{Binding IsChromiuimVisible, Converter={StaticResource BooleanToVisibilityConverter}, FallbackValue=Collapsed}">
<Popup Placement="Top" PlacementTarget="{Binding ElementName=MyTextBlock}"
    IsOpen="{Binding IsChromiumVisible}" PopupAnimation="Fade" AllowsTransparency="True"
    MouseEnter="OnMouseEnter" MouseLeave="OnMouseLeave">
    <Grid Background="Transparent">
        <cefSharp:ChromiumWebBrowser
                 Width="300" Height="620"
              Address="{Binding ChromiumAddress, Mode=TwoWay}">
        </cefSharp:ChromiumWebBrowser>
    </Grid>
</Popup>
</Canvas>
....

Upvotes: 7

Views: 6175

Answers (1)

I have solved the problem of fitting the cefSharp browser height to page content in the following way:

browser = new ChromiumWebBrowser("https://stackoverflow.com/");
// ... adding to parent's children etc. ...

browser.LoadingStateChanged += async (s, e) =>
{
    if (!e.IsLoading) // browser.CanExecuteJavascriptInMainFrame == TRUE !
    {
        JavascriptResponse response = 
            await browser.EvaluateScriptAsync(
                // GET HEIGHT OF CONTENT
                "(function() {                       " +
                "  var _docHeight =                  " +
                "    (document.height !== undefined) " +
                "    ? document.height               " +
                "    : document.body.offsetHeight;   " +
                "                                    " +
                "  return _docHeight;                " +
                "}                                   " +
                ")();");

        int docHeight = (int)response.Result;
        browser.Dispatcher.Invoke(() => { browser.Height = docHeight + 10; });
    }
};

Upvotes: 5

Related Questions