问题
I am writing my first chrome extension, which should open an URL in a new tab and after that do something.
manifest:
{
"manifest_version": 2,
"name": "Test",
"description": "",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"tabs",
"activeTab"
]
}
script.js:
function toggle() {
chrome.tabs.create({ url: "http://google.com" }, function(tab) {
alert("Hello!");
});
}
document.getElementById('toggle').addEventListener('click', toggle);
popup.html:
<html>
<head>
</head>
<body>
<div id="toggle" class="clickable">START</div>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
The problem is that nothing happens after the URL is opened. What can be the problem?
回答1:
When you create a new tab, by default it opens focused, and that causes the popup to close. When the popup closes, its JavaScript context is destroyed and there's no callback left to call.
You have 2 options:
Move logic to the background/event page, which will survive the popup being closed. For example, instead of opening the tab from the popup, you can message the background page to do it for you.
Specify that you want to open the tab unfocused:
chrome.tabs.create( { url: "http://google.com", active: false }, function(tab) { /* ... */ } );
However, this won't simply cause the tab to not focus - Chrome won't switch to it (opening it in the background). Might not be what you want. You can switch after your other operations are done though - with
chrome.tabs.update
to setactive: true
.
Note that there is no way for a popup to survive focus loss, this is by design.
来源:https://stackoverflow.com/questions/37089887/callback-of-chrome-tabs-create-is-not-triggered-in-a-popup