Allowing two sites to communicate to know the current URL of an iframe

问题: I'm trying to figure out a solution to allow an website to know what URL the user is on through an iframe. Website 1: http://website.website.com (Remote Website, can only...

问题:

I'm trying to figure out a solution to allow an website to know what URL the user is on through an iframe.

Website 1: http://website.website.com (Remote Website, can only add javascript & html to the webpage)

Website 2: https://example.com (Fully Editable, php, html, js.. etc)

Current Code: (Of Website 2 (Example.com)

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US" prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb#">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>Website.com</title>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body class="body_blank">
    <script type="text/javascript">

        jq = jQuery.noConflict();

        jq(document).ready(function() {

            var currentFramePath = '';
            var iframe = '<iframe src="{src}" id="#iFrameContainer" style="position:fixed; top:0px; bottom:0px; right:0px; width: 100%; border: none; margin:0; padding:0; overflow: hidden; z-index:999999; height: 100%;">';

            var urlFrame = getUrlParameter('currentFrame');

            if(urlFrame != null && urlFrame != ''){
                console.log("Frame not found");
                jq('#iFrameContainer').html(iframe.replace('{src}', urlFrame));
                currentFramePath = urlFrame;
            }

            jq('#iFrameContainer').click(function(){
                console.log("Clicked in frame");
                currentFramePath = jq(this).attr('href');
                console.log(currentFramePath);
            });

            setInterval(function(){
                window.location = window.location.href.split('?')[0] + '?currentFrame=' + currentFramePath;
                console.log("Update Query");
            }, 5000);

        });

        function getUrlParameter(sParam) {
            var sPageURL = decodeURIComponent(window.location.search.substring(1)),
                sURLVariables = sPageURL.split('&'),
                sParameterName,
                i;
            console.log("Get Query");   
            for (i = 0; i < sURLVariables.length; i++) {
                sParameterName = sURLVariables[i].split('=');

                if (sParameterName[0] === sParam) {
                    return sParameterName[1] === undefined ? true : sParameterName[1];
                }
            }
        };
    </script>
    <div id="wrapper" class="wrapper_blank">
        <iframe src="http://website.website.com" id="#iFrameContainer" style="position:fixed; top:0px; bottom:0px; right:0px; width: 100%; border: none; margin:0; padding:0; overflow: hidden; z-index:999999; height: 100%;">
    </div>
</body>
</html>

Problem

If I refresh the page (iframe) on example.com it refreshes and forgets the page that the user is/was on...

As you can see I have attempted to get it working by detecting their page through an iFrame however this is impossible due to it being on a different domain.

Solution?

I'm looking for some sort of solution to do something like described below, bare in mind there could be a better solution.

I want the website website.website.com to get the current path / url of the page the user is on (which is being viewed through an iframe) and for it to send this path/url through to example.com then example.com would update the session / temporary cookie / temporary local storage / variable... etc which would then mean it would adjust the query string to point itself to the correct URL for when the user refreshes their page resulting in the refresh correctly remembering the page they were on.

Attempt

I tried to use the postMessage function by putting the follow code on their respective sites:

Website 1 Extra Code

<script type="text/javascript">
    setInterval(function() {
        parent.postMessage(window.location.pathname, "https://website.com");
    },1000);
</script>

Website 2 Extra Code:

var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";

eventer(messageEvent, function(e) {
    console.log('Parent Message: ', e.data);
}, false);

However nothing happens, no console messages or errors... just nothing.

I've even tried copying the likes of https://blog.teamtreehouse.com/cross-domain-messaging-with-postmessage but nothing in that helped :(

Any ideas what I am doing wrong and a way to resolve it to achieve this?

Thanks

Edits

I've tried the following js inside http://website.website.com but it didn't work:

localStorage.setItem('CurrentURLChecker', window.location.href)

if (localStorage.getItem('CurrentURLChecker')) {
    if (window.parent.location.href == "https://website.com/" ) {
        console.log("URL FOUND");
    }
}

Uncaught DOMException: Blocked a frame with origin "http://website.website.com" from accessing a cross-origin frame at http://website.website.com/:251:44

EDIT - An example

Website 1 = "http://stackoverflow.serviceprovider.com"

Website 2 = "https://stackoverflow.com"

Website 2 contains an iframe which shows the exactly what Website 1 shows.

I am never going to visit Website 1, all clicks are done on Website 2

If I was to click on a link inside the iframe and it was to navigate to: http://stackoverflow.serviceprovider.com/this-new-page/ then Website 1 should be able to detect this and store the iframes location and remember it.

Now if I refresh my browser instead of the iframe loading http://stackoverflow.serviceprovider.com it would instead load the page they actually refreshed which is http://stackoverflow.serviceprovider.com/this-new-page/

The tab/window URL will always stay on https://stackoverflow.com/ but it would be a necessity to append a query string so the links can be made sharable.

It's that simple.


回答1:

Since you can add javascript to the website 1 (http://website.website.com) you could create a session with javascript and save the current page the user visits in the cookies (as described here). When the user visits the home page of website on (which is happening, when the user reloads the website 2) you could get this value with javascript and load the saved page (window.location.href = 'http://website.website.com/YourSavedPage').

If you don't want that redirection every time the user visits the home page of website 1, you could think about creating a own page to redirect the user to the last opened page and to open that page once, when the iframe is loaded.


回答2:

For security reasons, you can only get the url for as long as the contents of the iframe, and the referencing javascript, are served from the same domain.

If the two domains are mismatched, you'll run into cross site reference scripting security restrictions.


回答3:

It seems like the targetOrigin (second argument of postMessage) may simply not match. Do not forget that the protocol, host & port must all be an exact match.

From the markup you posted, the iframe src domain is http://website.website.com while the parent domain is https://example.com.

If you wish for http://website.website.com to communicate it's URL to https://example.com then posting a message from the iframe should read:

window.parent.postMessage(window.location.pathname, 'https://example.com');

To make sure that the targetOrigin filter is not what's causing communication issues you can also use * for testing.

It seems that you are doing the opposite in your example (passing source domain instead of target domain) and it's also very misleading that you use "website 1" to reference the embedded site and "website 2" to reference the parent site in your explanation: I would expect the opposite.

  • 发表于 2019-03-23 01:04
  • 阅读 ( 293 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除