blazorblazor-webassemblyasp.net-blazor

How to display google adsense ads with asp.net core blazor web assembly


I have a project running on blazor and I want to add google adsense ads on blazor but I don't find any solution to run google ads on blazor.

Please help me to setup the ads!


Solution

  • Check out this video!

    https://www.youtube.com/watch?v=GjLEVlUA7mY

    This has a very simple way of putting your add inside a component.

    You properly need to create a component.

    This is what I used in my project

     <div @key="@Guid.NewGuid()" >
     @if (Ads is not null)
     {
         @Ads
     }
     </div>
    
     @code {
    
        [Parameter]
        public string Slot { get; set; }
        [Parameter]
        public string Style { get; set; }
        [Parameter]
        public string Adsformat { get; set; } = "auto";
    
        private RenderFragment Ads { get; set; }
    
    
        protected override void OnParametersSet()
        {
            Ads = new RenderFragment(b =>
            {
                b.OpenElement(0, "ins");
                b.AddMultipleAttributes(1, new List<KeyValuePair<string, object>>()
                {
                    new KeyValuePair<string, object>("class", "adsbygoogle"),
                    new KeyValuePair<string, object>("style", $"{Style}"),
                    new KeyValuePair<string, object>("data-ad-client", "your-client-secure-code"),
                    new KeyValuePair<string, object>("data-ad-slot", Slot),
                    new KeyValuePair<string, object>("data-ad-format", Adsformat),
                    new KeyValuePair<string, object>("data-full-width-responsive", true),
                });
                b.CloseElement();
     
                b.OpenElement(0, "script");
                b.AddContent(3, "(adsbygoogle = window.adsbygoogle || []).push({});");
                b.CloseElement();
           });
       }
    }