IT

iPhone Safari Web App이 새 창에서 링크를 엽니 다

lottoking 2020. 6. 9. 07:53
반응형

iPhone Safari Web App이 새 창에서 링크를 엽니 다


홈 화면에 아이콘을 추가 한 후 웹에 문제가 있습니다. 웹이 홈 화면에서 시작되면 모든 링크가 Safari의 새 창에서 열리고 전체 화면 기능이 손실됩니다. 어떻게 방지 할 수 있습니까? 나는 아무런 대답도 찾지 못했습니다. 답이없는 동일한 질문 만.


iWebKit 프레임 워크 에서 JavaScript 솔루션을 찾았습니다 .

var a=document.getElementsByTagName("a");
for(var i=0;i<a.length;i++)
{
    a[i].onclick=function()
    {
        window.location=this.getAttribute("href");
        return false
    }
}

여기에있는 다른 솔루션은 외부 링크 (Safari에서 외부 적으로 열려고 함)를 고려하지 않거나 상대 링크 (도메인이없는)를 고려하지 않습니다.

html5 mobile-boilerplate 프로젝트는이 요점에 연결되어 있으며 https://gist.github.com/1042026

그들이 작성한 최종 코드는 다음과 같습니다.

<script>(function(a,b,c){if(c in b&&b[c]){var d,e=a.location,f=/^(a|html)$/i;a.addEventListener("click",function(a){d=a.target;while(!f.test(d.nodeName))d=d.parentNode;"href"in d&&(d.href.indexOf("http")||~d.href.indexOf(e.host))&&(a.preventDefault(),e.href=d.href)},!1)}})(document,window.navigator,"standalone")</script>

jQuery를 사용하는 경우 다음을 수행 할 수 있습니다.

$("a").click(function (event) {
    event.preventDefault();
    window.location = $(this).attr("href");
});

이것은 iOS 6.1 및 Bootstrap JS 링크 (예 : 드롭 다운 메뉴 등)에서 작동합니다.

$(document).ready(function(){
    if (("standalone" in window.navigator) && window.navigator.standalone) {
      // For iOS Apps
      $('a').on('click', function(e){
        e.preventDefault();
        var new_location = $(this).attr('href');
        if (new_location != undefined && new_location.substr(0, 1) != '#' && $(this).attr('data-method') == undefined){
          window.location = new_location;
        }
      });
    }
  });

이것은 오래된 질문이며 여기에있는 많은 솔루션이 자바 스크립트를 사용하고 있습니다. 그 이후로 iOS 11.3이 출시되었으며 이제 scope 멤버를 사용할 수 있습니다 . 범위 멤버는 "/"해당 범위 아래의 모든 경로가 새 페이지를 열지 않는 URL 입니다.

범위 멤버는이 웹 응용 프로그램 응용 프로그램 컨텍스트의 탐색 범위를 나타내는 문자열입니다.

내 예는 다음과 같습니다.

{
  "name": "Test",
  "short_name": "Test",
  "lang": "en-US",
  "start_url": "/",
  "scope": "/",
  ...
}

자세한 내용은 여기를 참조 하십시오 . 또한 이 기능을 제공 할 생성기사용하는 것이 좋습니다 .

범위를 지정하면 모든 것이 Android와 유사하게 예상대로 작동하며 범위를 벗어난 대상은 Safari에서 열릴 수 있습니다 (상태 표시 줄의 작은 항목).


Davids 답변 및 Richards 의견에 따라 도메인 확인을 수행해야합니다. 그렇지 않으면 다른 웹 사이트에 대한 링크도 웹 응용 프로그램에 열립니다.

$('a').live('click', function (event)
{      
    var href = $(this).attr("href");

    if (href.indexOf(location.hostname) > -1)
    {
        event.preventDefault();
        window.location = href;
    }
});

jQuery Mobile을 사용하는 경우 data-ajax = 'false'속성을 사용할 때 새 창이 나타납니다. 실제로 이것은 $ .mobile.ajaxEnabled 설정에 의해 또는 target = ''속성을 사용하여 ajaxEnabled를 끄거나 외부 링크를 사용하거나 해제 할 때마다 발생합니다.

이것을 사용하여 고칠 수 있습니다.

$("a[data-ajax='false']").live("click", function(event){
  if (this.href) {
    event.preventDefault();
    location.href=this.href;
    return false;
  }
});

(live () 메소드에 대해 Richard Poole에게 감사합니다-bind ()와 함께 작동하지 않았습니다)

전역 적으로 ajaxEnabled를 끈 경우 [data-ajax = 'false']를 삭제해야합니다.

