问题
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.
Permit the URL (better) or
"<all_urls>"
(worse, but sometimes unavoidable) in manifest.json:"permissions": ["http://www.example.com/*"],
Put the name into a variable:
var windowName = JSON.stringify({ foo: 'bar', });
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