2017-10-27 8 views
1

ユーザーがページを更新しなくても、PHPセッションをアクティブに保つための小さなスクリプトを作成しました。ここで AJAX間隔を設定して、ページにまだフォーカスがある場合にのみリフレッシュする方法はありますか?

はJavascriptが私が生きているセッションを維持するためにPHPを経由して使用していている:それは正常に動作しますが、私はそれがページがある 場合でもrefreshTheSession.phpスクリプトを呼び出し続けることに気付きました

echo 'setInterval(function(){$.post(\'/refreshTheSession.php\');},90000);'; 

フォーカスが合っていない、これは誰かがそのページでタブを開いたままにして、別のタブで何か他の操作を行っていてもセッションを無期限に保つことを意味するからです。

ユーザーが問題のページにまだ積極的に参加している場合のみ、セッションを有効にします。

これは可能ですか?もしそうなら、上記のコードを変更するにはどうすればよいですか?

+2

https://stackoverflow.com/questions/3479734/javascript-jquery-test-if-window-has-focus – Connum

+0

また、チェックアウトhttps://developer.mozilla.org/enの可能性の重複-US/docs/Web/API/Page_Visibility_API – Connum

+0

@Connum:それは本当に私の質問に答えませんでした。私は 'if(document.hasFocus()){}'でJavascriptをラップしようとしましたが、動作しませんでしたが、ページにフォーカスがない場合でも 'refreshTheSession.php'スクリプトを呼び出していました。 – ProgrammerGirl

答えて

2

正確には「うまくいかなかった」とは言わないが、私がコメントした2番目のリンクである「ページビジビリティAPI」は、この実際の例のように、あなたが求めていることを間違いなく実行する:

function isDocumentVisible() { 
 
\t return !(document.hidden || document.webkitHidden || document.msHidden); 
 
} 
 

 
// this is what you'd output via PHP: 
 
setInterval(function(){ 
 
\t if (isDocumentVisible()) { 
 
    \t $.post('/refreshTheSession.php');} 
 
    } 
 
, 90000); 
 

 
// for the sake of demonstrating that this example is indeed working: 
 
window.setInterval(function() { 
 
console.log(isDocumentVisible() ? "document is visible, refresh session" : "document is not visible, don't refresh session"); 
 
}, 1000);

更新:document.setFocus()を使用して、それは次のようになります。

// this is what you'd output via PHP: 
 
setInterval(function(){ 
 
\t if (document.hasFocus()) { 
 
    \t $.post('/refreshTheSession.php');} 
 
    } 
 
, 90000); 
 

 
// for the sake of demonstrating that this example is indeed working: 
 
window.setInterval(function() { 
 
console.log(document.hasFocus() ? "document has focus, refresh session" : "document does not have focus, don't refresh session"); 
 
}, 1000);
Click into and out of the result iframe to see the focus change.

+0

解決策の問題点は、視認性を考慮に入れているものの、フォーカスがないことです。たとえば、画面を分割して2つのブラウザを並べて表示し、その横に表示されているものを残して、自分のサイトを持たないものでアクティブにすることができます。ユーザーが別のサイトでアクティブであっても、この場合、 'setInterval'を使って呼び出すのに' if(document.hasFocus()){$。post( '/ refreshTheSession.php');} 'のようなものはありませんか? (これはモバイルサイト用ですので、考慮する必要があります) – ProgrammerGirl

+0

要求通りに 'document.hasFocus()'を使用するように私の答えを更新しました。 – Connum

関連する問題