单击Iframe中的链接时,使用历史记录pushState更改父窗口的URL

时间:2016-02-20 03:28:04

标签: javascript jquery iframe

我的页面有一个标题和侧边栏,右侧内容面板是一个iframe。

在加载到右侧内容面板的页面中,我尝试使用单击链接将父窗口中的浏览器URL更新为加载到Iframe中的新页面的URL。

我不希望实际的父窗口重新加载URL,而只是更新地址栏中的URL。

类似的东西:

window.history.pushState('obj', 'newtitle', '/bookmarks/list/');

这可能来自iframe吗?

3 个答案:

答案 0 :(得分:2)

使用Window.postMessage()的其他解决方案。

I帧:

<a href="/test">/test</a>
<a href="/test2">/test2</a>

<script>
Array.from(document.querySelectorAll('a')).forEach(el => {
  el.addEventListener('click', event => {
    event.preventDefault();
    window.parent.postMessage(this.href, '*');
  });
});
</script>

主页:

Current URL: <div id="current-url"></div>
<iframe src="iframe-url"></iframe>

<script>
const $currentUrl = document.querySelector('#current-url');
$currentUrl.textContent = location.href;

window.addEventListener('message', event => {
  history.pushState(null, null, event.data);
  $currentUrl.textContent = event.data;
});
</script>

请参阅demo on JS Fiddle

答案 1 :(得分:1)

我能够使用history.pushState更新地址栏中的父窗口URL,方法是使用postMessage从父窗口向父窗口发送新URL,并在父窗口中侦听此事件。

当父级收到子iframe postMessage事件时,它会使用该消息中传递的URL使用pushSTate更新URL。

儿童iframe

<script>
// Detect if this page is loaded inside an Iframe window
function inIframe() {
    try {
        return window.self !== window.top;
    } catch (e) {
        return true;
    }
}

// Detect if the CTRL key is pressed to be used when CTRL+Clicking a link
$(document).keydown(function(event){
    if(event.which=="17")
        cntrlIsPressed = true;
});
$(document).keyup(function(){
    cntrlIsPressed = false;
});
var cntrlIsPressed = false;

// check if page is loaded inside an Iframe?
if(inIframe()){
    // is the CTRL key pressed?
    if(cntrlIsPressed){
        // CTRL key is pressed, so link will open in a new tab/window so no need to append the URL of the link
    }else{

        // click even on links that are clicked without the CTRL key pressed
        $('a').on('click', function() {

            // is this link local on the same domain as this page is?
            if( window.location.hostname === this.hostname ) {

                // new URL with ?sidebar=no appended to the URL of local links that are clicked on inside of an iframe
                var linkUrl = $(this).attr('href');
                var noSidebarUrl = $(this).attr('href')+'?sidebar=no';

                // send URL to parent window
                parent.window.postMessage('message-for-parent=' +linkUrl , '*');

                alert('load URL with no sidebar: '+noSidebarUrl+' and update URL in arent window to: '+linkUrl);

                // load Iframe with clicked on URL content
                //document.location.href = url;
                //return false;
            }
        });
    }
}
</script>

父窗口

<script>

// parent_on_message(e) will handle the reception of postMessages (a.k.a. cross-document messaging or XDM).
function parent_on_message(e) {
    // You really should check origin for security reasons
    // https://developer.mozilla.org/en-US/docs/DOM/window.postMessage#Security_concerns
    //if (e.origin.search(/^http[s]?:\/\/.*\.localhost/) != -1
    //    && !($.browser.msie && $.browser.version <= 7)) {
        var returned_pair = e.data.split('=');
        if (returned_pair.length != 2){
            return;
        }
        if (returned_pair[0] === 'message-for-parent') {
            alert(returned_pair[1]);
            window.history.pushState('obj', 'newtitle', returned_pair[1]);
        }else{
            console.log("Parent received invalid message");
        }

    //}
}

jQuery(document).ready(function($) {
    // Setup XDM listener (except for IE < 8)
    if (!($.browser.msie && $.browser.version <= 7)) {
        // Connect the parent_on_message(e) handler function to the receive postMessage event
        if (window.addEventListener){
            window.addEventListener("message", parent_on_message, false);
        }else{
            window.attachEvent("onmessage", parent_on_message);
        }
    }
});
</script>

答案 2 :(得分:0)

无论是否使用History API,这里的东西都可以检测iframe的URL更改。

setInterval(function() {

    var iframeUrl = document.getElementById("the-iframe").contentWindow.location.href;

    if (window.lastIframeUrl !== iframeUrl) {
        console.log("iframe url changed", iframeUrl);
        window.lastIframeUrl = iframeUrl
    }

}, 100)