I get embed codes (Instagram, Twitter and so on) from database. How to bind them to a vue component? Is there any way for executing script tag in v-html?
Asked
Active
Viewed 1.3k times
2 Answers
6
Short answer: You can't. Your browsers blocks the execution of script tags once the dom has loaded.
Long answer: You could try matching the src attribute of the script and fetch + evaluate it, or match the inner content of the div and evaluate it, but this is not recommended.

Antony
- 1,253
- 11
- 19
-
2Thanks for answer! As I understood v-html use innerHTML, which don't execute script tag. But there are some workarounds https://stackoverflow.com/questions/1197575/can-scripts-be-inserted-with-innerhtml – GrayRF Jun 19 '17 at 08:02
-
1This is the eval solution, which needs to you match the inner content of a script. I still strongly recommend you to avoid using this workaround and find a better solution instead – Antony Jun 19 '17 at 12:34
3
For the purpose of the title, the browser will block you.
However, for the purpose of the question, you can easily predict/list the embed codes you want to support, so this is something you could do:
if (window.twttr) {
// The script is already loaded, so just reload the embeds
window.twttr.widgets.load();
} else if (!document.getElementByID('twttr-widgets')) {
const embed = document.createElement('script');
embed.id = 'twttr-widgets'
embed.src = 'https://platform.twitter.com/widgets.js';
document.body.appendChild(embed);
// And when the script loads, the embeds will load too
}
This can easily be replicated for most embed libraries that allow you to "reload" all the widgets on the page:

jdrydn
- 50
- 1
- 4