Open new tabs from the extension
Chrome extension can do more than just display your Bubble app in the popup. This guide explains how to add functions to your extension, and how to trigger the functions from your Bubble app.
We are going to create an extension function that opens links in new tabs. This function can be triggered by an action in your Bubble appās workflow.
Step 1: Add listener and define functions
Communication between extensions and Bubble apps works by message passing. In short, we can send a message from the Bubble app to the extension. The extension can listen for the message, run some functions, and send a response.
To receive the message, we need to create a listener in the background script. We will also create a function openNewTab()
to open URLs in new tabs.
Open background.js with any text editor.
//background.js
let openNewTab = function(url) { //create new tab
chrome.tabs.create({
active: true,
url: url
});
}
chrome.runtime.onMessageExternal.addListener( //receive msg from Bubble app
function(request, sender, sendResponse) {
if (request.action === 'openNewTab') {
openNewTab(request.url);
}
}
);
Step 2: Allow the extension to receive messages from your app
Open manifest.json
. Find the key externally_connectable
in the JSON file. Add URL pattern to the list matches
. The URL pattern should match your Bubble appās URL.
{
"name": "Nalfe extension demo",
...
"externally_connectable": {
// Match patterns for web pages.
"matches": [
"https://*.bubbleapps.io/*"
]
},
...
}
Step 3: Send message from the Bubble App
To send a message from your page, you have to run a JavaScript function with an action. You can create a custom plugin action to do it, or use the Toolbox plugin.
Run this function to send a message:
let extensionId = "<extensionID>"; //replace this with your extension id
let url = "https://nalfe.com/"; //this URL will be opened in a new tab
try {
chrome.runtime.sendMessage(extensionId, {
action: "openNewTab",
url: url
}, function(response) {
var lastError = chrome.runtime.lastError;
if (lastError) {
console.log(lastError.message);
}
});
} catch (err) {
console.log(err);
}
You can find your extension ID here.
Notice that the extension ID for an unpacked extension is not fixed.
Done!
You have created an action that opens a link in a new tab. Load the extension to test. Make sure you have the correct extension ID.