Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to use this inside chrome extension ? #104

Closed
AbbosRakhmonov opened this issue Jun 17, 2022 · 4 comments
Closed

How to use this inside chrome extension ? #104

AbbosRakhmonov opened this issue Jun 17, 2022 · 4 comments

Comments

@AbbosRakhmonov
Copy link

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
Copy link
Owner

apvarun commented Jun 19, 2022

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();
});

@apvarun apvarun closed this as completed Jun 19, 2022
@AbbosRakhmonov
Copy link
Author

AbbosRakhmonov commented Jun 19, 2022

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
Copy link
Owner

apvarun commented Jun 19, 2022

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
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants