如何在每次在Javascript中使用fetch()时执行函数



每次在脚本中发出HTTP请求时,我都会尝试向sharedWorker发布一条消息,以避免在每次HTTP请求后手动执行此操作。

我设法让它像这样工作:

var App = {
__webWorker: null,
__XMLHttpRequest: XMLHttpRequest.prototype.open,
__onScriptComplete: e       => {
if( e.data.type && e.data.type === 'worker' ) {
sessionStorage.setItem( 'token', e.data.session.token );
return;
}
}
};
window.addEventListener( 'load', () => {
XMLHttpRequest.prototype.open  = (method, url, async, user, password) => {
App.__XMLHttpRequest(method, url, async, user, password);
App.__webWorker.postMessage( '{{md5(session_id())}}' );
};
const worker = new SharedWorker( '{{$router->generate( 'web_notify_worker' )}}' );
worker.port.onmessage = e => App.__onScriptComplete( e );
App.__webWorker = worker.port;
// The below gives me a Uncaught TypeError: Illegal invocation and the App.__webWorker.postMessage is executed
let req = new XMLHttpRequest();
req.open( 'GET', '/', true );
req.send();
// The below works fine but the App.__webWorker.postMessage is not executed
fetch( '/', { method: 'GET' } );
} );

当我创建一个new XMLHttpRequest()时,它工作得很好,并且sessionStorage项是用数据设置的。但是,我不使用XMLHttpRequest,而是使用fetch()。这似乎并没有创建一个我认为会创建的XMLHttpRequest

每次调用新的fetch()时,如何在App.__webWorker上执行postMessage函数?最好是在它完成之后。

更新:这是我自己的框架,我使用了Smarty模板引擎,所以忽略了{{}}前缀区域。这就是我从PHP将数据导入脚本的方式。

更新:我试过这样做,但我得到了Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation:

var App = {
...,
__fetch: fetch
}
fetch = ( uri, args ) => {
App.__fetch( uri, args );
App.__webWorker.postMessage( '{{md5( session_id() )}}' );
};

您可以覆盖覆盖全局并调用它。如果您将其作为自己的方法并调用它,而不是这种‘劫持

const _fetch = window.fetch
// window.fetch = function() {
window.fetch = function(...args) {
console.log('before fetch')
// return Promise.resolve(_fetch.apply(window, arguments))
return Promise.resolve(_fetch.apply(window, args))
.then(resp => {
console.log('inside then');
return resp;
})
}
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => console.log(json))

经过大量的谷歌搜索,我发现问题是将fetch存储在App范围中。要解决此问题,必须将其存储在window范围内。

_fetch = fetch;
fetch = ( uri, args ) => {
let f = _fetch( uri, args );
App.__webWorker.postMessage( '{{md5( session_id() )}}' );
return f;
};

这样做很好,每次发送fetch()时,我的sharedWorker都会被发送一条消息。

最新更新