开发者

jquery Linkify: Firefox displaying "/#%21/..." instead of "/#!/..." in href attr after linkification

开发者 https://www.devze.com 2023-03-07 00:48 出处:网络
It\'s odd, I really don\'t know what else to check... I\'m using this code for linkifying URLs... And the URLs with a hash like Twitter http://twitter.com/#!/username/status/1234567890

It's odd, I really don't know what else to check... I'm using this code for linkifying URLs...

And the URLs with a hash like Twitter http://twitter.com/#!/username/status/1234567890

Firefox shows this on the href: http://twitter.com/#%21/username/status/1234567890

The link works, but unfortunately, this brokes the Embedly plugin to auto-embed Tweets. In Chrome and Safari both, the Link and the autoEmbed are working fine. I checked on Firefox with an url without the "#!" and it works too...

So, I need to get Firefox to use "!" instead of "%21" (or any other special character for that matter)

Any clue on how to fix this?

Here is my .linkify code:

// encoding: utf-8
// $.fn.linkify 1.0 - MIT/GPL Licensed - More info: http://github.com/maranomynet/linkify/
(function($){

var 
noProtocolUrl = /(^|["'(\s]|<)((?:[a-z0-9-]+\.)+(?:ac|ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|asia|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cat|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|info|int|io|iq|ir|is|it|je|jm|jo|jobs|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mil|mk|ml|mm|mn|mo|mobi|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tel|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|travel|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|xxx|ye|yt|za|zm|zw)(?:\/[a-zA-Z0-9_][^\s]*)?)((?:[:?]|\.+)?(?:\s|$)|>|[)"',])/g,
httpOrMailtoUrl = /\b((?:[a-z][\w-]+:)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/gi,
linkifier = function ( html ) {
    return FormatLink(html
                .replace( noProtocolUrl, '$1<a href="<``>://$2" rel="nofollow external" class="external_link">$2</a>$3' )  // NOTE: we escape `"http` as `"<``>` to make sure `httpOrMailtoUrl` below doesn't find it as a false-positive
                .replace( httpOrMailtoUrl, '<a href="$1" rel="nofollow external" class="external_link">$1</a>' )
                .replace( /"<``>/g, '"http' ));  // reinsert `"http`
  },

    linkify = $.fn.linkify = function ( cfg ) {
      if ( !$.isPlainObject( cfg ) )
      {
        cfg = {
            use:         (typeof cfg == 'string') ? cfg : undefined,
            handleLinks: $.isFunction(cfg) ? cfg : arguments[1]
          };
      }
      var use = cfg.use,
          allPlugins = linkify.plugins || {},
          plugins = [linkifier],
          tmpCont,
          newLinks = [],
          callback = cfg.handleLinks;
      if ( use == undefined ||  use == '*' ) // use === undefined  ||  use === null
      {
        for ( var name in allPlugins )
        {
          plugins.push( allPlugins[name] );
        }
      }
      else
      {
        use = $.isArray( use ) ? use : $.trim(use).split( / *, */ );
        var plugin,
            name;
        for ( var i=0, l=use.length;  i<l;  i++ )
        {
          name = use[i];
          plugin = allPlugins[name];
          if ( plugin )
          {
            plugins.push( plugin );
          }
        }
      }

      this.each(function () {
          var childNodes = this.childNodes,
              i = childNodes.length;
          while ( i-- )
          {
            var n = childNodes[i];
            if ( n.nodeType == 3 )
            {
              var html = n.nodeValue;
              if ( html.length>1  &&  /\S/.test(html) )
              {
                var htmlChanged,
                    preHtml;
                tmpCont = tmpCont || $('<div/>')[0];
                tmpCont.innerHTML = '';
                tmpCont.appendChild( n.cloneNode(false) );
                var tmpContNodes = tmpCont.childNodes;

                for (var j=0, plugin; (plugin = plugins[j]); j++)
                {
                  var k = tmpContNodes.length,
                      tmpNode;
                  while ( k-- )
                  {
                    tmpNode = tmpContNodes[k];
                    if ( tmpNode.nodeType == 3 )
                    {
                      html = tmpNode.nodeValue;
                      if ( html.length>1  &&  /\S/.test(html) )
                      {
                        preHtml = html;
                        html = html
                                  .replace( /&/g, '&amp;' )
                                  .replace( /</g, '&lt;' )
                                  .replace( />/g, '&gt;' );
                        html = $.isFunction( plugin ) ? 
                                    plugin( html ):
                                    html.replace( plugin.re, plugin.tmpl );
                        htmlChanged = htmlChanged || preHtml!=html;
                        preHtml!=html  &&  $(tmpNode).after(html).remove();
                      }
                    }
                  }
                }
                html = tmpCont.innerHTML;
                if ( callback )
                {
                  html = $('<div/>').html(html);
                  //newLinks.push.apply( newLinks,  html.find('a').toArray() );
                  newLinks = newLinks.concat( html.find('a').toArray().reverse() );
                  html = html.contents();
                }
                htmlChanged  &&  开发者_开发问答$(n).after(html).remove();
              }
            }
            else if ( n.nodeType == 1  &&  !/^(a|button|textarea)$/i.test(n.tagName) )
            {
              arguments.callee.call( n );
            }
          };
      });
      callback  &&  callback( $(newLinks.reverse()) );
      return this;
    };

      linkify.plugins = {
       // default mailto: plugin
      mailto: {
      re: /(^|["'(\s]|&lt;)([^"'(\s&]+?@.+\.[a-z]{2,7})(([:?]|\.+)?(\s|$)|&gt;|[)"',])/gi,
      tmpl: '$1<a href="mailto:$2">$2</a>$3'
    },
  topickrUser: {
//        re: /(^|["'(]|&lt;|\s)@([a-z0-9_-]+)((?:[:?]|\.+)?(?:\s|$)|&gt;|[)"',])/gi,
      re: /(^|\s)@(\w+)/gi,
      tmpl: '$1@<a href="http://topickr.com/$2">$2</a>'
  },
      topickrHashtag: {
          re: /(^|["'(]|&lt;|\s)(#.+?)((?:[:?]|\.+)?(?:\s|$)|&gt;|[)"',])/gi,
      tmpl: function (match, pre, hashTag, post) {
            return pre+'<a href="http://topickr.com/search.php?q='+ encodeURIComponent(hashTag) +'">'+hashTag+'</a>'+post;
      }
  }
  };

  function FormatLink(a) {
  // Configurable settings
  var wbrPosition = 25;
  var hellipPosition = 40;
  var wbr = '<wbr></wbr>';
  var hellip = '&hellip;';

  // Put the data into a span, makes it so we can alter it without losing surrounding text.
  var link = $('<span>' + a + '</span>');

  // If no href, this is not a URL. Pass it back.
  if (link.find('a').attr('href') == undefined) {
      return a;
  }

  jQuery.each(link.find('a'), function () {
      var original = $(this).html() + '</a>';
      var updated = $(this);
      // Set length
      var length = updated.html().length;

      if (length > hellipPosition) {
          updated.html(updated.html().substr(0, hellipPosition) + hellip);
      }

      if (length > wbrPosition) {
          updated.html(updated.html().substr(0, wbrPosition) + wbr + updated.html().substr(wbrPosition, length));
      }

      if (link.html() !== null && link.find('a').html() !== null && original !== null && updated.html() !== null) {
          var changes = link.html().replace(original, updated.html() + '</a>');
          if (changes !== null && changes !== '') {
              link.html(changes);
          }
      }
  });

  return link.html();
  }

 })(jQuery);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号