URL encoding for document.location.href

18,673

Solution 1

the encodeURIComponent function will do what you want.

<script type="text/javascript">
document.write("<iframe src='http://www.facebook.com/plugins/like.php?href=" + encodeURIComponent( document.location.href ) + "&layout=standard&show_faces=false&action=like&font=verdana&colorscheme=light' frameborder=0></iframe>");
</script>

Solution 2

Facebook like buttons double encode the page uri of the target page so the way to get what you're looking for is...

encodeURIComponent(encodeURIComponent( document.location.href ))

Oh those wacky FB guys.

Share:
18,673
Tyler
Author by

Tyler

Updated on June 04, 2022

Comments

  • Tyler
    Tyler almost 2 years

    I am building an iFrame and am using document.location.href -> my exact code is:

    <script type="text/javascript">
    document.write("<iframe src='http://www.facebook.com/plugins/like.php?href=" + document.location.href + "&layout=standard&show_faces=false&action=like&font=verdana&colorscheme=light' frameborder=0></iframe>");
    </script>
    

    This is working great for all of my pages except one. I believe the issue with the one page is caused by a dash "-" being in the page name. My questions is - is there a way to encode my src differently so that the link works? The CORRECT URL I want it to pull is:

    []/products/Product%252dExample.html

    But what it IS pulling in is:

    []/products/Product-Example.html

    And this is causing the page to not work correctly.

    Thanks!