2017-02-16 124 views
0

我正在開發一個Chrome擴展。 我有一個requiremen是創建一個新的選項卡與像JavaScript'窗口'功能的一些參數。如何創建開發Chrome擴展的chrome選項卡,比如window.location?

默認情況下,javascript窗口的功能,我需要設置下面的代碼,然後window.location.replace允許在新窗口中訪問頁面的權限。

window.name = JSON.stringify({ 
    id : 'tmp', 
    companyCode : companyCode, 
    locationCode : locationCode, 
    terminalNo : terminalNo, 
    terminalKey : terminalKey, 

    server:{ 
     protocol : protocol, 
     remoteHost : remoteHost, 
     remotePort : remotePort, 

     clientHost : clientHost, 
     localPort : clientPort, 
     webContext : null, 

     gcRemoteHost : remoteHost, 
     gcRemotePort : remotePort, 

     soaPort: 9091, 
     webSocketPort : 9099, 
    } 
}); 

現在,我正在使用谷歌瀏覽器api創建選項卡。

chrome.tabs.create({ 
    url: new_location 
}); 

所以,我有一個問題,我應該如何通過上述window.name創建我可以訪問新位置的新標籤。

+0

new_location是web網址,在允許我訪問網站之前,它需要準確接收window.name的值。是否有可能在創建chrome選項卡時模擬window.name – tommychoo

+0

相關:[將參數傳遞給使用chrome.tabs.executeScript()注入的內容腳本](// stackoverflow.com/q/17567624) – Makyen

回答

1

注入設置名稱的內容腳本代碼。

  1. 允許URL(更好)或"<all_urls>"(更糟糕的,但有時不可避免的)的manifest.json:

    "permissions": ["http://www.example.com/*"], 
    
  2. 把名字到一個變量:

    var windowName = JSON.stringify({ 
        foo: 'bar', 
    }); 
    
  3. 在後臺/彈出窗口/選項頁面腳本中使用chrome.tabs.executeScript以內嵌窗口名稱作爲參數在新創建的選項卡中將內容腳本代碼作爲字符串運行:

    chrome.tabs.create({ 
        url: 'http://www.example.com' 
    }, function(tab) { 
        runContentCode(tab.id, injectedSetWindowName, windowName); 
    }); 
    
    function injectedSetWindowName(name) { 
        window.name = name; 
    } 
    
    function runContentCode(tabId, fn, params) { 
        chrome.tabs.executeScript(tabId, { 
         code: '(' + fn + ')(' + JSON.stringify(params) + ')', 
         runAt: 'document_start', 
        }); 
    } 
    

如果你已經有一個自動執行腳本的內容(例如在manifest.json中聲明),請使用messaging(chrome.tabs。sendMessage)發送窗口名稱並相應地進行設置。

相關問題