1

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

1 Answer 1

0

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);
    }
  });
});
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, I can't believe noone mentioned this before :)
How would settings crossDomain: true interfere with the request itself?
I can't believe no-one mentioned this before - not sure what you mean by this as this answer was pretty quick after you asked. The reason you won't find this on "how to create a jquery plugin" type tutorials (such as jquery plugin creation) is because you haven't actually created a plugin, you've added a method to $
@LimetaPeta it's because using crossDomain: true is an outdated way of telling jQuery that you expect the response to be in JSONP format, which won't be the case when you're proxying the request.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.