1. 程式人生 > 其它 >修改iframe裡的css樣式及跨域問題

修改iframe裡的css樣式及跨域問題

前段時間給一個客戶製作網站線上客服的時候遇到一個問題,客戶想盡量美化一下客服的框,而我們研究發現,客服框其實是iframe引用的外部資源。開始我們也天真地以為,自己寫段程式碼,再優化一下css就可以完美實現客戶想要的效果了,其實不然。
工作中總能遇到 引用別人的頁面,就會帶來很多問題,比如iframe中的樣式不滿足我們的需求,這就需要修改iframe中的樣式。

下面我們做一個修改 iframe 中樣式的 Demo:
知識點:

let test = document.getElementById('引用的iframeId').contentWindow.document.getElementById('修改樣式的Id');
test.style.width = "200px";

第1步:建立一個setIframeStyle資料夾

第2步:在setIframeStyle資料夾中建立 A.html 和 B.html

2.1: A.html檔案

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" />
<script>
window.onload = function () {
var test =
document.getElementById('frame').contentWindow.document.getElementById('cc');
test.style.background = "#333";
}
</script>
</head>
<body>
<div>
這是 第一個 網頁
</div>
<iframe src="2.html" frameborder="0" id="frame" width="100%" height="100%"></iframe>
</body>
</html>

2.2: B.html檔案

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" />
</head>
<body>
<div id="cc">
這是 2 網頁
</div>
</body>
</html>

iframe 中的 背景變成 灰色了 到了這一步就算成功了!

----------------但是,iframe引用網路資源則不行----------------

不是所有的頁面都是引用本地的,如果網路資源,比如百度呢?接下來說說引用網路資源!

1、將A.html中 iframe 的 src 屬性 修改為 www.baidu.com

<iframe src="https://www.baidu.com/" frameborder="0" id="frame" width="100%" height="800px"></iframe>

執行 A.html 發現報錯了

原因: 瀏覽器有一個同源策略限制

第一種: 限制就是不能通過 ajax 的方法去請求不同源的文件。

第二種: 限制是不同瀏覽器中不同域的 iframe 之間是不能進行js的互動操作的。

我們修改下 A.html中 程式碼 :

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" />
<script>
</script>
</head>
<body>
<div>
這是 第一個 網頁
</div>
<iframe src="https://www.baidu.com/" frameborder="0" id="frame" width="100%" height="400px"></iframe>
</body>
<script>
window.onload = function () {
var test =
document.getElementById('frame').contentWindow//.document.getElementById('cc');
console.log(test)
// test.style.background = "#333";
}
</script>
</html>

下面 是 輸出 test 的結果

子域 window 幾乎沒有 有價值東西, document 根本不存在,此問題有兩種方式解決
1、值得注意的是, 不同源的東西,是不可進行 js 互動的
2、 利用 postMessage函式,進行子域與父域通訊(前提是必須同域,本例子中,你得有百度的管理許可權,可能嗎?)

var frame = document.getElementById('your-frame-id');
frame.contentWindow. postMessage (data, '*');
data可以是string,boolean,number,array,object
在iframe子頁面
window. addEventListener ('message', function(event) {
//event.data獲取傳過來的資料
});

總結來說:frame如果是同域下的內容,修改css樣式簡簡單單,而如果是跨域了的話,則需要另當別論

參考:https://letus.top/archives/27.html