apvarun / toastify-js

Pure JavaScript library for better notification messages
https://apvarun.github.io/toastify-js/
MIT License
2.09k stars 230 forks source link

How to use this inside chrome extension ? #104

Closed AbbosRakhmonov closed 2 years ago

AbbosRakhmonov commented 2 years ago

I am currently creating a single chrome extension. One of its functions is to send a toast to the user. I want to do this using this library, can you help?

apvarun commented 2 years ago

Hi @AbbosRakhmonov

In order to use Toastify in a chrome extension, you'll need to do the following.

  1. Declare a content script in manifest.json file for extension.
  2. Include the CSS and JS files from the toastify CDN link or via local file ( using web_accessible_resources )
  3. Call the toast function as required

Some sample code:

// Add CSS file
const style = document.createElement('link');
style.rel = 'stylesheet';
style.type = 'text/css';
style.href = 'https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.css';
(document.head||document.documentElement).appendChild(style);

// Add JS file
const script = document.createElement('script');
script.type = 'text/javascript';
script.href = 'https://cdn.jsdelivr.net/npm/toastify-js';
document.body.appendChild(script);

// Trigger a notification
script.addEventListener('load', function() {
  Toastify({ text: "This is a toast" }).showToast();
});
AbbosRakhmonov commented 2 years ago

Hi @apvarun Thanks for your answer, but it is not worked, console shows error like this image

I need to use it in background.js because toastify should work when the user selects a word, opens the context menu in the browser and clicks on the extension icon.

apvarun commented 2 years ago

It is not possible to use it in background.js since the styles won't be loaded and there will be no DOM in background.

A way to achieve this is to use postMessage API available to chrome extensions. You can trigger a message from background.js and then receive it in content scripts where you then load toastify css&js (only if its not loaded already) and then trigger a toast.

AbbosRakhmonov commented 2 years ago

I also used postMessage. But content.js show toastify is not defined