我有两个域名。一个用于销售产品,即https://sellproducts.com,另一个用于产品文档,即https://docs.product.wiki
在https://sellproducts.com中,我有一个名为docs (https://sellproducts.com/docs)的页面,我使用iframe从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,这是可能的。
下面是你需要的逻辑:
- 创建/获取iframe元素->document.createElement
- 解析URL ->URLSearchParams
- 捕捉iframe的click事件link ->createEventListener
- 管理主窗口位置->窗口。top和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();
});
});
感谢反馈:)