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

Dynamic theme switching #401

Closed
mrsauravsahu opened this issue Oct 6, 2020 · 8 comments
Closed

Dynamic theme switching #401

mrsauravsahu opened this issue Oct 6, 2020 · 8 comments

Comments

@mrsauravsahu
Copy link
Contributor

mrsauravsahu commented Oct 6, 2020

I'm currently using utterances to add comments to my site. Sample is - https://mrsauravsahu.github.io/posts/39/ I have a theme toggle button in my navbar which allows to switch between light and dark themes. However, utterances loads directly when the page loads, so it does not respect the change in the theme attribute.

Is there a way to dynamically switch themes?

@tmshkr
Copy link

tmshkr commented Oct 6, 2020

You can dispatch a custom event on theme change, then handle it with a function that will remove the previous DOM node and then load the script again with the new theme.

https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events

@mrsauravsahu
Copy link
Contributor Author

Thanks @tmshkr
Worked great.
Closing this.

@tmshkr
Copy link

tmshkr commented Oct 7, 2020

Happy to help @mrsauravsahu

It would be ideal if the theme could be changed without having to reload the script. There seems to be a way to change the theme without reloading the script by using postMessage.

For example, if you execute the following code in your browser console, it should change the theme of the comments to dark:

document.querySelector("iframe.utterances-frame").contentWindow.postMessage({type: "set-theme", theme: "github-dark"});

But it only seems to work on utteranc.es or the utterances local dev environment. It doesn't seem to work on other sites.

@mrsauravsahu
Copy link
Contributor Author

I can give it a try.

@tmshkr
Copy link

tmshkr commented Oct 7, 2020

Ah, the targetOrigin needs to be specified. This works:

document
  .querySelector("iframe.utterances-frame")
  .contentWindow.postMessage(
    { type: "set-theme", theme: themeName },
    "https://utteranc.es/"
  )

@mrsauravsahu
Copy link
Contributor Author

Oh that makes sense. There is a check on the origin

@mrsauravsahu
Copy link
Contributor Author

Works great! Thanks @tmshkr
https://mrsauravsahu.github.io/blog/39/

@transitive-bullshit
Copy link

That worked for me -- thanks @tmshkr

KimBiYam added a commit to KimBiYam/KimBiYam.log that referenced this issue Jun 13, 2022
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

3 participants