Home > Back-end >  Custom jquery plugin: '$.myPlugin()' is not a function
Custom jquery plugin: '$.myPlugin()' is not a function

Time:10-08

Hello there I know this has been anwsered many times before, but none of the anwsers help me

am trying to load a jquery plugin to bypass cors during development

<html>

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>

<body>
  <script>
    $(document).ready(function() {
      $.get('https://google.com', function(r) {
        console.log(r);
      });
    });
  </script>


  <script>
    (function($) {
      $.fn.myPlugin = function() {
        $.ajaxPrefilter(function(options) {
          if (options.crossDomain) {
            options.url = "https://corsproxy.io/?"   options.url;
          }
        });
        return this;
      };
    }(jQuery));
  </script>
  <script>
    $.myPlugin();
  </script>
  <script></script>
</body>

</html>

but chrome is always throwing that the plugin is not a function

Uncaught TypeError: $.myPlugin is not a function

I am realy not sure what I am doing wrong here because it seams that the plugin is properly defined?

Thanks for Anwsering and Best Regards

CodePudding user response:

You've defined the plugin as $.fn.myPlugin(), so it needs to be instantiated on a jQuery object, eg. $('#foo').myPlugin().

However as your intended usage is against jQuery itself, therefore you don't need to use fn - $.myPlugin = function() ...

As a side note, your plugin relies on you setting crossDomain: true in the AJAX options, which your original example omitted. This setting will need to be reverted back to false for it to not interfere with the request itself.

(function($) {
  $.myPlugin = function() {
    $.ajaxPrefilter(function(options) {
      if (options.crossDomain) {
        options.url = "https://corsproxy.io/?"   options.url;
        options.crossDomain = false;
      }
    });
  };
}(jQuery));

$.myPlugin();

$(document).ready(function() {
  $.ajax({
    crossDomain: true,
    url: 'https://google.com',
    success: function(r) {
      console.log(r);
    }
  });
});
  • Related