Skip to content

Commit

Permalink
🐛修复误与react工具通信事故
Browse files Browse the repository at this point in the history
  • Loading branch information
greatanimalion committed Aug 26, 2024
1 parent 278f754 commit 41ebf2e
Show file tree
Hide file tree
Showing 15 changed files with 116 additions and 50 deletions.
13 changes: 7 additions & 6 deletions dist/content/content.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion dist/contentPage/contentPage.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion dist/contentPage/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,11 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Measuring Tools</title>
<script type="module" crossorigin src="/contentPage/contentPage.js"></script>
<link rel="modulepreload" crossorigin href="/js/client-Gw-UosAD.js">
<link rel="modulepreload" crossorigin href="/js/client-B7nMxStY.js">
<link rel="stylesheet" crossorigin href="/assets/contentPage-i4Tcqm5Z.css">
</head>
<body>
<div id="root"></div>
<script></script>
</body>
</html>
Expand Down
40 changes: 40 additions & 0 deletions dist/js/client-B7nMxStY.js

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions dist/js/postMessage-B4GKDR20.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions dist/js/postMessage-B_nyYmIz.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion dist/popup/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Measuring Tools </title>
<script type="module" crossorigin src="/popup/popup.js"></script>
<link rel="modulepreload" crossorigin href="/js/client-Gw-UosAD.js">
<link rel="modulepreload" crossorigin href="/js/client-B7nMxStY.js">
<link rel="stylesheet" crossorigin href="/assets/popup-D9HIifOd.css">
</head>
<body>
Expand Down
2 changes: 1 addition & 1 deletion dist/popup/popup.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

30 changes: 19 additions & 11 deletions src/content/content.ts
Original file line number Diff line number Diff line change
@@ -1,45 +1,49 @@
import { eventTypes } from '../types/eventTypes'
import { iframe } from '../const/iframe'
import dragImg from '../assets/drag.png'
import PostMessage from '../utils/postMessage'
const timeS = "inject-D" + Date.now().toString()
const style = `
.${timeS}{
outline: 1px solid red;
}
`
let postMessage:any;
let preEl: Element | null = null
let dragOpen = false;
let dragTarget: HTMLElement | null = null;
//@ts-ignore
let centralEl: HTMLElement | null = null;
let onCneter = false;

