2016-10-04 82 views
0

如何使用requirejs導入recaptcha。我已經嘗試了幾件事情,但沒有任何作用。reCaptcha + RequireJS

我需要這樣做,以便能夠使用ReCaptcha的方法渲染器一旦它被加載後呈現它。

require.config({ 
 
    paths: { 
 
     'recaptcha': 'http://www.google.com/recaptcha/api' 
 
    } 
 
}); 
 

 
require(['recaptcha'], function(recaptcha) { 
 
    // do something with recaptcha 
 
    // recaptcha.render /// at this point recaptcha is undefined 
 
    console.log(recaptcha); 
 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.2.0/require.min.js"></script>

回答

0

是我對你的解決方案。所以最終發生的事情是,直到它從谷歌API中加載它所需的內容後,才能渲染它。

所以你需要做的是以下(也不要使用HTTP/HTTPS在您的路徑):

require.config({ 
    paths: { 
     'recaptcha': '//www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit' 
    } 
}); 

現在將允許必要的庫已經被下載後執行回調來自google API。 這個回調不幸的是需要全球化。

JS

var requireConfig = { 
paths: { 
    'recaptcha': '//www.google.com/recaptcha/api.js? onload=onloadCallback&render=explicit' 
} 
}; 

function render(id) { 
    console.log('[info] - render'); 
    recaptchaClientId = grecaptcha.render(id, { 
    'sitekey': '6LdntQgUAAAAANdffhZl0tIHw0fqT3MwNOlAI-xY', 
    'theme': 'light' 
    }); 
}; 
window.renderRecaptcha = render; 

var onloadCallback = function() { 
    console.log('[info] - onLoadCallback'); 
    if (!document.getElementById('g-recaptcha')) { 
    return; 
    } 
    window.renderRecaptcha('g-recaptcha'); 
}; 

requirejs.config(requireConfig); 

require(['recaptcha'], function(recaptcha) { 

}); 

HTML

<body> 
    <form action="?" method="POST"> 
     <div id="g-recaptcha"></div> 
     <br/> 
     <input type="submit" value="Submit"> 
    </form> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.14/require.js"> </script> 


</body> 

我希望你的作品!

鏈接到實施例:https://jsbin.com/kowepo/edit?html,js,console,output

+0

請包括在一個的jsfiddle,一個jsbin或甚至堆棧片段形式的工作示例。當我嘗試向OP的代碼中添加'onload ='時,它不起作用。 – Louis

+0

嗨,對不起。我應該從一開始就這樣做。我已經編輯了一個鏈接到jsbin –

+0

是的,我明白了,它的工作原理,但並沒有多大幫助,因爲這些限制打破了我的組織:( –