2017-02-16 62 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)发送窗口名称并相应地进行设置。

相关问题