|
| 1 | +// Extension event listeners are a little different from the patterns you may have seen in DOM or |
| 2 | +// Node.js APIs. The below event listener registration can be broken in to 4 distinct parts: |
| 3 | +// |
| 4 | +// * chrome - the global namespace for Chrome's extension APIs |
| 5 | +// * runtime – the namespace of the specific API we want to use |
| 6 | +// * onInstalled - the event we want to subscribe to |
| 7 | +// * addListener - what we want to do with this event |
| 8 | +// |
| 9 | +// See https://developer.chrome.com/docs/extensions/reference/events/ for additional details. |
| 10 | +chrome.runtime.onInstalled.addListener(async () => { |
| 11 | + |
| 12 | + // While we could have used `let url = "hello.html"`, using runtime.getURL is a bit more robust as |
| 13 | + // it returns a full URL rather than just a path that Chrome needs to be resolved contextually at |
| 14 | + // runtime. |
| 15 | + let url = chrome.runtime.getURL("hello.html"); |
| 16 | + |
| 17 | + // Open a new tab pointing at our page's URL using JavaScript's object initializer shorthand. |
| 18 | + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#new_notations_in_ecmascript_2015 |
| 19 | + // |
| 20 | + // Many of the extension platform's APIs are asynchronous and can either take a callback argument |
| 21 | + // or return a promise. Since we're inside an async function, we can await the resolution of the |
| 22 | + // promise returned by the tabs.create call. See the following link for more info on async/await. |
| 23 | + // https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await |
| 24 | + let tab = await chrome.tabs.create({ url }); |
| 25 | + |
| 26 | + // Finally, let's log the ID of the newly created tab using a template literal. |
| 27 | + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals |
| 28 | + // |
| 29 | + // To view this log message, open chrome://extensions, find "Hello, World!", and click the |
| 30 | + // "service worker" link in th card to open DevTools. |
| 31 | + console.log(`Created tab ${tab.id}`); |
| 32 | +}); |
0 commit comments