0

Good time.

I have some interesting idea for which have to do changing URL after inputing pushing "enter" by user.

My manifest file:

 {
  "name": "The Pirate Bay_2",
  "description": "Redirect The Pirate Bay to a different host",
  "version": "1.0",
  "manifest_version": 2,

  "browser_action": {
        "default_title": "Saving Studio generator",
        "default_popup": "popup.html"

    },
    "background": {"scripts":["redirect.js"]},
    "content_scripts": [
   {
     "matches": ["http://*/*", "https://*/*"],
     "js": ["background.js"]
   }
   ],
  "permissions": 
  [ 
    "webRequest", 
    "https://www.amazon.com/", 
    "webRequestBlocking",
    "tabs",
    "activeTab"
    ]

}

My redirect.js file:

var host = "https://2ch.hk/b/";

chrome.tabs.query({
    'active': true, 'currentWindow': true
    }, function (tabs) {
    var url = tabs[0].url;
    host = host+url;
    console.log(url);
    });

chrome.webRequest.onBeforeRequest.addListener(  
    function(details) {

        if (localStorage.check_box == "true"){
            console.log("start_1");

         return {redirectUrl: host};
        }
    },
    {
        urls: ["https://www.amazon.com/" ],
        types: ["main_frame", "sub_frame", "stylesheet", "script", "image", "object", "xmlhttprequest", "other"]
    },

    ["blocking"]
);

Main is to how to take entered URL, change it by some regex pattern, return resulting URL to redirect to it. How it's possible to do? How to insert chrome.tabs.query inside onBeforeRequest or this needn't and there is another way?

Big thanks

  • 1
    See [Synchronous call in Google Chrome extension](https://stackoverflow.com/a/22054013) and [How to wait for an asynchronous method's callback return value?](https://stackoverflow.com/a/15130214) – wOxxOm Sep 17 '16 at 15:25

1 Answers1

0

I've had to do something similar using the chrome storage API which is also asynchronous. What I did was put the web request listener inside the callback of the async function. So in your case:

var host = "https://2ch.hk/b/";
chrome.tabs.query(
    {
        'active': true, 'currentWindow': true
    }, 
    function (tabs) {
        var url = tabs[0].url;
        host = host+url;
        console.log(url);
    }
    chrome.webRequest.onBeforeRequest.addListener(  
        function(details) {
            if (localStorage.check_box == "true"){
                console.log("start_1");
                return {redirectUrl: host};
            }
        },
        {
            urls: ["https://www.amazon.com/" ],
            types: ["main_frame", "sub_frame", "stylesheet", "script", "image", "object", "xmlhttprequest", "other"]
        },
        ["blocking"]
    );
);

I haven't tested this but it's what I did when I needed to use the storage API, so give it a try.