How to create chrome tab of develop Chrome Extension like window.location?

北城余情 提交于 2019-12-25 04:58:07

问题


I am developing a chrome extension. I have a requiremen that is create a new tab with some params like javascript 'window' function.

By default javascript window function, i need to set this code as below then window.location.replace allow permission to access the page in new window.

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,
    } 
});

Now, I am using the google chrome api to create tab.

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

So, I have a question, How should I pass above window.name to create a new tab that I can access the new location.


回答1:


Inject a content script code that sets the name.

  1. Permit the URL (better) or "<all_urls>" (worse, but sometimes unavoidable) in manifest.json:

    "permissions": ["http://www.example.com/*"],
    
  2. Put the name into a variable:

    var windowName = JSON.stringify({
        foo: 'bar',
    });
    
  3. Use chrome.tabs.executeScript in a background/popup/options page script to run the content script code as a string with embedded window name as a parameter in the newly created tab:

    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',
        });
    }
    

In case you already have an automatically executed content script (e.g. declared in manifest.json), use messaging (chrome.tabs.sendMessage) to send the window name and set it accordingly.



来源:https://stackoverflow.com/questions/42272044/how-to-create-chrome-tab-of-develop-chrome-extension-like-window-location

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!