簡體   English   中英

如何使用代理捕獲對象創建?

[英]How do I catch object creation using a proxy?

感謝您花時間閱讀我的問題。 我正在逆向工程的網站的 javascript 執行以下行:

this.socket = new WebSocket(o.host)

該行被埋在其他函數的函數等中,所以我無法在運行時正常訪問它。 我想使用 Proxy 對象在每次調用 new Websocket() 時“注入”代碼,以便通知我它的創建並將其保存到我事先准備好的全局變量中。

我的油脂猴腳本看起來像這樣:

var caught_socket; // prepare variable

handler = {
  apply: function(target, thisArg, argumentsList) {
    console.log("WebSocket was created!");
    caught_socket = target;
  }
}

WebSocket = new Proxy(WebSocket, handler);

這顯然不起作用,我將不勝感激任何有關代理實際工作方式的幫助或演示!

使用Proxy.construct()代替,它會在new被調用時執行。

 // Create a new WebSocket proxy WebSocket = new Proxy(WebSocket, { construct: (target, args) => { console.log('New WebSocket Instance!') return new target(...args) } }) // Test the WebSocket proxy by connecting to a remote server const ws = new WebSocket('wss://echo.websocket.org') // Listen for an open connection // Send a message to the connection ws.addEventListener('open', () => { console.log('Connection Open!') ws.send('hello') }) // Listen for messages from the remote server ws.addEventListener('message', msg => console.log('Response:', msg.data))

如果您添加第二個代理,兩個代理都會執行:

 // Create a new WebSocket proxy WebSocket = new Proxy(WebSocket, { construct: (target, args) => { console.log('New WebSocket Instance!') return new target(...args) } }) WebSocket = new Proxy(WebSocket, { construct: (target, args) => { console.log('New WebSocket Override!') return new target(...args) } }) // Test the WebSocket proxy by connecting to a remote server const ws = new WebSocket('wss://echo.websocket.org') // Listen for an open connection // Send a message to the connection ws.addEventListener('open', () => { console.log('Connection Open!') ws.send('hello') }) // Listen for messages from the remote server ws.addEventListener('message', msg => console.log('Response:', msg.data))

你甚至可以返回一個完全不同的類:

 class MyCoolWebSocket { addEventListener(event, callback) { console.log('override event:', event) } } // Create a new WebSocket proxy WebSocket = new Proxy(WebSocket, { construct: (target, args) => { console.log('New WebSocket Instance!') return new WebSocket(...args) } }) // Create a new WebSocket proxy WebSocket = new Proxy(WebSocket, { construct: (target, args) => { console.log('Greasemonkey override!') return new MyCoolWebSocket(...args) } }) // Test the WebSocket proxy by connecting to a remote server const ws = new WebSocket('wss://echo.websocket.org') // Listen for an open connection // Send a message to the connection ws.addEventListener('open', () => { console.log('Connection Open!') ws.send('hello') }) // Listen for messages from the remote server ws.addEventListener('message', msg => console.log('Response:', msg.data))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM