Skip to content

Accessing Context

pablocar80 edited this page Feb 25, 2021 · 3 revisions

It's possible to access the Document object that represents the user's page.

using Integrative.Lara;

internal class DocumentContextExample : WebComponent
{
    const string IconId = "MyIconElement";

    public DocumentContextExample()
    {
        ShadowRoot.Children = new Element[]
        {
            new HtmlDivElement
            {
                InnerText = "Check the title and icon of this webpage"
            }
        };
    }

    // OnConnect = component placed on web page
    protected override void OnConnect()
    {
        base.OnConnect();
        var icon = Document.GetElementById(IconId);
        if (icon != null) return;
        Document.Head.AppendChild(new HtmlLinkElement
        {
            Id = IconId,
            Rel = "icon",
            HRef = "https://stackoverflow.com/favicon.ico",
        });
        Document.Head.AppendChild(new HtmlTitleElement
        {
            InnerText = "Hello title",
        });
    }
}

Similarly, ASP.NET Core's HttpContext instance is available through LaraUI.Context.Http:

using Integrative.Lara;

internal class HttpContextExample : WebComponent
{
    private string _message;
    public string Message { get => _message; set => SetProperty(ref _message, value); }

    public HttpContextExample()
    {
        ShadowRoot.Children = new Element[]
        {
            new HtmlDivElement()
                .Bind(this, x => x.InnerText = Message)            
        };
    }

    protected override void OnConnect()
    {
        base.OnConnect();
        Message = $"Your IP is {LaraUI.Context.Http.Connection.RemoteIpAddress}";
    }
}
Clone this wiki locally