Chrome扩展:标签页创建完成前阻塞脚本的异步问题
Got it, let's sort out this execution order problem for you! The issue you're hitting is that the classic chrome.tabs.create uses a callback pattern instead of returning a Promise by default—so just throwing await at it won't work because there's no Promise to wait for. But we can fix this while still grabbing the new tab's ID.
Solution 1: Wrap the Callback in a Promise (Works for Manifest V2 & V3)
We can create a simple wrapper function that converts the callback-based API into a Promise. This lets us use async/await to pause execution until the tab is created, and we'll get the new tab object (including its ID) once it's ready.
Here's how to implement it:
// Wrapper function to turn tabs.create into a Promise function createTabAsync(tabOptions) { return new Promise((resolve) => { chrome.tabs.create(tabOptions, (newTab) => { resolve(newTab); // Pass the new tab data (including ID) to the Promise }); }); } // Your main script using async/await async function runMyScript() { console.log("Start of my script"); // Wait for the tab to be created, then get its data const newTab = await createTabAsync({ url: "https://your-target-url.com" }); console.log(`Tab created: ${newTab.id}`); console.log("end of my script"); } // Execute the script runMyScript();
With this code, the execution order will be exactly what you want:Start of my script → Tab created:... → end of my script
Solution 2: Use the Native Promise API (Manifest V3 Only)
If you're working with Manifest V3, Chrome has already updated most APIs to return Promises when you don't provide a callback. That means you can skip the wrapper and use await directly:
async function runMyScript() { console.log("Start of my script"); // No callback needed—chrome.tabs.create returns a Promise in V3 const newTab = await chrome.tabs.create({ url: "https://your-target-url.com" }); console.log(`Tab created: ${newTab.id}`); console.log("end of my script"); } runMyScript();
This is cleaner, but it only works for Manifest V3. If you're still on V2, stick with the wrapper approach.
Why Your Original await Didn't Work
The original chrome.tabs.create (when you pass a callback) doesn't return a Promise—it just executes immediately and runs the callback later when the tab is ready. So await had nothing to wait for, hence the out-of-order logs. By wrapping it in a Promise, we give await something to hold onto until the tab creation finishes.
内容的提问来源于stack exchange,提问作者Laurent

