如何从iframe获取当前页面url并显示在浏览器上

How to get the current page url from iframe and display on the browser

我有两个域。一种用于销售 https://sellproducts.com and the other for product documentation that is https://docs.product.wiki

的产品

https://sellproducts.com i have page called docs ( https://sellproducts.com/docs) which i used iframe to call or display contents from https://docs.product.wiki

<iframe id="docs" src="https://docs.product.wiki/" frameborder="0">
</iframe>

https://docs.product.wiki有很多页的例子,

https://docs.product.wiki/intro.html

https://docs.product.wiki/about.hml

我想使用 javascript 或 jquery 从 iframe 中获取当前的 url 并在浏览器中显示为 " https://sellproducts.com/docs?page=intro",当一个页面被点击时打开或重新加载。

如果你能在两边放一些js就可以了。

按顺序,有你需要的逻辑:

  1. Create/Get iframe 元素 -> document.createElement
  2. 解析 URL -> URLSearchParams
  3. 在 iframe link -> createEventListener
  4. 上捕捉点击事件
  5. 管理主要 window 位置 -> window.top and window.location

以下可能是一个好的开始:

在您的 https://sellproducts.com/docs 上输入此代码:

window.onload = function(e) {
    const docsUrl = 'https://docs.product.wiki/';
    const queryString = window.location.search; //Parse URL to get params like ?page=
    let iframe;
    if(document.querySelector('iframe').length) //If iframe exit use it
        iframe = document.querySelector('iframe');
    else
        iframe = document.createElement('iframe'); //Create iframe element
    iframe.src = docsUrl; //Set default URL
    iframeframeBorder = 0; //Set frameborder 0 (optional)
    if (queryString !== '') {
        const urlParams = new URLSearchParams(queryString); //Convert to URLSearchParams, easy to manipulate after
        const page = urlParams.get('page'); //Get the desired params value here "page"
        iframe.src = docsUrl+page + '.html'; //Set iframe src example if ?page=intro so url is https://docs.product.wiki/intro.html
    }
    if(!document.querySelector('iframe').length)
        document.body.appendChild(iframe);//Append iframe to DOM
}

并且 https://docs.product.wiki 方将此代码放入您的全局模板中(必须在所有页面上):

let links = document.querySelectorAll('a'); //Get all link tag <a>
links.forEach(function(link) { //Loop on each <a>
    link.addEventListener('click', function(e) { //Add click event listener
        let target = e.target.href; //Get href value of clicked link
        let page = target.split("/").pop(); //Split it to get the page (eg: page.html)
        page = page.replace(/\.[^/.]+$/, ""); //Remove .html so we get page
        let currentHref = window.top.location.href; //Get the current windows location
        //console.log(window.location.hostname+'/docs?page='+page);
        window.top.location.href = 'https://sellproducts.com/docs?page='+page; //Set the current window (not the frame) location
        e.preventDefault();
    });
});

感谢反馈:)