Commit 8fdf6f3e authored by 刘燕芳's avatar 刘燕芳

通信

parent 4e86efe9
...@@ -27,8 +27,7 @@ ...@@ -27,8 +27,7 @@
"matches": [ "matches": [
"*://myseller.taobao.com/*", "*://myseller.taobao.com/*",
"*://admin.rtxmdz.com/*", "*://admin.rtxmdz.com/*",
"http://localhost:8082/*", "http://localhost:10823/*",
"http://localhost:8083/*",
"*://*.rtxmdz.com/*" "*://*.rtxmdz.com/*"
], ],
"js": ["content.js"], "js": ["content.js"],
......
...@@ -9,67 +9,18 @@ const PlatfromsMap = new Map([ ...@@ -9,67 +9,18 @@ const PlatfromsMap = new Map([
[2, /.+:\/\/jd.*\.fahuoyi.com\/scanPrinting\/index/] [2, /.+:\/\/jd.*\.fahuoyi.com\/scanPrinting\/index/]
]) ])
let monitoringRemoveTabId = new Map(); let monitoringRemoveTabId = new Map();
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) { let result_sendResponse:boolean = false
chrome.runtime.onMessage.addListener(async function (message, sender, sendResponse) {
if (message.action === StartPrint) { if (message.action === ACTION.task) {
// console.log("startPrint")
// 通知fahuoyi的content开始点击
chrome.tabs.query({
url: "*://*.fahuoyi.com/scanPrinting/index"
}, function (tabs) {
let exp = new RegExp(PlatfromsMap.get(message.value.platform)!, 'i')
console.log(tabs, 'tabs66')
tabs && tabs.forEach(tab => {
if (exp.test(tab.url!)) {
chrome.tabs.sendMessage(tab.id!, { action: Print, value: message.value })
}
})
// // sendResponse("")
// if (tabs[0]) {
// chrome.tabs.sendMessage(tabs[0].id!, { action: Print, value: message.value })
// }
})
chrome.tabs.query({
url: "*://*.fahuoyi.com/features/scanPrinting"
}, function (tabs) {
console.log(tabs, 'tabs11')
tabs && tabs.forEach(tab => {
chrome.tabs.executeScript(tab.id!, {code: 'console.log(window["scan-printing-form"])'});
})
})
} else if (message.action === "sendNewWaybillNo") {
// 从bg页面转发给厂家页面的content.js
chrome.tabs.query({
url: factoryContentUrls
}, function (tabs) {
tabs && tabs.forEach(tab => {
// chrome.tabs.sendMessage(tab.id!, message)
const port = chrome.tabs.connect(tab.id!, { name: "sendNewWaybillNo" })
port.onMessage.addListener(function (msg, port) {
if (msg.action === "answer") {
// console.log(msg, port, 'bg')
port.disconnect()
}
})
port.postMessage(message)
})
})
// let port = chrome.runtime.connect({ name: "bgSendMessage" })
// port.postMessage(message)
}else if (message.action === ACTION.task) {
// 从bg页面转发给厂家页面的content.js // 从bg页面转发给厂家页面的content.js
chrome.tabs.query({ chrome.tabs.query({
url: bookingV2Urls url: bookingV2Urls
}, function (tabs) { }, function (tabs) {
tabs && tabs.forEach(tab => { tabs && tabs.forEach(tab => {
// chrome.tabs.sendMessage(tab.id!, message) // chrome.tabs.sendMessage(tab.id!, message)
chrome.tabs.update(tab.id!, { active: true}, function(tab1) {}); chrome.tabs.update(tab.id!, { active: true}, function(tab1) {});
chrome.tabs.sendMessage(tab.id!, { action: ACTION.task, value: message.value },res=>{ chrome.tabs.sendMessage(tab.id!, { action: ACTION.task, value: message.value },res=>{
console.log(3333,res,tab,new Date());
if(res){ if(res){
sendResponse(res); sendResponse(res);
chrome.tabs.update(sender.tab!.id!, { active: true}, function(tab1) {}); chrome.tabs.update(sender.tab!.id!, { active: true}, function(tab1) {});
...@@ -77,21 +28,40 @@ chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) { ...@@ -77,21 +28,40 @@ chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
}) })
}) })
if(tabs.length==0){ if(tabs.length==0){
alert('请打开新版发货易发货页面') alert('请打开千牛商家工作台')
sendResponse({status:1,msg:"请打开新版发货易发货页面"}); sendResponse({status:1,msg:"请打开千牛商家工作台"});
}
chrome.storage.sync.get("tb_user",function(res){
let userData = res.tb_user
if (userData == null) {
alert('请登录千牛商家工作台')
sendResponse({status:1,msg:"请登录千牛商家工作台"});
} }
}) })
})
// let port = chrome.runtime.connect({ name: "bgSendMessage" }) // let port = chrome.runtime.connect({ name: "bgSendMessage" })
// port.postMessage(message) // port.postMessage(message)
}else if(message.action==='getUserLoginData'){ }else if(message.action==='getUserLoginData'){
getUserLoginData() await getUserLoginData()
chrome.tabs.onUpdated.addListener(async (tabId, changeInfo, tab) => { sendResponse()
}
return true;
})
chrome.tabs.onUpdated.addListener(async (tabId, changeInfo, tab) => {
console.log('tab',tab);
//加载完毕后在执行一些动作 //加载完毕后在执行一些动作
if (tab.status== "complete") { if (tab.status== "complete") {
//如果进入了千牛首页 则开始获取对应的数据信息 //如果进入了千牛首页 则开始获取对应的数据信息
if(tab.url&&tab.url.indexOf("loginmyseller.taobao.com") != -1){ if(tab.url&&tab.url.indexOf("loginmyseller.taobao.com") != -1){
if(monitoringRemoveTabId.has(tab.id)){
let id:any = tab.id
chrome.tabs.remove(id);
}
chrome.storage.sync.remove("tb_user") chrome.storage.sync.remove("tb_user")
sendResponse(); result_sendResponse=true;
return return
} }
if (tab.url&&tab.url.indexOf("myseller.taobao.com/home.htm/QnworkbenchHome") != -1) { if (tab.url&&tab.url.indexOf("myseller.taobao.com/home.htm/QnworkbenchHome") != -1) {
...@@ -100,7 +70,8 @@ chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) { ...@@ -100,7 +70,8 @@ chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
console.log('userNickCookie',userNickCookie); console.log('userNickCookie',userNickCookie);
if (userNickCookie === null || userNickCookie === undefined) { if (userNickCookie === null || userNickCookie === undefined) {
chrome.storage.sync.remove("tb_user") chrome.storage.sync.remove("tb_user")
sendResponse(); result_sendResponse=true;
return return
}; };
let tuDe1 = decodeURI(userNickCookie.value); let tuDe1 = decodeURI(userNickCookie.value);
...@@ -132,11 +103,13 @@ chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) { ...@@ -132,11 +103,13 @@ chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
// } // }
let id:any = tab.id let id:any = tab.id
chrome.storage.sync.set({"tb_user":JSON.stringify(userData)}) chrome.storage.sync.set({"tb_user":JSON.stringify(userData)})
sendResponse(); result_sendResponse=true;
}else{ }else{
console.log(222,new Date().getMinutes(),new Date().getSeconds()); // console.log(222,new Date().getMinutes(),new Date().getSeconds());
chrome.storage.sync.remove("tb_user") chrome.storage.sync.remove("tb_user")
sendResponse(); result_sendResponse=true;
} }
} }
if(monitoringRemoveTabId.has(tab.id)){ if(monitoringRemoveTabId.has(tab.id)){
...@@ -145,16 +118,27 @@ chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) { ...@@ -145,16 +118,27 @@ chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
} }
} }
})
}
return true;
}) })
async function getUserLoginData(){ async function getUserLoginData(){
result_sendResponse = false
let tabId = await createTab(homeUrl); let tabId = await createTab(homeUrl);
monitoringRemoveTabId.set(tabId, ""); monitoringRemoveTabId.set(tabId, "");
await newTab()
return new Promise<void>((resolve, reject) => {
resolve()
})
}
function newTab(){
return new Promise<void>((resolve, reject) => {
if(result_sendResponse){
resolve()
}else{
setTimeout(() => {
newTab()
},500);
}
})
} }
async function createTab(url:string) { async function createTab(url:string) {
......
import { bookingV2Urls } from "../config";
let domEle = {
divNav:document.getElementsByClassName("nav-link") as HTMLCollection,
inputOrderId: "#originalIds",
btnSearch: "#root > section > main > div > div > div > div.order-main > div.order-table-container > div.order-search-pane > div > div > div:nth-child(2) > button:nth-child(2)",
checkBoxSelectAll: "div.bottom-operation-bar > span input.ant-checkbox-input",
btnPrint: ".ec-print-waybill-button",
modalTips:"ant-modal-confirm-title",
btnTipsConfirm:"div.ant-modal-confirm-body-wrapper > div > button.ant-btn-primary",
spanWaybillTemplate: ():any=>document.getElementsByClassName("ant-modal-body")[0].getElementsByClassName("ant-select-selector")[0] ,
divWaybillTemplateList: ():any=>document.getElementsByClassName("rc-virtual-list-holder-inner")[0] ,
radioGetNewWaybill: ():any=>document.querySelector(".ant-modal-body input.ant-radio-input") ,
inputWaybillNoOnly: ():any=>document.querySelector("#isGenerateWaybillNoOnly") ,
btnDialogPrint: ():any=>document.querySelector("div.ant-modal-footer button"),
modalResult: "#printEwaybillResultDialog",
tableResult: ():any=>document.querySelector("#ewaybill-result-table > div > div.ant-table-body > table"),
btnClose: ():any=>document.querySelector("div.ant-modal-footer button:nth-child(3)") ,
btnDeliver: ():any=>document.querySelector("div.ant-modal-footer button:nth-child(2)") ,
deliverResult:():any=>document.querySelector(".ant-modal-body>div.ant-table-wrapper .ant-table-tbody"),
deliverClose: ():any=>document.querySelector("div.ant-modal-footer button") ,
}
async function booking(info: any) { async function booking(info: any) {
return ; console.log(2222);
let data:object = { catId: 150704, jsonBody: info}
}
async function waitOrder() {
let result = {
status: 4,
msg: "获取订单超时",
data: [],
}
for (let i = 0; i < 10; i++) {
await delayDate(1000);
let loadingMask = document.querySelector("#root > section > main > div > div > div > div.order-main > div.order-table-container > div.loading-mark-container > div") as any;
if (loadingMask.style.display=="none" ) {
if (document.querySelector("#root > section > main > div > div > div > div.order-main > div.order-table-container > div.loading-mark-container > table > tbody > tr > td > div > div.mb10 > p")) {
//无订单
result.status = 2;
result.msg = "无相关订单"
return result;
} else {
result.status = 0;
result.msg = ""
return result;
}
}
}
return result;
}
async function waitDialog() {
let result = {
status: 4,
msg: "获取打印按钮超时",
data: [],
}
for (let i = 0; i < 10; i++) {
await delayDate(1000);
if (document.getElementsByClassName("ant-modal-content").length) {
result.status = 0;
result.msg = ""
return result;
}
}
return result;
}
async function waitPrintResult() {
let result = {
status: 4,
msg: "获取打印结果超时",
data: [],
}
for (let i = 0; i < 10; i++) {
await delayDate(1000);
if (domEle.tableResult()) {
result.status = 0;
result.msg = ""
return result;
}
}
return result;
}
function delayDate(time: number) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
setTimeout(() => { fetch("https://item.upload.taobao.com/sell/v2/submit.htm", { method: "POST",body:JSON.stringify(data) }).then(res => {
//console.log(‘开始执行‘) console.log('fetch 111',res);
resolve("success"); resolve(res)
}, time); })
});
}
function changeReactInputValue(inputDom:any,newText:string){
let lastValue = inputDom.value;
inputDom.value = newText;
let event = new Event('input', { bubbles: true });
// @ts-ignore
event.simulated = true;
let tracker = inputDom._valueTracker;
if (tracker) {
tracker.setValue(lastValue);
}
inputDom.dispatchEvent(event);
}
const mouseClickEvents = ['mousedown', 'click', 'mouseup'];
function simulateMouseClick(element:any){
mouseClickEvents.forEach(mouseEventType =>
element.dispatchEvent(
new MouseEvent(mouseEventType, {
view: window,
bubbles: true,
cancelable: true,
buttons: 1
}) })
)
);
} }
export default { export default {
booking booking
} }
\ No newline at end of file
...@@ -6,16 +6,24 @@ import { message } from "antd"; ...@@ -6,16 +6,24 @@ import { message } from "antd";
import { ACTION, Print, StartPrint } from "../types"; import { ACTION, Print, StartPrint } from "../types";
import BookingV2 from "./bookingV2" import BookingV2 from "./bookingV2"
type Params = {
a: number // 运单号
b: number
}
interface Message {
action: "Print",
value: Params
}
// web页面通信 // web页面通信
window.addEventListener("message",function(message:any){ window.addEventListener("message",function(message:any){
console.log('web页面通信',message); console.log('web页面通信1',message,new Date());
if(message.data.action == ACTION.task){ if(message.data.action == ACTION.task){
chrome.runtime.sendMessage(message.data,(ret)=>{ chrome.runtime.sendMessage(message.data,(ret)=>{
// window.postMessage({isResult:1,...ret},"*") console.log(2222,ret);
console.log("message ret:",ret,message.data); window.postMessage({isResult:1,...ret},"*")
console.log("message ret:1",ret,message.data);
}) })
} }
}) })
...@@ -37,10 +45,10 @@ chrome.runtime.onMessage.addListener(function (message, sender, response) { ...@@ -37,10 +45,10 @@ chrome.runtime.onMessage.addListener(function (message, sender, response) {
* 发货易content * 发货易content
*/ */
window.addEventListener("message", function (msg) { // window.addEventListener("message", function (msg) {
console.log('发货易content',msg); // console.log('发货易content',msg,new Date());
}) // })
This diff is collapsed.
...@@ -5,3 +5,6 @@ ...@@ -5,3 +5,6 @@
overflow-x: hidden; overflow-x: hidden;
margin-left: 10px; margin-left: 10px;
} }
.btn{
margin: 10px 0 0 10px;
}
\ No newline at end of file
...@@ -7,6 +7,7 @@ interface User { ...@@ -7,6 +7,7 @@ interface User {
cookie:string, cookie:string,
token:string token:string
} }
let initTime = 0
const WayBillModel = function () { const WayBillModel = function () {
// 当前是否连接成功 // 当前是否连接成功
const [link,setLink] = useState<boolean>(false) const [link,setLink] = useState<boolean>(false)
...@@ -18,6 +19,8 @@ const WayBillModel = function () { ...@@ -18,6 +19,8 @@ const WayBillModel = function () {
cookie:'', cookie:'',
token:'' token:''
}) })
// 刷新时候的状态
const [loading,setLoading] = useState<boolean>(false)
// 获取发货易快递模板列表 // 获取发货易快递模板列表
const getLogin = useCallback(async () => { const getLogin = useCallback(async () => {
chrome.tabs.query({ chrome.tabs.query({
...@@ -43,7 +46,6 @@ const WayBillModel = function () { ...@@ -43,7 +46,6 @@ const WayBillModel = function () {
// 获取用户信息 // 获取用户信息
chrome.storage.sync.get("tb_user",function(res){ chrome.storage.sync.get("tb_user",function(res){
console.log(res); console.log(res);
let userData = res.tb_user let userData = res.tb_user
if (userData == null) { if (userData == null) {
setIsLogin(false) setIsLogin(false)
...@@ -61,6 +63,9 @@ const WayBillModel = function () { ...@@ -61,6 +63,9 @@ const WayBillModel = function () {
// 刷新连接状态 // 刷新连接状态
const refresh = useCallback(() => { const refresh = useCallback(() => {
if(initTime>0)return
setLoading(true)
initTime++
getLogin() getLogin()
chrome.runtime.sendMessage({ action: 'getUserLoginData' },async()=>{ chrome.runtime.sendMessage({ action: 'getUserLoginData' },async()=>{
let userData:any = await getStorageItem("tb_user") let userData:any = await getStorageItem("tb_user")
...@@ -76,6 +81,8 @@ const WayBillModel = function () { ...@@ -76,6 +81,8 @@ const WayBillModel = function () {
setUser(userDataJson) setUser(userDataJson)
setLink(true) setLink(true)
} }
initTime = 0
setLoading(false)
}) })
// alert("刷新完毕"); // alert("刷新完毕");
}, []) }, [])
...@@ -85,7 +92,7 @@ const WayBillModel = function () { ...@@ -85,7 +92,7 @@ const WayBillModel = function () {
<div className="waybill-model-title" key="one">千牛登录账号:{is_login?user.userNick:'未登录'}</div> <div className="waybill-model-title" key="one">千牛登录账号:{is_login?user.userNick:'未登录'}</div>
<div className="waybill-model-title" key="two">通信状态:{link?'连接成功':'连接中断'}</div> <div className="waybill-model-title" key="two">通信状态:{link?'连接成功':'连接中断'}</div>
</div> </div>
<Button type="link" onClick={ refresh }>刷新连接状态</Button> <Button className="btn" type="primary" loading={loading} disabled={loading} onClick={ refresh }>刷新连接状态</Button>
</> </>
) )
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment