FVl*_*lad 9 javascript google-chrome synchronize
我正在使用Google Chrome扩展程序,该扩展程序必须阻止/重定向某些传出请求.为此,我使用了chrome.webRequest.onBeforeRequest监听器.要决定是否阻止请求,我需要一些有关选项卡请求的信息.我可以使用它chrome.tabs.get(integer tabId, function callback),但回调是异步的,这意味着它可以在从onBeforeRequest侦听器返回值后调用.
chrome.webRequest.onBeforeRequest.addListener(function(details){
chrome.tabs.get(details.tabId, function(tab){
// get info from tab
});
// based on info from tab return redirect or not
}), {
urls: ["<all_urls>"],
types: ["main_frame"]
}, ["blocking"]);
Run Code Online (Sandbox Code Playgroud)
有没有办法同步通话?或许还有一些其他选择.
Tyl*_*ich 13
Stack Overflow上的另一个答案建议跟踪监听器功能之外的选项卡,这完全避免了这个问题.
示例代码:
/*
* --------------------------------------------------
* Keep list of tabs outside of request callback
* --------------------------------------------------
*/
var tabs = {};
// Get all existing tabs
chrome.tabs.query({}, function(results) {
results.forEach(function(tab) {
tabs[tab.id] = tab;
});
});
// Create tab event listeners
function onUpdatedListener(tabId, changeInfo, tab) {
tabs[tab.id] = tab;
}
function onRemovedListener(tabId) {
delete tabs[tabId];
}
// Subscribe to tab events
chrome.tabs.onUpdated.addListener(onUpdatedListener);
chrome.tabs.onRemoved.addListener(onRemovedListener);
/*
* --------------------------------------------------
* Request callback
* --------------------------------------------------
*/
// Create request event listener
function onBeforeRequestListener(details) {
// *** Remember that tabId can be set to -1 ***
var tab = tabs[details.tabId];
// Respond to tab information
}
// Subscribe to request event
chrome.webRequest.onBeforeRequest.addListener(onBeforeRequestListener, {
urls: ["<all_urls>"],
types: ["main_frame"]
}, ["blocking"]);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2579 次 |
| 最近记录: |