This took me rather long to figure out as I was expecting it to be a jQuery Mobile specific problem where in fact it was the Ajax linking that actually prohibited the new window.


This code works for iOS 5 (it worked for me):

In the head tag:

<script type="text/javascript">
    function OpenLink(theLink){
        window.location.href = theLink.href;
    }
</script>

In the link that you want to be opened in the same window:

<a href="(your website here)" onclick="OpenLink(this); return false"> Link </a>

I got this code from this comment: iphone web app meta tags


Maybe you should allow to open links in new window when target is explicitly set to "_blank" as well :

$('a').live('click', function (event)
{      
    var href = $(this).attr("href");

    // prevent internal links (href.indexOf...) to open in safari if target
    // is not explicitly set_blank, doesn't break href="#" links
    if (href.indexOf(location.hostname) > -1 && href != "#" && $(this).attr("target") != "_blank")
    {
        event.preventDefault();
        window.location = href;
    }

});

I've found one that is very complete and efficient because it checks to be running only under standalone WebApp, works without jQuery and is also straightforward, just tested under iOS 8.2 :

Stay Standalone: Prevent links in standalone web apps opening Mobile Safari


You can also do linking almost normally:

<a href="#" onclick="window.location='URL_TO_GO';">TEXT OF THE LINK</a>

And you can remove the hash tag and href, everything it does it affects appearance..


This is what worked for me on iOS 6 (very slight adaptation of rmarscher's answer):

<script>                                                                
    (function(document,navigator,standalone) {                          
        if (standalone in navigator && navigator[standalone]) {         
            var curnode,location=document.location,stop=/^(a|html)$/i;  
            document.addEventListener("click", function(e) {            
                curnode=e.target;                                       
                while (!stop.test(curnode.nodeName)) {                  
                    curnode=curnode.parentNode;                         
                }                                                       
                if ("href" in curnode && (curnode.href.indexOf("http") || ~curnode.href.indexOf(location.host)) && curnode.target == false) {
                    e.preventDefault();                                 
                    location.href=curnode.href                          
                }                                                       
            },false);                                                   
        }                                                               
    })(document,window.navigator,"standalone")                          
</script>

This is slightly adapted version of Sean's which was preventing back button

// this function makes anchor tags work properly on an iphone

$(document).ready(function(){
if (("standalone" in window.navigator) && window.navigator.standalone) {
  // For iOS Apps
  $("a").on("click", function(e){

    var new_location = $(this).attr("href");
    if (new_location != undefined && new_location.substr(0, 1) != "#" && new_location!='' && $(this).attr("data-method") == undefined){
      e.preventDefault();
      window.location = new_location;
    }
  });
}

});


For those with Twitter Bootstrap and Rails 3

$('a').live('click', function (event) {
  if(!($(this).attr('data-method')=='delete')){
    var href = $(this).attr("href");
    event.preventDefault();
    window.location = href; 
  }   
});

Delete links are still working this way.


I prefer to open all links inside the standalone web app mode except ones that have target="_blank". Using jQuery, of course.

$(document).on('click', 'a', function(e) {
    if ($(this).attr('target') !== '_blank') {
        e.preventDefault();
        window.location = $(this).attr('href');
    }
});

One workaround i used for an iOS web app was that I made all links (which were buttons by CSS) form submit buttons. So I opened a form which posted to the destination link, then input type="submit" Not the best way, but it's what I figured out before I found this page.


I created a bower installable package out of @rmarscher's answer which can be found here:

http://github.com/stylr/iosweblinks

You can easily install the snippet with bower using bower install --save iosweblinks


For those using JQuery Mobile, the above solutions break popup dialog. This will keep links within webapp and allow for popups.

$(document).on('click','a', function (event) {
    if($(this).attr('href').indexOf('#') == 0) {
        return true;
    }
    event.preventDefault();
    window.location = $(this).attr('href');     
});

Could also do it by:

$(document).on('click','a', function (event){
    if($(this).attr('data-rel') == 'popup'){
        return true;
    }
    event.preventDefault();
    window.location = $(this).attr('href');     
});

Here is what I'd use for all links on a page...

document.body.addEventListener(function(event) {
    if (event.target.href && event.target.target != "_blank") {
        event.preventDefault();
        window.location = this.href;                
    }
});

If you're using jQuery or Zepto...

$("body").on("click", "a", function(event) {
   event.target.target != "_blank" && (window.location = event.target.href);
});

You can simply remove this meta tag.

<meta name="apple-mobile-web-app-capable" content="yes">

참고URL : https://stackoverflow.com/questions/2898740/iphone-safari-web-app-opens-links-in-new-window

반응형