Call method from another JS in SW

56 views
Skip to first unread message

Divya Rijhwani

unread,
May 24, 2023, 1:47:54 PM5/24/23
to Chromium Extensions
Hello Team,

Please let me know how I can call any method from different JS in my SW. Previously it was working by just calling function. My editor shows that method is present but SW gives me error when I try to call the same.

Please do Needful.

Simeon Vincent

unread,
May 24, 2023, 2:21:04 PM5/24/23
to Divya Rijhwani, Chromium Extensions
You can't directly call a function in a different context. You can, however, send a message from one context to another and have the receive call a function in response.

For example, the below extension will open a new tab on example.com when you click on any website loaded after you install the extension.

// manifest.json
{
"name": "Open tab on page click",
"version": "1.0",
"manifest_version": 3,
"background": {
"service_worker": "background.js"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"]
}
]
}

// content.js
document.body.addEventListener("click", () => {
chrome.runtime.sendMessage("open-new-tab");
});

// background.js
chrome.runtime.onMessage.addListener((message, _sender, _sendResponse) => {
if(message == "open-new-tab") {
openExampleTab();
}
});

function openExampleTab() {
chrome.tabs.create({url: "https://example.com"});
}

Simeon - @dotproto
incremental.software

--
You received this message because you are subscribed to the Google Groups "Chromium Extensions" group.
To unsubscribe from this group and stop receiving emails from it, send an email to chromium-extens...@chromium.org.
To view this discussion on the web visit https://groups.google.com/a/chromium.org/d/msgid/chromium-extensions/96918d72-76b8-4bdc-86b6-c0e276361650n%40chromium.org.
Reply all
Reply to author
Forward
0 new messages