问题
I am trying to create a new tab using browser.tabs.create()
from my background.js
WebExtension as shown here:
createTab: function () {
var newTab = browser.tabs.create({ url: someUrl });
newTab.then(onCreated, onError);
}
The new tab creates in the browser, but when the last line is reached, an error is thrown:
SCRIPT5007: Unable to get property 'then' of undefined or null reference
The Locals window shows newTab
is undefined
.
What am I doing wrong here? I thought that .create()
would immediately return a Promise
. I know create()
is an asynchronous function - but my calling function doesn't need to by async, does it?
Any help would be appreciated.
回答1:
I ended up reading the Microsoft documentation (who knew?) and came across this little gem:
Seems pretty definitive; now I just need an example of using callbacks for it instead...
回答2:
As Scott Baker already mentioned, Microsoft Edge extension APIs sadly don't support promises.
So you could refer to this MDN example on how to use callbacks:
browser.windows.onCreated.addListener((tab) => {
console.log("New tab: " + tab.id);
});
Or even better: Provide the callback directly as second parameter to the create
function:
var newTab = browser.tabs.create({ url: someUrl }, (tab) => {
console.log("New window: " + window.id);
});
See the chrome docs (seems to apply for Edge, too): https://developer.chrome.com/extensions/tabs#method-create
Please note: You can achieve the same, if you're aiming for a new window (instead of a new tab) with windows.create(object createData, function callback)
来源:https://stackoverflow.com/questions/47545719/cant-get-edge-to-return-a-promise-in-my-webextension