2016-05-14 30 views
2

我有一個頁面,用戶會點擊它來發送邀請他的朋友在Gmail無法重定向使用javascript

這裏的用戶是按鈕

​​

這裏是JavaScript部分

function TwkInvite() { 
    alert('function is called'); 
    window.location.href = "https://accounts.google.com/o/oauth2/auth?client_id=*********-*************.apps.googleusercontent.com&redirect_uri=https://www.example.com/app/invite-send&scope=https://www.google.com/m8/feeds/&response_type=code"; 
} 

我已經試過window.location.href,window.location的,location.href一切

此功能正在執行完美的警報也執行,但我不知道它爲什麼不重定向到谷歌網站,只要我點擊按鈕頁面刷新

沒有錯誤打印,我檢查了mozilla控制檯但也沒有發現錯誤

+0

的可能的複製[window.location.href處理不工作:()(http://stackoverflow.com/questions/6109527/window-location-href-not-working) – Rahul

+2

'

+0

can y你看看這個http://stackoverflow.com/questions/6109527/window-location-href-not-working我希望它會有所幫助。它建議返回false或在location.href之後使用event.preventDefault()。 – Rahul

回答

2

你的問題說在控制檯中沒有錯誤,這意味着什麼導致重定向是一個默認操作。它可能會提交一個我們知道的表格。這會阻止父表單被提交,如果有的話。

您可以使用return false來防止發生這種情況。

<button onclick="TwkInvite();return false;" class="btn"> 
0

看起來像一個權限問題。

當我變成了這個片段,我在控制檯得到這個錯誤:

Refused to display 'https://accounts.google.com/o/oauth2/auth?client_id=*********-*************…/app/invite-send&scope=https://www.google.com/m8/feeds/&response_type=code' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'. 

function TwkInvite() {  
 
    window.location.href = "https://accounts.google.com/o/oauth2/auth?client_id=*********-*************.apps.googleusercontent.com&redirect_uri=https://www.example.com/app/invite-send&scope=https://www.google.com/m8/feeds/&response_type=code"; 
 
}
<button onclick="TwkInvite()" class="btn"> 
 
    <i class="fa fa-google"></i>Import your Gmail Contacts 
 
</button>

0

一切都在你的代碼不錯。 我嘗試以下方法和它的運行:

<script type="text/javascript"> 
     function TwkInvite() { 
     alert('function is called'); 
     window.location.href = "https://accounts.google.com/o/oauth2/auth?client_id=*********-*************.apps.googleusercontent.com&redirect_uri=https://www.example.com/app/invite-send&scope=https://www.google.com/m8/feeds/&response_type=code"; 
    } 
    </script> 

或包含在一個特定的JavaScript文件中的代碼和它的運行。

1

看起來您並不是阻止按鈕重新加載頁面,至少在Chrome中會這樣做。爲了防止這種情況發生,您必須防止發生默認事件。

這樣定義你的按鈕,這樣你將事件轉發參數你處理:

<button onclick="TwkInvite(event)" class="btn"> 

現在阻止默認事件與event.preventDefault()

function TwkInvite(e) { 
    alert('function is called'); 
    window.location.href = "https://accounts.google.com/o/oauth2/auth?client_id=*********-*************.apps.googleusercontent.com&redirect_uri=https://www.example.com/app/invite-send&scope=https://www.google.com/m8/feeds/&response_type=code"; 

    // The event is in window.event in IE 
    var e = e || window.event; 

    // e.prevenDefault() for modern browsers, e.returnValue for IE 
    e.preventDefault ? e.preventDefault() : (e.returnValue = false); 
}