I have stored some urls in chrome.storage.sync like below......
sitesToBeBlocked: {
"https://www.google.com/":"https://www.google.com/" ,
"https://www.example.com/": "https://www.example.com/"
}
Now i am trying to block these urls using the code below.....
Manifest.json
{
"name": "chrome extension",
"description": ".............",
"version": "0.0.1",
"manifest_version": 2,
"background": {
"scripts": ["/scripts/background/background.js"]
},
"content_scripts": [
{
"matches": ["https://*/*","http://*/*"] ,
"js": ["/scripts/content/jquery-3.6.0.js","/scripts/content/content-script.js"]
}
],
"permissions": ["storage","unlimitedStorage","webRequest","webRequestBlocking","*://*/*"],
"browser_action": {
"default_popup": "/popup/popup.html",
"default_icon": {
............
}
},
"options_ui": {
"page": "/options/options.html",
"open_in_tab": true
},
}
background.js
function isRequestCancelled(sitesArray, url){
return sitesArray.includes(url);
}
function blockListener (details) {
chrome.storage.sync.get(null, (items)=>{
var sitesArray = Object.keys(items['sitesToBeBlocked']);
return { cancel: isRequestCancelled(sitesArray, details.url ) };
});
}
chrome.webRequest.onBeforeRequest.addListener( blockListener ,{ urls: ["<all_urls>"], types: [ 'main_frame' ] }, ['blocking'] );
But URLs are not blocked, I don't know what is the matter... please help me to get the exact problem that i am facing ............
I figured out the problem in my code myself..
Actually the problem here is that
chrome.storage.sync's callback is asynchronous fucntion. Due to whichchrome.webRequest's callback is terminated beforechrome.storage.sync's callback return.The solution can be,
Put everything inside
chrome.storage.sync's callback, so that every function will return afterchrome.storage.sync's callback executes.Finally I have fixed this issue with the modified code below....
Actual clue is got from related query