2016-05-08 45 views
0

我認爲下面的問題是範圍相關的,但我不是很好用jQuery插件模式,我該如何解決它?Jquery回調 - 未捕獲ReferenceError

詳細
我試圖修復an issue(跨域)本chrome extension

我想我找到(使用anyorigin.com)一個解決方案,但我得到了與$.getJSON一個新的問題:

Uncaught ReferenceError: jQuery19109374020271279013_1462700430014 is not defined: 

?url=https%3A//thepiratebay.cr/search/I%20Will%20Survive%201999/0/7/0&callback=jQuery19109374020271…:1 Uncaught ReferenceError: jQuery19109374020271279013_1462700430016 is not defined(anonymous function) @ ?url=https%3A//thepiratebay.cr/search/I%20Will%20Survive%201999/0/7/0&callback=jQuery19109374020271…:1 

這裏涉及的代碼doSearch()是我去問題的地方:

(function($) { 
     $.fn.extend({ 
      tpbSearch : function(options){ 
       var defaults = { searchTerm: ''}; 
       var options = $.extend(defaults, options); 
       return this.each(function(){ 
        doSearch($(this), options.searchTerm); 
       }) 
      } 
     }); 

     // private functions 
     // .... 

     function buildSearchUrl(searchTerm) 
     { 
      var searchPart = 'https://thepiratebay.cr/search/' + encodeURIComponent(searchTerm) + '/0/7/0'; 
      var searchUrl = 'http://anyorigin.com/get?url=' + escape(searchPart) + '&callback=?'; 

      return searchUrl; 
     } 
     // function where the issue happens. 
     function doSearch(container, searchTerm){ 
      // here we should iterate over the container selector, because it's possible multiple items will be selected. 
      var sanitizedSearchTerm = sanitizeSearchTerm(searchTerm); 

      // set the default logo 
      var loadingImageUrl = chrome.extension.getURL('images/ajax-loader.gif'); 
      var logo = $('<img id="tpb-logo">') 
         .attr('src', loadingImageUrl) 
         .css('width', '25px') 
         .css('height', '25px'); 
      container.children().remove(); 
      container.append(logo); 

      var searchUrl = buildSearchUrl(sanitizedSearchTerm); 

      $.getJSON(searchUrl, function(data){ 
       alert('aa'); 
      }); 
     } 
}(jQuery)); 

回答

1

無論如何,這並不是正確的方式。

如果遇到跨源問題,則需要爲該源定義主機權限。然後Chrome會忽略CORS。請參閱Google文檔中的Requesting cross-origin permissions


爲了完整起見,雖然我鼓勵你解決這個:

你這裏的錯誤是在內容腳本處理JSONP。 JSONP通過插入<script>元素來工作,但在頁面上下文中執行,而回調在separate content script context中。這給出了無法找到回調函數的錯誤。

因此,在內容腳本中使用JSONP非常尷尬,如果絕對需要應該委託給後臺頁面(與appropriate CSP considerations)。

+0

我不確定你是否對JSON部分是正確的(相同的命令,在js控制檯的同一頁上工作...)無論如何,你是完全正確的關於CORS和Chrome的分機。這就像一個魅力。 Thx – WonderLand

+1

嗯,該代碼來自內容腳本。那麼問題就是孤立的世界。我更新了答案是正確的。 – Xan

相關問題