Search code examples
vue.jsscript-tagoembed

How to integer an oembed javascript tag inside a VueJs component?


I have an "embed" field used by my users for transform a simple link to a rich content link (link with image, title, description, etc.).

Example: enter image description here

Note: I use this library to get all link information: oscarotero/Embed

As you can see, when you provide an url (a twitter tweet by example), the "code" parameter contain the HTML and script tags to include on my frontend:

<blockquote class="twitter-tweet"><p lang="en" dir="ltr">I am so hopelessly in love with <a href="https://twitter.com/ChucklefishLTD?ref_src=twsrc%5Etfw">@ChucklefishLTD</a> ‘s spooky logo <a href="https://twitter.com/TomJamesSlade/status/1315781356023173120">pic.twitter.com/2KtjCNOOUl</a></p>&mdash; Tom Slayed 🔪😱 (@TomJamesSlade) <a href="https://twitter.com/TomJamesSlade/status/1315781356023173120?ref_src=twsrc%5Etfw">October 12, 2020</a></blockquote> <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>

The problem is with VueJs and the script tag. When my ajax call is OK, I store all embed informations like that:

this.preview = response.embed

And inside my component, I display the html code with the "v-html" VueJs directive

<div v-if="preview['code']" v-html="preview['code']"></div>

The html is displayed :

enter image description here

The script tag is visible inside the code inspector :

enter image description here

But the script is not loaded :

I have the same problem with all oembed url who provide a javascript tag inside the response.

Note: If I try to load the script directly inside the component, VueJs return this error:

VueCompilerError: Tags with side effect ( and ) are ignored in client component templates

A solution on google is to use the "mounted" event, but it's not compatible with my context. Because the script I have to load is received from an api and can be different each time depending of the link.


Solution

  • it's bit late but here is an option: The api gives you the possibility to not send the script tag, so you can include it on your own in the html before. Add to the url a omit_script=true and it's gone in the result.

    Then you can insert the twitter block. Maybe you have to call twttr.widgets.load() to initialize the tweet.

    Edit: Since you're using the plugin, this should be working

    $embed = new Embed();
    
    $result = $embed->get('https://www.instagram.com/p/B_C0wheCa4V/');
    $result->setSettings([
        'oembed:query_parameters' => ['omit_script' => true]
    ]);
    $oembed = $info->getOEmbed();