0

I've created a fully customizable audio player widget with the intent that people can embed it in their blog posts (such as wordpress) by including an <iframe> tag like so:

<iframe id=“my_widget” width="800px" height="100%" scrolling="no" frameborder="no" allow="autoplay" src="http://mywebsite.com/player?audio_id=xxxxxxx">
</iframe>

The widget includes a few buttons for the purpose of sharing the article to facebook, twitter, and copying the blog url to the clipboard. When I tested my widget by embedding it in a page on my website, all of the buttons worked as expected. However, when I embedded the widget in a wordpress post, clicking on the share buttons gives me this javascript error:

Uncaught DOMException: Blocked a frame with origin "http://mywebsite.com" from accessing a cross-origin frame.
at shareFacebook (http://mywebsite.com/player?audio_id=xxxxxxx:172:46)
at HTMLButtonElement.onclick (http://mywebsite.com/player?audio_id=xxxxxxx:38:123)

My logic for redirecting the user to facebook for sharing the post (in my widget code) looks like this:

<button class="share-fb-button-sm" onclick="shareFacebook();">

<script>
    function shareFacebook() {
        var currentURL = window.top.location.href;
        window.top.location.href = "https://www.facebook.com/sharer/sharer.php?u=" + currentURL;
    }
</script>

I understand that this javascript error is telling me that my attempt at redirection is being blocked by the Same-Origin Policy. But I've definitely seen other iframe widgets do what I'm trying to do. What is the proper course of action here? I can't seem to figure out how everyone else is doing this.

Michael
  • 615
  • 6
  • 21

1 Answers1

0

Thank you for the suggestion Jimmy Leahy, I didn't know about window.open(). That partly fixed my problem. After some more research I discovered document.referrer(). Accessing location.href from an iframe is blocked by the same-origin policy, but document.referrer() is not. This function will return the url that called the iframe, which ends up being the parent url. Here's how I implemented my solution.

<button class="share-fb-button-sm" onclick="shareFacebook();">

<script>
    function shareFacebook() {
        var currentURL = document.referrer;
        window.open("https://www.facebook.com/sharer/sharer.php?u=" + currentURL);
    }
</script>
Michael
  • 615
  • 6
  • 21