web插件hook data 与 content 交互

To integrate the `injectData` function, which hooks into the `XMLHttpRequest.prototype.send` to capture and inject data, with the WebSocket connection in the `content.js` script, follow these steps:

### 1. Content Script (`content.js`):
This script will inject the necessary JavaScript into the webpage to hook into `XMLHttpRequest` and establish the WebSocket connection.

```javascript
// content.js

// Inject the XMLHttpRequest hook into the page
const script = document.createElement('script');
script.textContent = `
    (function() {
        const originalSend = window.XMLHttpRequest.prototype.send;
        window.XMLHttpRequest.prototype.send = function(body) {
            this._url = this._url || this._url !== undefined ? this._url : this._openArgs && this._openArgs[1];
            // Hook onreadystatechange event 
            this.addEventListener('readystatechange', function() { 
                if (this.readyState === 4 && this._url && this._url.includes("graphql/")) { // readyState 4 means the request is done 
                    try { 
                        var jsonResponse = JSON.parse(this.responseText);
                        window.postMessage({ type: 'INJECTED_DATA', jsonResponse }, '*');
                    } catch (e) {
                        console.error("Failed to parse JSON response", e);
                    } 
                }
            });
            return originalSend.apply(this, arguments);
        };
    })();
`;
(document.head || document.documentElement).appendChild(script);
script.remove();

// Listen for messages from the injected script
window.addEventListener('message', function(event) {
    if (event.source !== window) return;
    if (event.data.type && event.data.type === 'INJECTED_DATA') {
        const jsonResponse = event.data.jsonResponse;
        sendDataToWebSocket(jsonResponse);
    }
});

// WebSocket connection
const ws = new WebSocket('wss://your-websocket-server.com');

ws.onopen = function() {
    console.log('WebSocket connection established');
};

ws.onmessage = function(event) {
    console.log('Message from server:', event.data);
};

ws.onclose = function() {
    console.log('WebSocket connection closed');
};

function sendDataToWebSocket(data) {
    if (ws.readyState === WebSocket.OPEN) {
        ws.send(JSON.stringify(data));
    } else {
        console.error('WebSocket is not open. ReadyState: ' + ws.readyState);
    }
}
```

### Explanation:

1. **Injecting Script:**
   - A script is injected into the webpage to hook into `XMLHttpRequest.prototype.send`. This script captures the JSON response of requests that include "graphql/" in their URL and sends the data using `window.postMessage`.

2. **Listening for Messages:**
   - The content script listens for `INJECTED_DATA` messages from the injected script. When such a message is received, it extracts the `jsonResponse` and calls the `sendDataToWebSocket` function.

3. **WebSocket Connection:**
   - A WebSocket connection is established to `wss://your-websocket-server.com`.
   - The `sendDataToWebSocket` function sends the captured data to the WebSocket server if the WebSocket connection is open.

### Conclusion

This setup allows the content script to inject a script into the webpage that hooks into `XMLHttpRequest`, captures JSON responses, and sends the data to a WebSocket server. Make sure to replace `wss://your-websocket-server.com` with your actual WebSocket server URL.

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值