const MeasureTools = (event: MouseEvent) => {
const MeasureTools = (event: MouseEvent) => {
if (dragOpen) {
if (dragTarget) {
dragTarget.style.top = event.clientY + "px";
dragTarget.style.left = event.clientX + "px";
}
}
if(onCneter)return
if (onCneter) return
let cur = document.elementFromPoint(event.clientX, event.clientY)!
if (cur && (cur.tagName === 'IFRAME' || cur.id === timeS||cur.id===timeS+'-')) return
if (cur && (cur.tagName === 'IFRAME' || cur.id === timeS || cur.id === timeS + '-')) return
if (cur !== preEl) {
preEl && preEl.classList.remove(timeS)
preEl = cur
cur && cur.classList.add(timeS)
centralEl=cur as HTMLDivElement
centralEl = cur as HTMLDivElement
}
}
const centralElClick = (e: KeyboardEvent) => {
let keyNum=window.event ? e.keyCode :e.which;
let keyNum = window.event ? e.keyCode : e.which;
if (keyNum === 81) {
onCneter = !onCneter;
if (!onCneter) { centralEl=null}
console.log(centralEl);
if (!onCneter) {
centralEl = null
}
else {
postMessage.send("hello")
}
}


}
//@ts-ignore
const handleEvent = (e: string) => {
Expand Down Expand Up @@ -83,7 +87,7 @@ const handlePage = (e: string) => {
padding: 10px;`
let img = document.createElement('img')
img.src = dragImg;
img.id=timeS+'-'
img.id = timeS + '-'
img.style.cssText = `width: 20px;
height: 20px;
position: absolute;
Expand All @@ -95,10 +99,14 @@ const handlePage = (e: string) => {
document.body.appendChild(div);
dragTarget = div
img.onclick = () => {
dragOpen=!dragOpen;
dragOpen = !dragOpen;
if (dragOpen) img.style.cursor = 'grabbing';
else img.style.cursor = 'grab';
}
//@ts-ignore
postMessage = new PostMessage(contentIframe.contentWindow)
postMessage.send("hello")

} else if (e == eventTypes.close) {
document.querySelector(`#${timeS}`) && document.querySelector(`#${timeS}`)!.remove()
}
Expand Down
9 changes: 9 additions & 0 deletions src/contentPage/App.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
import { useEffect } from 'react';
import './App.css'

export default function App() {

useEffect(() => {

window.addEventListener('message', (e) => {
console.log(e);
top?.postMessage('ok',"*")
}, false)
})
return <>
<div>
<div id="app">
Expand Down
1 change: 1 addition & 0 deletions src/contentPage/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,6 @@
<body>
<div id="root"></div>
<script type="module" src="./main.tsx"></script>
<script></script>
</body>
</html>
1 change: 1 addition & 0 deletions src/popup/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ export default function App() {
if(e){openMeasureTool();console.log("open")}
else{closeMeasureTool();console.log("close")}
}

return <>
<div id="app">
<div className="toggle normal" >
Expand Down
5 changes: 5 additions & 0 deletions src/utils/diary.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
- window.postMessage中的window指的是你想发送跨域消息的那个窗口(你需要通信的目标窗口),而不是自身窗口的window

- 父页面中:父页面向子页面发送跨域信息,window就是在父页面中嵌入的iframe指向的子页面的window,即:iFrame.contentWindow子页面中:子页面想父页面发送跨域信息
- window就是父页面的window,在这里因为子页面是嵌入到父页面中的,对于子页面来讲,window就是top或者parent
- 需要等到iframe中的子页面加载完成后才发送消息,否则子页面接收不到消息在监听message事件时需要判断一下消息来源origin
26 changes: 12 additions & 14 deletions src/utils/postMessage.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,21 @@
class PostMessage {
#iFrame: HTMLIFrameElement|null =null;
#targetOrigin: string = '';
constructor(el:HTMLIFrameElement, targetOrigin: string) {
this.#iFrame = el;
this.#targetOrigin = targetOrigin;
iFrame: Window |null =null;
targetOrigin: string|undefined = '';
constructor(el:Window,targetOrigin?: string) {
this.iFrame = el;
this.targetOrigin =targetOrigin;
window.addEventListener('message',this.handle,false)
}
sendMessage(message: any) {
this.#iFrame!.contentWindow!.postMessage(message,this.#targetOrigin);
send(message: any) {
if(this.targetOrigin)this.iFrame!.postMessage(message,this.targetOrigin);
else this.iFrame!.postMessage(message,'*');
}
private handle(e: MessageEvent) {
if(e.origin===this.#targetOrigin){
console.log(e.origin) //父页面URL,这里是http://a.index.com
console.log(e.source) // 父页面window对象,全等于window.parent/window.top
console.log(e.data) //父页面发送的消息
}
private handle(e: MessageEvent) {
if(e.data.source!="react-devtools-content-script")console.log(e);

}
destroy() {
window.removeEventListener('message',this.handle,false)
}
}
export default PostMessage;
export default PostMessage;
30 changes: 15 additions & 15 deletions vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,33 +7,33 @@ import path from 'path'
export default defineConfig({
root: 'src/',
plugins: [react(),
copy({
targets: [
{ src: 'manifest.json', dest: 'dist' }, // 复制 manifest.json 到 dist 目录
{ src: "src/icons/**", dest: 'dist/icons' } // 复制 src/icons/** 到 dist/icons 目录
]
})
copy({
targets: [
{ src: 'manifest.json', dest: 'dist' }, // 复制 manifest.json 到 dist 目录
{ src: "src/icons/**", dest: 'dist/icons' } // 复制 src/icons/** 到 dist/icons 目录
]
})
],
build: {
outDir: path.resolve(__dirname, 'dist'),
rollupOptions: {
rollupOptions: {
input: {
popup: path.resolve(__dirname, 'src/popup/index.html'),
contentPage: path.resolve(__dirname, 'src/contentPage/index.html'),
content: path.resolve(__dirname, 'src/content/content.ts'),
background: path.resolve(__dirname, 'src/background/service-worker.ts'),
},
contentPage: path.resolve(__dirname, 'src/contentPage/index.html'),
content: path.resolve(__dirname, 'src/content/content.ts'),
background: path.resolve(__dirname, 'src/background/service-worker.ts'),
},
output: {
assetFileNames: 'assets/[name]-[hash].[ext]', // 静态资源
chunkFileNames: 'js/[name]-[hash].js', // 代码分割中产生的 chunk
entryFileNames: (chunkInfo) => { // 入口文件
chunkFileNames: 'js/[name]-[hash].js', // 代码分割中产生的 chunk
entryFileNames: (chunkInfo) => { // 入口文件
const baseName = path.basename(chunkInfo.facadeModuleId!, path.extname(chunkInfo.facadeModuleId!))
const saveArr = ['content', 'service-worker']
return `[name]/${saveArr.includes(baseName) ? baseName : chunkInfo.name}.js`;
},
name: '[name].js'
name: '[name].js'
}
},
},

})

0 comments on commit 41ebf2e

Please sign in to comment.