Browse Source

[add][message回调]

zhangwei 2 năm trước cách đây
mục cha
commit
f0424e99dc

+ 14 - 5
src/entry/content.js

@@ -59,6 +59,7 @@ import {
     injectDenet
 } from "@/logic/content/denet.js";
 
+import doTask from '@/logic/content/help/doTask'
 chrome.storage.onChanged.addListener(changes => {
     initExecuteScript(changes)
 })
@@ -72,9 +73,15 @@ window.onload = () => {
         data: {}
     });
 };
+
+
 window.onmessage = (res) => {
-    if (res.data && res.data.actionType) {
-        switch (res.data.actionType) {
+    if (!res.data) {
+        return
+    }
+    let { info, data } = res.data
+    if ((res.data.actionType) || (info && info.actionType)) {
+        switch (info.actionType || res.data.actionType) {
             case "IFRAME_SHOW_IFREME":
                 showIframeHandler();
                 break;
@@ -121,9 +128,11 @@ window.onmessage = (res) => {
                 getExtensionStorgeDataForIframe(res.data.data);
                 break;
             case 'IFRAME_DO_TASK_CREATE_TWEET':
-                // 做任务
-                // 接受数据,sendmessage
-                console.log('IFRAME_DO_TASK_CREATE_TWEET', res)
+                // 接收消息
+                doTask.TwitterApiCreateTweet({ info, data })
+                break
+            case 'IFRAME_DO_TASK_LIKE':
+                doTask.TwitterLikeAPI({ info, data })
                 break
         }
     }

+ 3 - 2
src/logic/content/ParseCard.js

@@ -344,9 +344,10 @@ class ParseCard {
         return _iframe
     }
     createTreasureIframe(params = { page_type, tweet_Id, post_Id, invite_code, invite_channel }) {
+        let _iframeId = `denet-${guid()}`
         let _iframe = document.createElement('iframe')
-        _iframe.id = params.post_Id
-        _iframe.src = chromeExtensionUrl + ('iframe/treasure-hunt.html') + `?params=${JSON.stringify(params)}&iframeId=${guid()}`;
+        _iframe.id = _iframeId
+        _iframe.src = chromeExtensionUrl + ('iframe/treasure-hunt.html') + `?params=${JSON.stringify(params)}&iframeId=${_iframeId}`;
         _iframe.style.cssText = 'border:medium none; width:375px; min-height:580px; border: 1px solid #DCDCDC; border-radius: 20px;'
         return _iframe
     }

+ 127 - 0
src/logic/content/help/doTask.js

@@ -0,0 +1,127 @@
+import messageCenter from '@/uilts/messageCenter/content';
+import { getCookie } from '@/uilts/help'
+
+
+const TwitterApiCreateTweet = ({ info, data }) => {
+    // let params = {
+    //     queryId: "hC1nuE-2d1NX5LYBuuAvtQ",
+    //     features: {
+    //         "dont_mention_me_view_api_enabled": true,
+    //         "interactive_text_enabled": true,
+    //         "responsive_web_uc_gql_enabled": false,
+    //         "vibe_api_enabled": true,
+    //         "responsive_web_edit_tweet_api_enabled": false,
+    //         "standardized_nudges_misinfo": true,
+    //         "responsive_web_enhance_cards_enabled": false
+    //     },
+    //     variables: {
+    //         "tweet_text": text,
+    //         "media": {
+    //             "media_entities": [],
+    //             "possibly_sensitive": false
+    //         },
+    //         "withDownvotePerspective": true,
+    //         "withReactionsMetadata": false,
+    //         "withReactionsPerspective": false,
+    //         "withSuperFollowsTweetFields": true,
+    //         "withSuperFollowsUserFields": true,
+    //         "semantic_annotation_ids": [],
+    //         "dark_request": false
+    //     }
+    // };
+    // axios.post(`https://twitter.com/i/api/graphql/hC1nuE-2d1NX5LYBuuAvtQ/CreateTweet`,
+    //     params, {
+    //     headers: {
+    //         "accept": "*/*",
+    //         "accept-language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7",
+    //         "authorization": "Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA",
+    //         "content-type": "application/json",
+    //         "sec-ch-ua": "\" Not A;Brand\";v=\"99\", \"Chromium\";v=\"101\", \"Google Chrome\";v=\"101\"",
+    //         "sec-ch-ua-mobile": "?0",
+    //         "sec-ch-ua-platform": "\"Windows\"",
+    //         "sec-fetch-dest": "empty",
+    //         "sec-fetch-mode": "cors",
+    //         "sec-fetch-site": "same-origin",
+    //         "x-csrf-token": getCookie('ct0'),
+    //         "x-twitter-active-user": "yes",
+    //         "x-twitter-auth-type": "OAuth2Session",
+    //         "x-twitter-client-language": "en"
+    //     },
+    // }).then(function (response) {
+    // data.response = response
+
+    // messageCenter.send({ info, data: response })
+    // messageCenter.send({ id: data.iframeId, actionType, data: response })
+    // chrome.runtime.sendMessage({ actionType: "DO_TASK", do_type: 'api', tweet_Id, task_type: 'createTweet1', task_data: '', task_done: '是', response, iframeId })
+    // }).catch(function (err) {
+    //     messageCenter.send({ id: data.iframeId, actionType, data: err })
+    //     // chrome.runtime.sendMessage({ actionType: "DO_TASK", do_type: 'api', tweet_Id, task_type: 'createTweet1', task_data: '', task_done: '否', iframeId })
+    // });
+}
+
+const TwitterLikeAPI = ({ info, data }) => {
+    fetch("https://twitter.com/i/api/graphql/lI07N6Otwv1PhnEgXILM7A/FavoriteTweet", {
+        "headers": {
+            "accept": "*/*",
+            "accept-language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7",
+            "authorization": "Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA",
+            "content-type": "application/json",
+            "sec-ch-ua": "\" Not A;Brand\";v=\"99\", \"Chromium\";v=\"101\", \"Google Chrome\";v=\"101\"",
+            "sec-ch-ua-mobile": "?0",
+            "sec-ch-ua-platform": "\"Windows\"",
+            "sec-fetch-dest": "empty",
+            "sec-fetch-mode": "cors",
+            "sec-fetch-site": "same-origin",
+            "x-csrf-token": getCookie('ct0'),
+            "x-twitter-active-user": "yes",
+            "x-twitter-auth-type": "OAuth2Session",
+            "x-twitter-client-language": "en"
+        },
+        "referrer": "https://twitter.com/home",
+        "referrerPolicy": "strict-origin-when-cross-origin",
+        "body": "{\"variables\":{\"tweet_id\":\"" + data.tweetId + "\"},\"queryId\":\"lI07N6Otwv1PhnEgXILM7A\"}",
+        "method": "POST",
+        "mode": "cors",
+        "credentials": "include"
+    }).then(() => {
+        // 返回信息
+        messageCenter.send({ info, data: { task_done: true } })
+    }).catch(() => {
+        messageCenter.send({ info, data: { task_done: false } })
+    })
+}
+
+// const TwitterFollowAPI = (item, tweet_Id) => {
+//     fetch("https://twitter.com/i/api/1.1/friendships/create.json", {
+//         "headers": {
+//             "authorization": "Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA",
+//             "content-type": "application/x-www-form-urlencoded",
+//             "sec-ch-ua": "\" Not A;Brand\";v=\"99\", \"Chromium\";v=\"102\", \"Google Chrome\";v=\"102\"",
+//             "sec-ch-ua-mobile": "?0",
+//             "sec-ch-ua-platform": "\"macOS\"",
+//             "x-csrf-token": getCookie('ct0'),
+//             "x-twitter-active-user": "yes",
+//             "x-twitter-auth-type": "OAuth2Session",
+//             "x-twitter-client-language": "zh-cn"
+//         },
+//         "referrer": "https://twitter.com/home",
+//         "referrerPolicy": "strict-origin-when-cross-origin",
+//         "body": "include_profile_interstitial_type=1&include_blocking=1&include_blocked_by=1&include_followed_by=1&include_want_retweets=1&include_mute_edge=1&include_can_dm=1&include_can_media_tag=1&include_ext_has_nft_avatar=1&skip_status=1&user_id=" + item.twitterUserId + "",
+//         "method": "POST",
+//         "mode": "cors",
+//         "credentials": "include"
+//     }).then(() => {
+//         let task_data = {
+//             follow_name: item.name
+//         }
+//         chrome.runtime.sendMessage({ actionType: "DO_TASK", do_type: 'api', tweet_Id, task_type: 'follow', task_data, task_done: true }, () => { })
+//         messageCenter.send({ id: data.iframeId, actionType, data: '123' })
+//     }).catch(() => {
+//         console.log('DO_TASK3')
+//         chrome.runtime.sendMessage({ actionType: "DO_TASK", do_type: 'api', tweet_Id, task_type: 'follow', task_data, task_done: false }, () => { })
+//     })
+// }
+
+export default {
+    TwitterApiCreateTweet, TwitterLikeAPI
+}

+ 77 - 58
src/logic/content/twitter.js

@@ -10,7 +10,7 @@ import { jumpTwitterDetailByAlert, showEditTweet } from '@/logic/content/help/tw
 import { clearPostContent, setGroupIconStatus } from '@/logic/content/nft.js'
 import { toolBox } from '@/logic/content/ToolBox'
 import axios from 'axios';
-import messageCenter from '@/uilts/messageCenter';
+import messageCenter from '@/uilts/messageCenter/content';
 import { PlayType } from '@/types';
 import { reSetBindPostContent } from '@/http/help.js';
 import { setDeviceInfo } from '@/logic/content/help/twitter';
@@ -882,10 +882,10 @@ function setIframeCard(type = 'twitter') {
                             index = Number(i) + 1
                             if (arr[i] == 'invite' && arr.length >= index) {
                                 item.invite_code = arr[index];
-                                if(arr.length > index + 1) {
-                                  item.invite_channel = arr[index+1];
+                                if (arr.length > index + 1) {
+                                    item.invite_channel = arr[index + 1];
                                 } else {
-                                  item.invite_channel = '';
+                                    item.invite_channel = '';
                                 }
                                 break
                             }
@@ -1079,18 +1079,18 @@ export const getTweetUserFollowStatus = (params) => {
     Promise.allSettled(promiseList).then((res) => {
         let list = [];
         if (res && res.length) {
-          let resList = res.filter(item => item.status == 'fulfilled');
-          for (let i = 0; i < resList.length; i++) {
-              let item = resList[i];
-              if (item && item.value && item.value.data && item.value.data.data) {
-                  list.push(item.value.data.data)
-              }
-          }
+            let resList = res.filter(item => item.status == 'fulfilled');
+            for (let i = 0; i < resList.length; i++) {
+                let item = resList[i];
+                if (item && item.value && item.value.data && item.value.data.data) {
+                    list.push(item.value.data.data)
+                }
+            }
         }
 
         chrome.runtime.sendMessage({ actionType: 'CONTENT_GET_TWEET_USER_FOLLOW_STATUS_RES', data: list, tweetId, type: params.type, iframeId: params.iframeId }, () => { })
     }).catch(err => {
-      chrome.runtime.sendMessage({ actionType: 'CONTENT_GET_TWEET_USER_FOLLOW_STATUS_RES', data: [], tweetId, type: params.type, iframeId: params.iframeId }, () => { })
+        chrome.runtime.sendMessage({ actionType: 'CONTENT_GET_TWEET_USER_FOLLOW_STATUS_RES', data: [], tweetId, type: params.type, iframeId: params.iframeId }, () => { })
     })
 }
 
@@ -1463,45 +1463,45 @@ export function showJoinDialog(data) {
 }
 
 const TwitterFriendshipsUpdate = (params) => {
-  let {id = '', device = true, name} = params || {};
-  let data = {
-    include_profile_interstitial_type: 1,
-    include_blocking: 1,
-    include_blocked_by: 1,
-    include_followed_by: 1,
-    include_want_retweets: 1,
-    include_mute_edge: 1,
-    include_can_dm: 1,
-    include_can_media_tag: 1,
-    include_ext_has_nft_avatar: 1,
-    skip_status: 1,
-    cursor: -1,
-    id,
-    device
-  }
-  if(!id) {
-    return;
-  }
-  return fetch("https://twitter.com/i/api/1.1/friendships/update.json", {
-      "headers": {
-          "authorization": "Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA",
-          "content-type": "application/x-www-form-urlencoded",
-          "sec-ch-ua": "\" Not A;Brand\";v=\"99\", \"Chromium\";v=\"102\", \"Google Chrome\";v=\"102\"",
-          "sec-ch-ua-mobile": "?0",
-          "sec-ch-ua-platform": "\"macOS\"",
-          "x-csrf-token": getCookie('ct0'),
-          "x-twitter-active-user": "yes",
-          "x-twitter-auth-type": "OAuth2Session",
-          "x-twitter-client-language": "en",
-          "referer": `https://twitter.com/${name}`
-      },
-      "referrer": `https://twitter.com/${name}`,
-      "referrerPolicy": "strict-origin-when-cross-origin",
-      "body": `include_profile_interstitial_type=1&include_blocking=1&include_blocked_by=1&include_followed_by=1&include_want_retweets=1&include_mute_edge=1&include_can_dm=1&include_can_media_tag=1&include_ext_has_nft_avatar=1&skip_status=1&cursor=-1&id=${id}&device=true`,
-      "method": "POST",
-      "mode": "cors",
-      "credentials": "include"
-  })
+    let { id = '', device = true, name } = params || {};
+    let data = {
+        include_profile_interstitial_type: 1,
+        include_blocking: 1,
+        include_blocked_by: 1,
+        include_followed_by: 1,
+        include_want_retweets: 1,
+        include_mute_edge: 1,
+        include_can_dm: 1,
+        include_can_media_tag: 1,
+        include_ext_has_nft_avatar: 1,
+        skip_status: 1,
+        cursor: -1,
+        id,
+        device
+    }
+    if (!id) {
+        return;
+    }
+    return fetch("https://twitter.com/i/api/1.1/friendships/update.json", {
+        "headers": {
+            "authorization": "Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA",
+            "content-type": "application/x-www-form-urlencoded",
+            "sec-ch-ua": "\" Not A;Brand\";v=\"99\", \"Chromium\";v=\"102\", \"Google Chrome\";v=\"102\"",
+            "sec-ch-ua-mobile": "?0",
+            "sec-ch-ua-platform": "\"macOS\"",
+            "x-csrf-token": getCookie('ct0'),
+            "x-twitter-active-user": "yes",
+            "x-twitter-auth-type": "OAuth2Session",
+            "x-twitter-client-language": "en",
+            "referer": `https://twitter.com/${name}`
+        },
+        "referrer": `https://twitter.com/${name}`,
+        "referrerPolicy": "strict-origin-when-cross-origin",
+        "body": `include_profile_interstitial_type=1&include_blocking=1&include_blocked_by=1&include_followed_by=1&include_want_retweets=1&include_mute_edge=1&include_can_dm=1&include_can_media_tag=1&include_ext_has_nft_avatar=1&skip_status=1&cursor=-1&id=${id}&device=true`,
+        "method": "POST",
+        "mode": "cors",
+        "credentials": "include"
+    })
 }
 
 const TwitterFollowAPI = (item, tweet_Id) => {
@@ -1527,7 +1527,7 @@ const TwitterFollowAPI = (item, tweet_Id) => {
         let task_data = {
             follow_name: item.name
         }
-        TwitterFriendshipsUpdate({id: item.twitterUserId, name: item.name})
+        TwitterFriendshipsUpdate({ id: item.twitterUserId, name: item.name })
 
         chrome.runtime.sendMessage({ actionType: "DO_TASK", do_type: 'api', tweet_Id, task_type: 'follow', task_data, task_done: true }, () => { })
     }).catch(() => {
@@ -2338,7 +2338,12 @@ const addPageScrollEvent = () => {
         contentHeight: contentDom.offsetHeight
     }
 
-    messageCenter.send('de-tab-group-content', 'CONTENT_GROUP_LIST_SCROLL', data)
+    messageCenter.send({
+        info: {
+            iframeId: 'de-tab-group-content', actionType: 'CONTENT_GROUP_LIST_SCROLL'
+        },
+        data
+    })
 
     // chrome.runtime.sendMessage({
     //     actionType: "CONTENT_GROUP_LIST_SCROLL",
@@ -2424,7 +2429,11 @@ const setGroupTabSelfStyle = (params = {}) => {
  * 切换到 Group tab时 刷新列表
  */
 export const refreshTabGroup = () => {
-    messageCenter.send('de-tab-group-content', 'CONTENT_REFRESH_TAB_GROUP_LIST', {})
+    messageCenter.send({
+        info: {
+            iframeId: 'de-tab-group-content', actionType: 'CONTENT_REFRESH_TAB_GROUP_LIST'
+        }
+    })
     //     chrome.runtime.sendMessage({
     //         actionType: "CONTENT_REFRESH_TAB_GROUP_LIST",
     //         data: {}
@@ -2505,7 +2514,7 @@ const addTabGroupContent = (cb) => {
     }
     let iframe = document.createElement('iframe');
     iframe.id = 'de-tab-group-content';
-    iframe.src = getInnerIframeURL(`${iframeHost}/tab-group` + `?params=${JSON.stringify(params)}&iframeID=${iframe.id}`);
+    iframe.src = getInnerIframeURL(`${iframeHost}/tab-group` + `?params=${JSON.stringify(params)}&iframeId=${iframe.id}`);
     iframe.style.cssText = `border: medium none; height: 500px;display: none`
 
     let iframeContent = getGroupTabContentNode();
@@ -2607,7 +2616,9 @@ export const getTweetProfileNavTop = (params) => {
     let top = document.querySelector('div[role="tablist"]').closest('nav').getBoundingClientRect().top;
 
     messageCenter.send({
-        actionType: "CONTENT_SEND_GROUP_NAV_TOP",
+        info: {
+            actionType: "CONTENT_SEND_GROUP_NAV_TOP"
+        },
         data: {
             top,
             scrollTop: params.scrollTop
@@ -2653,7 +2664,13 @@ export const setGroupInfo = (params = {}) => {
 
 export const getExtensionStorgeDataForIframe = (data) => {
     getChromeStorage(data.key).then((res) => {
-        messageCenter.send(data.iframeID, `IFRAME_GET_EXTENSION_STORGE_DATA-${data.messageID}`, res)
+        messageCenter.send({
+            info: {
+                iframeId: data.iframeId,
+                actionType: `IFRAME_GET_EXTENSION_STORGE_DATA-${data.messageId}`
+            },
+            data: res
+        })
     });
 }
 
@@ -2680,7 +2697,9 @@ const sysThemeChange = () => {
     setTimeout(() => {
         let bgColor = document.querySelector('body').style.backgroundColor;
         messageCenter.send({
-            actionType: "CONTENT_SYS_THEME_CHANGE",
+            info: {
+                actionType: "CONTENT_SYS_THEME_CHANGE"
+            },
             data: {
                 theme: systemInfo.theme,
                 twitterTheme: bgColor == 'rgb(0, 0, 0)' ? 'dark' : 'light'

+ 0 - 6
src/uilts/denet.js

@@ -1,6 +0,0 @@
-import Content from '@/uilts/messageCenter/messageContent'
-
-let denet = {}
-denet.content = Content
-
-export default denet

+ 52 - 0
src/uilts/denet/content/doTask.js

@@ -0,0 +1,52 @@
+import MESSAGE_ENUM from '@/uilts/messageCenter/iframe/messageEnum'
+import messageCenter from '@/uilts/messageCenter/iframe'
+
+// 做任务
+const doTask = {
+    createTweet({ iframeId, tweetId }, overTime) {
+        return new Promise((res, rej) => {
+            messageCenter.send({
+                info: {
+                    actionType: MESSAGE_ENUM.IFRAME_DO_TASK_CREATE_TWEET,
+                    iframeId: iframeId //用于告诉父窗口会传消息给哪个iframe
+                },
+                data: {
+                    tweetId
+                },
+                overTime,
+                callback: (data) => {
+                    res(data);
+                },
+                failback: (e) => {
+                    rej(e)
+                }
+            })
+        })
+    },
+
+    like({ iframeId, tweetId }, overTime) {
+        return new Promise((res, rej) => {
+            messageCenter.send({
+                info: {
+                    actionType: MESSAGE_ENUM.IFRAME_DO_TASK_LIKE,
+                    iframeId: iframeId //用于告诉父窗口会传消息给哪个iframe
+                },
+                data: {
+                    tweetId,
+                },
+                overTime,
+                callback: (data) => {
+                    res(data);
+                },
+                failback: (e) => {
+                    rej(e)
+                }
+            })
+        })
+    }
+}
+
+export default doTask
+
+// iframe > dom id 
+// iframe > createTweet  dom id 

+ 5 - 0
src/uilts/denet/content/index.js

@@ -0,0 +1,5 @@
+import doTask from '@/uilts/denet/content/doTask'
+
+export default {
+    doTask
+}

+ 7 - 0
src/uilts/denet/index.js

@@ -0,0 +1,7 @@
+import content from '@/uilts/denet/content'
+
+const denet = {
+    content
+}
+
+export default denet

+ 50 - 0
src/uilts/messageCenter/content/index.js

@@ -0,0 +1,50 @@
+class MessageCenter {
+    constructor() {
+        this.iframeMap = new Map();
+        this.messageCallbackMap = new Map();
+        // this.listen()
+    }
+
+    findIframeById(id) {
+        let target = this.iframeMap.get(id);
+        if (!target) {
+            target = document.getElementById(id)
+            this.iframeMap.set('id', target)
+        }
+        return target
+    }
+
+    send({ info, data }) {
+        const target = this.findIframeById(info.iframeId);
+        target && target.contentWindow.postMessage({
+            info,
+            data
+        }, '*')
+    }
+
+    // ---- don't use ---- 
+    // add(actionType, callback) {
+    //     let activeQuene = this.messageCallbackMap.get(actionType);
+    //     if (activeQuene?.length > 0) {
+    //         activeQuene.push(callback)
+    //     } else {
+    //         this.messageCallbackMap.set(actionType, [callback])
+    //     }
+    // }
+    // ---- don't use ---- 
+    // listen() {
+    //     window.addEventListener('message', (e) => {
+    //         const { actionType, data } = e.data;
+    //         console.log('get message in content ...', actionType, data)
+    //         const quene = this.messageCallbackMap.get(actionType) || [];
+    //         while (quene.length > 0) {
+    //             let callback = quene.pop();
+    //             callback(data)
+    //         }
+    //     })
+    // }
+}
+
+const messageCenter = new MessageCenter();
+
+export default messageCenter;

+ 0 - 3
src/uilts/messageCenter/messageEnum.js → src/uilts/messageCenter/content/messageEnum.js

@@ -7,9 +7,6 @@ const SEND_MESSAGE_ENUM = {
     /** 获取content的localstorge数据 */
     IFRAME_GET_EXTENSION_STORGE_DATA: 'IFRAME_GET_EXTENSION_STORGE_DATA',
 
-    // ---- 做任务 ----
-    IFRAME_DO_TASK_CREATE_TWEET: 'IFRAME_DO_TASK_CREATE_TWEET'
-
 }
 
 /** 接收父窗口的事件定义 */

+ 101 - 0
src/uilts/messageCenter/iframe/index.js

@@ -0,0 +1,101 @@
+import { guid } from '@/uilts/help'
+//  iframe 通信中心
+class MessageCenter {
+    constructor() {
+        //  缓存事件队列
+        this.messageCallbackMap = new Map();
+        this.messageFailbackMap = new Map();
+        this.timer = null
+        this.init()
+    }
+
+    send({ info = {}, data = {}, callback, overTime, failback }) {
+        info.messageId = `${info.actionType}-${guid()}` // 唯一的ID,用于标记回调函数
+        window.parent.postMessage({
+            info,
+            data
+        }, '*');
+        if (info.messageId && callback) {
+            // 带回调callback 的message, 要求携带messageId,callback,failback等
+            this.listen(info.messageId, callback)
+            if (failback) {
+                this.addFailback(info.messageId, overTime, failback)
+            }
+        }
+    }
+
+    listen(messageId, callback) {
+        let activeQuene = this.messageCallbackMap.get(messageId);
+        if (activeQuene?.length > 0) {
+            activeQuene.push(callback)
+        } else {
+            this.messageCallbackMap.set(messageId, [callback])
+        }
+    }
+
+    addFailback(messageId, overTime = 2000, failback) {
+        let failbackQuene = this.messageFailbackMap.get(messageId);
+        if (failbackQuene && failbackQuene.failCallbackList) {
+            failbackQuene.failCallbackList.push(
+                failback
+            )
+        } else {
+            this.messageFailbackMap.set(messageId, {
+                time: new Date().getTime(),
+                overTime,
+                failCallbackList: [failback]
+            })
+        }
+        this.checkTimer()
+    }
+
+
+
+    init() {
+        window.addEventListener('message', (e) => {
+            const { info, data } = e.data;
+            this.messageFailbackMap.delete(info.messageId);
+            const quene = this.messageCallbackMap.get(info.messageId) || [];
+            let index = 0;
+            while (index < quene.length) {
+                const callback = quene[index];
+                callback(data)
+                index++
+            }
+        })
+
+        this.checkTimer()
+    }
+    checkTimer() {
+        if (this.timer) {
+            return
+        }
+        this.timer = setInterval(() => {
+            if (this.messageFailbackMap.values().length == 0) {
+                clearInterval(this.timer)
+                this.timer = null
+            }
+
+            // 轮询查看有无超期的message信息
+            const now = new Date().getTime();
+            for (let item of this.messageFailbackMap.values()) {
+                if (now - item.time > item.overTime) {
+                    let index = 0;
+                    while (index < item.failCallbackList.length) {
+                        const callback = item.failCallbackList[index];
+                        callback({
+                            error: 0,
+                            msg: "message 超时错误"
+                        })
+                        index++
+                    }
+                }
+            }
+        }, 1000)
+    }
+}
+
+// messageCenter在每个iframe内实例化一次
+const messageCenter = new MessageCenter();
+
+export default messageCenter;

+ 24 - 0
src/uilts/messageCenter/iframe/messageEnum.js

@@ -0,0 +1,24 @@
+/** 向父窗口发送的事件定义 */
+const SEND_MESSAGE_ENUM = {
+    IFREME_TAB_GROUP_SET_IFRAME_HEIGHT: 'IFREME_TAB_GROUP_SET_IFRAME_HEIGHT',
+    /** group tab 内的列表项点击 */
+    IFRAME_PAGE_JUMP: 'IFRAME_PAGE_JUMP',
+    IFREME_TAB_GROUP_CONTENT_GET_NAV_TOP: 'IFREME_TAB_GROUP_CONTENT_GET_NAV_TOP',
+    /** 获取content的localstorge数据 */
+    IFRAME_GET_EXTENSION_STORGE_DATA: 'IFRAME_GET_EXTENSION_STORGE_DATA',
+    // ---- 做任务 ----
+    IFRAME_DO_TASK_CREATE_TWEET: 'IFRAME_DO_TASK_CREATE_TWEET',
+    IFRAME_DO_TASK_LIKE: 'IFRAME_DO_TASK_LIKE'
+}
+
+/** 接收父窗口的事件定义 */
+const RECEIVE_MESSAGE_ENUM = {
+    /** 切换到group tab */
+    CONTENT_REFRESH_TAB_GROUP_LIST: 'CONTENT_REFRESH_TAB_GROUP_LIST',
+    /** group打开时,页面发生滚动 */
+    CONTENT_GROUP_LIST_SCROLL: 'CONTENT_GROUP_LIST_SCROLL',
+    CONTENT_SEND_GROUP_NAV_TOP: 'CONTENT_SEND_GROUP_NAV_TOP',
+    CONTENT_SYS_THEME_CHANGE: 'CONTENT_SYS_THEME_CHANGE'
+}
+
+export default { ...SEND_MESSAGE_ENUM, ...RECEIVE_MESSAGE_ENUM }

+ 0 - 50
src/uilts/messageCenter/index.js

@@ -1,50 +0,0 @@
-class MessageCenter {
-    constructor() {
-        this.iframeMap = new Map();
-        this.messageCallbackMap = new Map();
-        // this.listen()
-    }
-
-    findIframeById(id) {
-        let target = this.iframeMap.get(id);
-        if (!target) {
-            target = document.getElementById(id)
-            this.iframeMap.set('id', target)
-        }
-        return target
-    }
-
-    send(id, actionType, data) {
-        const target = this.findIframeById(id);
-        target && target.contentWindow.postMessage({
-            actionType,
-            data
-        }, '*')
-    }
-
-    // don't use
-    add(actionType, callback) {
-        let activeQuene = this.messageCallbackMap.get(actionType);
-        if (activeQuene?.length > 0) {
-            activeQuene.push(callback)
-        } else {
-            this.messageCallbackMap.set(actionType, [callback])
-        }
-    }
-    // don't use
-    listen() {
-        window.addEventListener('message', (e) => {
-            const { actionType, data } = e.data;
-            console.log('get message in content ...', actionType, data)
-            const quene = this.messageCallbackMap.get(actionType) || [];
-            while (quene.length > 0) {
-                let callback = quene.pop();
-                callback(data)
-            }
-        })
-    }
-}
-
-const messageCenter = new MessageCenter();
-
-export default messageCenter;

+ 0 - 39
src/uilts/messageCenter/messageContent.js

@@ -1,39 +0,0 @@
-// class message  
-import messageCenter from '@/uilts/messageCenter';
-import MESSAGE_ENUM from "@/uilts/messageCenter/messageEnum";
-import { guid, iframeID } from '@/uilts/help.js'
-
-// content.createTweets('iframe') 
-
-// 做任务
-class doTask {
-    createTweet({ txt = '' }) {
-        return new Promise((res, rej) => {
-            messageCenter.send({
-                actionType: MESSAGE_ENUM.IFRAME_DO_TASK_CREATE_TWEET,
-                data: {
-                    iframeID,//用于告诉父窗口会传消息给哪个iframe 
-                    messageID: guid()// 唯一的ID,用于标记回调函数
-                },
-                info: {
-                    txt
-                },
-                callback: (data) => {
-                    res(data)
-                },
-                failback: (e) => {
-                    rej(e)
-                }
-            })
-        })
-        // console.log(window.parent.window.atest)
-        // window.postMessage({actionType: 'iframe_test', data: key})
-    }
-}
-
-
-export default {
-    doTask() {
-        return new doTask()
-    }
-}

+ 10 - 0
src/view/iframe/treasure-hunt/index.vue

@@ -22,6 +22,7 @@ import { getChromeStorage, sendCurrentTabMessage } from '@/uilts/chromeExtension
 import VToast from '@/view/iframe/treasure-hunt/components/toast.vue'
 import OpenBox from '@/view/iframe/treasure-hunt/components/open-box.vue'
 import Report from "@/log-center/log"
+import denet from '@/uilts/denet'
 
 let state = reactive({
     loading_redbag: true,
@@ -63,8 +64,17 @@ onMounted(() => {
 
     state.init();
     onRuntimeMsg();
+    // doLike()
 })
 
+async function doLike() {
+    let task = await denet.content.doTask.like({ iframeId: state.iframeId, tweetId: '1564877034756534272' })
+    console.log('task', task)
+    if (tgas) {
+
+    }
+}
+
 state.checkIsLogin = () => {
     return new Promise((resolve) => {
         getChromeStorage('userInfo', (_userInfo) => {