2016-09-17 69 views
0

好時機。使用onBeforeRequest和chrome.tabs.query(Chrome擴展)重定向到新的URL

我有一些有趣的想法,其中必須改變URL後輸入推動「輸入」由用戶。

我的清單文件:

{ 
    "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" 
    ] 

} 

我redirect.js文件:

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"] 
); 

主要是如何需要輸入的URL,一些正則表達式模式改變,返回結果網址重定向到它。怎麼可能做到?如何插入chrome.tabs.query裏面onBeforeRequest或者這不需要,還有另外一種方法嗎?

非常感謝

+1

請參閱[谷歌瀏覽器擴展中的同步呼叫](https://stackoverflow.com/a/22054013)和[如何等待異步方法的回調返回值?](https://stackoverflow.com/a/ 15130214) – wOxxOm

回答

0

我不得不做類似的事情,使用也是異步的鉻存儲API。我所做的就是將Web請求偵聽器放在異步函數的回調中。所以在你的情況下:

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"] 
    ); 
); 

我還沒有測試過,但這是我做什麼時,我需要使用存儲API,所以試試看。

相關問題