Search code examples
javascripthtmlvk

Show widget only on specific url


I have a script in the footer of a site. I want the widget to be shown if url contains 'mystring', and if not, then not to be shown

<script>
    if (window.location.href.indexOf("mystring") > -1) {
        <script type="text/javascript" src="https://vk.com/js/api/openapi.js?169"></script>
        <!-- VK Widget -->
        <div id="vk_community_messages"></div>
        <script type="text/javascript">
        if($(window).width()>800) { 
        VK.Widgets.CommunityMessages("vk_community_messages", 203651941, {expandTimeout: "20000",tooltipButtonText: "Any Question?"});
        }
        if($(window).width()<=800) {
        VK.Widgets.CommunityMessages("vk_community_messages", 203651941, {tooltipButtonText: "Any Question?"});
        }}
</script>

This code produces the following errors:

Uncaught SyntaxError: Unexpected identifier (string 3)

Uncaught SyntaxError: Unexpected token '}' (string 12)


Solution

  • You've got <script> tags and other HTML inside the outer <script> tags, that simply isn't allowed and isn't ever going to work. This is a fairly basic thing you should have learned when first learning about HTML and JavaScript.

    This will make more sense (I can't test it easily so no guarantees it will work exactly, but it certainly won't have any fundamental design flaws or syntax errors, so it should point you down the right road):

    <div id="vk_community_messages"></div>
    
    <script type="text/javascript" src="https://vk.com/js/api/openapi.js?169"></script>
    <script>
        if (window.location.href.indexOf("mystring") > -1) {
            if($(window).width()>800) { 
              VK.Widgets.CommunityMessages("vk_community_messages", 203651941, {expandTimeout: "20000",tooltipButtonText: "Any Question?"});
            }
    
            if($(window).width()<=800) {
              VK.Widgets.CommunityMessages("vk_community_messages", 203651941, {tooltipButtonText: "Any Question?"});
            }
        }
    </script>