Skip to content

Where is the proper place to parse text for YouTube videos? #584

@mark8044

Description

@mark8044

My YouTube urls in my HTML string are usually as follows

<a href="https://www.youtube.com/embed/tgbNymZ7vqY">https://www.youtube.com/embed/tgbNymZ7vqY</a>

OR

https://www.youtube.com/embed/tgbNymZ7vqY

I was previously successfully using a BuildOp to create a custom YouTube widget by regexing for YouTube urls inside .parse.

Now I've switched from flutter_widget_from_html_core to flutter_widget_from_html and am using your YouTube parser, but I need to get my YouTube video into a proper iframe format by parsing the html.

It looks like the .parse is happening after your YouTube parser.

When I put in the below code into .parse, which I previously used successfully as part of a BuildOp, the raw text HTML <iframe src="https://www.youtube.com/embed/..." allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"></iframe> shows up in the final output rather then a YouTube video.

I can get it to work by pre parsing the HTML before I even send it to HtmlWidget but Id rather parse it inside the widget itself so I can take advantage of the tree structure as my YouTube URLs are sometimes sitting inside <a></a> and sometimes not. Its also cleaner for me to do it inside HtmlWidget since I am using the widget in multiple places in my app


    if (meta.element.localName == 'a') {

      ///CHEK FOR YOUTUBE
      RegExp regExp = new RegExp(
        r'.*(?:(?:youtu\.be\/|v\/|vi\/|u\/\w\/|embed\/)|(?:(?:watch)?\?v(?:i)?=|\&v(?:i)?=))([^#\&\?]*).*',
        caseSensitive: false,
        multiLine: false,
      );

      final match = regExp.firstMatch(meta.element.text); 

      if (match != null)
      {

        /// YOUTUBE VIDEO CODE
        var youtubeCode = match.group(1);

        var _nText = '<iframe src="https://www.youtube.com/embed/'+youtubeCode.toString()+'" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"></iframe>';
        meta.register(BuildOp(
          onTree: (meta, tree) {
            tree.replaceWith(TextBit(tree, _nText));
          },
        ));

Metadata

Metadata

Assignees

Labels

questionFurther information is requested

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions