我有兩個域。一個用于銷售產品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”。
uj5u.com熱心網友回復:
如果你可以在兩邊放一些js,那是可能的。
按順序,您需要的邏輯是:
- 創建/獲取 iframe 元素 -> document.createElement
- 決議 URL -> URLSearchParams
- 在 iframe 的鏈接上捕獲點擊事件 -> createEventListener
- 管理主視窗位置 -> window.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();
});
});
反饋贊賞:)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/334632.html
標籤:javascript html 查询 内嵌框架
