此文章針對已經搭建好jenkins和會使用iconfont圖標庫而寫。
主要目標就是在不通過更改html文件,完成頁面交互圖標信息,因為美工最多可以上傳代碼並且自動發布,並不會在Html中加入我們想要通訊的代碼。
*看一下最后的總結
*看一下最后的總結
*看一下最后的總結
有用的內容說三遍
應用場景:
當我雙擊任意一個圖標的時候,應該把圖標的class返回到主頁面上,並且綁定數據
具體實現步驟。
1.頁面嵌入iframe 。
略過。。
<iframe class="ContentIfm" :src="Path + type + file"></iframe>
2.確定postMessage 生效。
圖標頁面需要生效的代碼
var length = document.getElementsByClassName('iconfont').length
for (var i = 0; i < length; i++) {
document.getElementsByClassName('iconfont')[i].ondblclick = function() {
//具體想要返回什么值,可以自己修改js
var iconClass = this.parentNode.lastElementChild.innerText.split('.icon-')[1]
var iconName = this.parentNode.children[1].innerText
window.parent.postMessage(iconClass, '*')
alert('已經選中圖表為 : < ' + iconName + ' >, 已返回' + iconClass)
}
}
主頁面需要生效的代碼
mounted() {
const _this = this window.addEventListener('message', function(rs) { _this.$emit('getIcon', rs.data) }) }
此時在頁面中雙擊任何一個圖標就已經可以返回你所需要的值了
3.在主頁面中,通過js,向iframe嵌入js代碼,使postMessage生效
const ifrm = document.getElementsByClassName('ContentIfm')[0].contentDocument
const script = ifrm.createElement('script') script.innerHTML = ` if (window.getEventListeners(document.getElementsByClassName('iconfont')[0]).dblclick === undefined) { var length = document.getElementsByClassName('iconfont').length for (var i = 0; i < length; i++) { document.getElementsByClassName('iconfont')[i].ondblclick = function() { var iconClass = this.parentNode.lastElementChild.innerText.split('.icon-')[1] var iconName = this.parentNode.children[1].innerText window.parent.postMessage(iconClass, '*') alert('已經選中圖表為 : < ' + iconName + ' >, 已返回' + iconClass) } } } ` ifrm.body.appendChild(script)
此時,js已經成功嵌入iframe中,並且可以得到返回得到的數據。
總結一下:
一共有兩個技術點。
一: 頁面的postMessage通訊
子頁面使用代碼
data: 將要發送到其他 window的數據。
* :指定哪些窗口接受消息
window.parent.postMessage('返回信息', '*')
父頁面使用的代碼
rs: 返回的序列化數據
const _this = this
window.addEventListener('message', function(rs) { alert(rs.data) })
PostMessage 說明: https://developer.mozilla.org/zh-CN/docs/Web/API/Window/postMessage
二: 向iframe中插入代碼
思路就是用
用js給iframe 的body 用createElement創建script標簽,然后appendChild到iframe中
const ifrm = document.getElementsByClassName('ContentIfm')[0].contentDocument
const script = ifrm.createElement('script')
script.innerHTML = `alert('寫啥啥好使')`
ifrm.body.appendChild(script)