teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

window\.nameを使わないソースに変更

2016/03/09 13:52

投稿

notable
notable

スコア415

answer CHANGED
@@ -4,31 +4,41 @@
4
4
  理論的には、次のようなJavaScriptで実現できる気がします。
5
5
  が、実環境で動かしてないので、動かないかもしれません…。
6
6
 
7
+ 【2016/03/09更新】
8
+ ソースを変更しました。よく考えると開いたウィンドウの参照があるので、`window.name`が取得できなくても直接`window.location`を変更すれば目的とする動作になります。
9
+ ブラウザ依存などあるかもしれませんが、FirefoxとChromeでは動作しました。
10
+
11
+ ```HTML
12
+ <!doctype html>
13
+ <html>
14
+ <head>
15
+ <title>sample</title>
16
+ <script src="https://code.jquery.com/jquery-2.2.1.min.js"></script>
7
- ```JavaScript
17
+ <script>
8
- $(function() {
18
+ $(function() {
9
- var windowRef;
19
+ var windowRef = null;
10
- var windowOpen = function(href){
20
+ var windowOpen = function(href) {
11
- var windowName = '_new';
12
- if(typeof windowRef != 'undefined') {
13
- if(windowRef.name != ''){
21
+ if(windowRef && !windowRef.closed) {
22
+ windowRef.location = href;
23
+ } else {
14
- windowName = windowRef.name;
24
+ windowRef = window.open(href);
15
- }
25
+ }
16
- }
17
- windowRef = window.open(href, windowName);
18
- return windowRef;
26
+ return windowRef;
19
- };
27
+ };
20
-
28
+
21
- $('#link1').click(function(e) {
29
+ var targetWindowOpen = function(e) {
22
- e.preventDefault();
30
+ e.preventDefault();
23
- windowOpen('index.html');
31
+ windowOpen($(this).attr('href'));
32
+ };
33
+
34
+ $('.targetWindowOpen').click(targetWindowOpen);
24
- });
35
+ });
25
- $('#link2').click(function(e) {
36
+ </script>
26
- e.preventDefault();
37
+ </head>
38
+ <body>
39
+ <a href="test.html" class="targetWindowOpen">link1</a><br>
40
+ <a href="https://ja-jp.facebook.com/" class="targetWindowOpen">link2</a><br>
41
+ <a href="https://www.google.co.jp/" class="targetWindowOpen">link3</a><br>
27
- windowOpen('index2.html');
42
+ </body>
28
- });
29
- $('#link3').click(function(e) {
30
- e.preventDefault();
43
+ </html>
31
- windowOpen('index3.html');
32
- });
33
- });
34
44
  ```