IT박스

PhoneGap : 데스크톱 브라우저에서 실행 중인지 감지

itboxs 2020. 7. 19. 10:51
반응형

PhoneGap : 데스크톱 브라우저에서 실행 중인지 감지


모바일 버전에 PhoneGap : Build를 사용하는 웹 응용 프로그램을 개발 중이며 '데스크톱'및 모바일 버전에 대한 단일 코드베이스를 원합니다. PhoneGap 통화가 작동하는지 감지 할 수 있기를 원합니다 (예 : PhoneGap을 지원하는 모바일 장치 사용자).

나는 이것을 검색하고 간단한 방법이 없다고 믿을 수 없다. 많은 사람들이 제안을했습니다.

데스크톱 버전의 앱에서 PhoneGap Javascript 파일을 제거하지 않는 한 어떤 코드도 작동하지 않습니다.

지금까지 내가 찾은 유일한 솔루션은 브라우저 / 사용자 에이전트 스니핑이지만 가장 적은 것은 강력하지 않습니다. 더 나은 솔루션을 환영합니다!

편집 : 조금 더 나은 해결책은 약간의 시간 초과 후 PhoneGap 함수를 호출하는 것입니다. 작동하지 않으면 사용자가 데스크톱 웹 브라우저에 있다고 가정합니다.


이 코드를 사용합니다 :

if (navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry|IEMobile)/)) {
  document.addEventListener("deviceready", onDeviceReady, false);
} else {
  onDeviceReady(); //this is the browser
}

최신 정보

phonegap이 브라우저에서 실행 중인지 여부를 감지하는 다른 많은 방법이 있습니다. 여기 또 다른 훌륭한 옵션이 있습니다.

var app = document.URL.indexOf( 'http://' ) === -1 && document.URL.indexOf( 'https://' ) === -1;
if ( app ) {
    // PhoneGap application
} else {
    // Web page
}  

여기에 표시된대로 : 모바일 브라우저 또는 PhoneGap 애플리케이션 간 감지


나는 며칠 전에 그것에 관한 게시물을 썼습니다 . 이것은 PhoneGap이 무언가를 출시 할 때까지 찾을 수있는 최상의 솔루션입니다. 짧고 간단하며 완벽합니다 (가능한 모든 방법과 플랫폼에서 확인했습니다).

이 기능은 98 %의 경우 작업을 수행합니다.

/**
 * Determine whether the file loaded from PhoneGap or not
 */
function isPhoneGap() {
    return (window.cordova || window.PhoneGap || window.phonegap) 
    && /^file:\/{3}[^\/]/i.test(window.location.href) 
    && /ios|iphone|ipod|ipad|android/i.test(navigator.userAgent);
}

if ( isPhoneGap() ) {
    alert("Running on PhoneGap!");
} else {
    alert("Not running on PhoneGap!");
}

사례의 다른 2 %를 완료하려면 다음 단계를 따르십시오 (기본 코드에서 약간 변경됨).

소스가 포함 된 __phonegap_index.html 파일을 작성하십시오 .

<!-- __phonegap_index.html -->
<script type="text/javascript">
    function isPhoneGap() {
        //the function's content is as described above
    }

    //ensure the 98% that this file is called from PhoneGap.
    //in case somebody accessed this file directly from the browser.
    if ( isPhoneGap() )
        localStorage.setItem("isPhoneGap","1");

    //and redirect to the main site file.
    window.location = "index.html";
</script>

이제 기본적 으로 모든 PhoneGap 플랫폼 에서 시작 페이지를 index.html 에서 __phonegap_index.html로 변경하면 됩니다. 내 프로젝트 이름이 example 이고 변경 해야하는 파일은 PhoneGap 버전 2.2.0과 같습니다.

  • 아이폰 OS -CordovaLibApp/AppDelegate.m
  • 안드로이드 -src/org/apache/cordova/example/cordovaExample.java
  • 윈도우 8 -example/package.appxmanifest
  • 블랙 베리 -www/config.xml
  • 웹 OS -framework/appinfo.json
  • 바다 - src/WebForm.cpp(56 행)
  • Window Phone 7- 어디에서 (누군가 해당 플랫폼에서 여전히 개발하고 있습니까?)

마지막으로 PhoneGap에서 실행 중인지 여부에 관계없이 사이트의 어느 곳에서나 사용할 수 있습니다.

if ( localStorage.getItem("isPhoneGap") ) {
    alert("Running on PhoneGap!");
} else {
    alert("Not running on PhoneGap!");
}

도움이 되길 바랍니다. :-)


얼마 전에 답변을 받았지만 "PhoneGap.available"은 더 이상 존재하지 않습니다. 다음을 사용해야합니다.

if (window.PhoneGap) {
  //do stuff
}

또는 1.7 이후로 다음을 선호하십시오.

if (window.cordova) {
  //do stuff
}

EDIT 2019 : 의견에서 말했듯이 이것은 데스크톱 브라우저 빌드에 cordova lib를 포함하지 않은 경우에만 작동합니다. 물론 대상으로하는 각 장치에 대해 엄격한 최소 javascript / html / css 파일 만 포함하는 것이 좋습니다.


우리가 cordova / phonegap 애플리케이션에 있는지 확인하는 가장 신뢰할 수있는 방법은이 구성 AppendUserAgent를 사용하여 cordova 애플리케이션의 사용자 에이전트를 수정하는 입니다.

config.xml추가 :

<preference name="AppendUserAgent" value="Cordova" />

그런 다음 전화 :

var isCordova = navigator.userAgent.match(/Cordova/i))

왜?

  1. window.cordovadocument.addEventListener('deviceready', function(){});경주 조건이 적용됩니다
  2. navigator.standalone<content src="index.html" />웹 사이트 인 경우 작동하지 않습니다 (예 : <content src="https://www.example.com/index.html" />또는 cordova-plugin-remote-injection 사용 )
  3. 사용자 에이전트가 실제 브라우저인지 추측하기 위해 화이트리스트를 작성하는 것은 매우 복잡합니다. 안드로이드 브라우저는 종종 맞춤형 웹뷰입니다.

나는 이것이 가장 간단하다고 생각합니다. var isPhoneGap = (location.protocol == "file:")

작동하지 않는 일부 사람들을 위해 편집하십시오 . 그런 다음 시도해 볼 수 있습니다 (테스트되지 않았습니다)

var isPhoneGap = ! /^http/.test(location.protocol);

이것은 나를 위해 작동합니다 (1.7.0 실행)

if (window.device) {
  // Running on PhoneGap
}

데스크톱 Chrome 및 Safari에서 테스트되었습니다.


원래 포스터와 마찬가지로 phonegap 빌드 서비스를 사용하고 있습니다. 이틀과 거의 50 건의 테스트 빌드 후에, 나는 나에게 잘 맞는 우아한 솔루션을 생각해 냈습니다.

모바일 브라우저에서 테스트하고 실행하려고했기 때문에 UA 스니핑을 사용할 수 없었습니다. 나는 원래 cobberboy의 매우 기능적인 기술에 정착했습니다. "howPatientAreWe : 10000"지연 / 시간 초과가 브라우저 내 개발에 너무 많은 방해가 되었기 때문에 이것은 나에게 효과가 없었습니다. 더 낮게 설정하면 앱 / 장치 모드에서 테스트에 실패하는 경우가 있습니다. 다른 방법이 있어야했습니다 ...

phonegap 빌드 서비스를 사용하려면 phonegap.js앱의 파일을 서비스에 제출하기 전에 코드 저장소에서 파일을 생략 해야합니다 . 따라서 브라우저와 앱에서 실행 중인지 확인하기 위해 존재 여부를 테스트 할 수 있습니다.

또 하나의 경고, 나는 또한 jQueryMobile을 사용하고 있으므로 사용자 정의 스크립팅을 시작하기 전에 jQM과 phonegap을 모두 초기화해야했습니다. 다음 코드는 앱의 사용자 정의 index.js 파일 시작 부분 (jQuery 후, jQM 전)에 있습니다. 또한 phonegap 빌드 문서 <script src="phonegap.js"></script>는 HTML 어딘가에 있다고 말합니다 . 나는 그것을 완전히 버리고 $ .getScript ()를 사용하여 존재 여부를 테스트합니다.

isPhoneGap = false;
isPhoneGapReady = false;
isjQMReady = false;

$.getScript("phonegap.js")
.done(function () {
    isPhoneGap = true;
    document.addEventListener("deviceready", function () {
        console.log("phonegap ready - device/app mode");
        isPhoneGapReady = true;
        Application.checkReadyState();
    }, false);
})
.fail(function () {
    console.log("phonegap load failed - browser only");
    isPhoneGapReady = true;
    Application.checkReadyState();
});

$(document).bind("mobileinit", function () {
    Application.mobileInit();
    $(document).one("pageinit", "#Your_First_jQM_Page", function () {
        isjQMReady = true;
        Application.checkReadyState();
    });
});

Application = {
    checkReadyState: function () {
        if (isjQMReady && isPhoneGapReady) {
            Application.ready();
        }
    },
    mobileInit: function () {
        // jQM initialization settings go here
        // i.e. $.mobile.defaultPageTransition = 'slide';
    },
    ready: function () {
        // Both phonegap (if available) and jQM are fired up and ready
        // let the custom scripting begin!
    }
}

흥미롭게도 많은 답변이 있지만 다음 세 가지 옵션은 포함되어 있지 않습니다.

1 – cordova.js가 전역 범위에서 cordova 객체를 설정합니다. 그렇다면 Cordova 범위에서 실행 중일 가능성이 높습니다.

var isCordovaApp = !!window.cordova;

2 – Cordova는 데스크탑에서 HTML 문서를 열 때처럼 응용 프로그램을 실행합니다. HTTP 프로토콜 대신 FILE을 사용합니다. 이를 감지하면 앱이 로컬로로드되었다고 가정 할 수 있습니다.

var isCordovaApp = document.URL.indexOf('http://') === -1
  && document.URL.indexOf('https://') === -1;

3 – cordova 스크립트의로드 이벤트를 사용하여 컨텍스트를 감지하십시오. 스크립트 포함은 빌드 프로세스에서 쉽게 제거 할 수 있거나 브라우저에서 스크립트로드가 실패합니다. 이 전역 변수는 설정되지 않습니다.

<script src="../cordova.js" onload="javascript:window.isCordovaApp = true;"></script>

크레딧은 Adobe에서 Damien Antipa 로갑니다


이 방법을 사용합니다.

debug = (window.cordova === undefined);

debug될 것입니다 true, 브라우저 환경에 false장치에.


이것은 실행 가능한 것으로 보이며 프로덕션에 사용했습니다.

if (document.location.protocol == "file:") {
    // file protocol indicates phonegap
    document.addEventListener("deviceready", function() { $(initInternal);} , false);
}
else {
    // no phonegap, start initialisation immediately
    $(initInternal);
}

출처 : http://tqcblog.com/2012/05/09/detecting-phonegap-cordova-on-startup/


문제의 본질은 cordova.device가 정의되지 않은 한 코드가 Cordova가 장치가 지원되지 않는다고 설정했거나 Cordova가 여전히 준비 중이고 나중에 장치가 준비되어 있기 때문에 확실하지 않다는 것입니다 (또는 세 번째 옵션 : cordova가 제대로로드되지 않았습니다).

유일한 해결책은 대기 기간을 정의하고이 기간 후에 코드가 장치가 지원되지 않는다고 가정해야한다는 것을 결정하는 것입니다. cordova가 "지원되는 장치를 찾고 포기했습니다"라는 매개 변수를 설정하려고하지만 그러한 매개 변수가없는 것 같습니다.

이것이 설정되면 지원되는 장치가없는 상황에서 정확하게 특정 작업을 수행 할 수 있습니다. 필자의 경우 장치의 앱 시장에 대한 링크를 숨기는 것처럼.

나는 거의 모든 상황을 다루어야하는이 기능을 하나로 모았습니다. 장치 준비 핸들러, 장치 준비 핸들러 및 대기 시간을 정의 할 수 있습니다.

//Deals with the possibility that the code will run on a non-phoneGap supported
//device such as desktop browsers. Gives several options including waiting a while
//for cordova to load after all.
//In:
//onceReady (function) - performed as soon as deviceready fires
//patience 
//  (int) - time to wait before establishing that cordova will never load
//  (boolean false) - don't wait: assume that deviceready will never fire
//neverReady 
//  (function) - performed once it's established deviceready will never fire
//  (boolean true) - if deviceready will never fire, run onceReady anyhow
//  (boolean false or undefined) - if deviceready will never fire, do nothing
function deviceReadyOrNot(onceReady,patience,neverReady){

    if (!window.cordova){
            console.log('Cordova was not loaded when it should have been')
            if (typeof neverReady == "function"){neverReady();}
        //If phoneGap script loaded...
        } else {
            //And device is ready by now...
            if  (cordova.device){
                callback();
            //...or it's loaded but device is not ready
            } else {
                //...we might run the callback after
                if (typeof patience == "number"){
                    //Run the callback as soon as deviceready fires
                    document.addEventListener('deviceready.patience',function(){
                        if (typeof onceReady == "function"){onceReady();}
                    })
                    //Set a timeout to disable the listener
                    window.setTimeout(function(){
                        //If patience has run out, unbind the handler
                        $(document).unbind('deviceready.patience');
                        //If desired, manually run the callback right now
                        if (typeof neverReady == 'function'){neverReady();}
                    },patience);
                //...or we might just do nothing
                } else {
                    //Don't bind a deviceready handler: assume it will never happen
                    if (typeof neverReady == 'function'){neverReady();} 
                    else if (neverReady === true){onceReady();} 
                    else {
                       //Do nothing
                    }
                }
            }
    }

}

내가하는 방식은 브라우저 전용 버전의 cordova.js로 덮어 쓰는 전역 변수를 사용하는 것입니다. 기본 HTML 파일 (일반적으로 index.html)에는 순서에 따라 다음 스크립트가 있습니다.

    <script>
        var __cordovaRunningOnBrowser__ = false
    </script>
    <script src="cordova.js"></script> <!-- must be included after __cordovaRunningOnBrowser__ is initialized -->
    <script src="index.js"></script> <!-- must be included after cordova.js so that __cordovaRunningOnBrowser__ is set correctly -->

그리고 내부 cordova.js에는 간단하게 다음이 있습니다.

__cordovaRunningOnBrowser__ = true

모바일 장치를 빌드 할 때는 cordova.js가 사용되지 않고 대신 플랫폼 별 cordova.js 파일이 사용되므로 프로토콜, userAgent 또는 라이브러리에 관계없이이 방법은 100 % 정확하다는 이점이 있습니다. 변수 (변경 될 수 있음). cordova.js에 포함시켜야 할 다른 것들이있을 수 있지만 아직 무엇인지 모르겠습니다.


SlavikMe의 솔루션을 기반으로하는 다른 방법 :

index.htmlPhoneGap 소스에서 전달 된 쿼리 매개 변수 만 사용 하십시오. 즉, 안드로이드 대신에

super.loadUrl("file:///android_asset/www/index.html");

사용하다

super.loadUrl("file:///android_asset/www/index.html?phonegap=1");

SlavikMe에는 다른 플랫폼에서이 작업을 수행 할 수있는 훌륭한 목록이 있습니다.

그럼 당신 index.html은 단순히 이것을 할 수 있습니다 :

if (window.location.href.match(/phonegap=1/)) {
  alert("phonegap");
}
else {
  alert("not phonegap");
}

하나의 코드베이스를 유지하려면 코드가 실행중인 "플랫폼"이 중요합니다. 저에게이 "플랫폼"은 세 가지 다른 것이 될 수 있습니다.

  • 0 : 컴퓨터 브라우저
  • 1 : 모바일 브라우저
  • 2 : 폰갭 / 코르도바

플랫폼을 확인하는 방법 :

var platform;
try {
 cordova.exec(function (param) {
   platform = 2;
  }, function (err) {}, "Echo", "echo", ["test"]);
} catch (e) {
  platform = 'ontouchstart' in document.documentElement ? 1 : 0;
}

노트 :

  • cordova.js가로드 된 후에 만 ​​실행 해야합니다 (body onload (...), $ (document) .ready (...))

  • document.documentElement의 'ontouchstart' 는 터치 스크린이있는 랩톱 및 데스크탑 모니터에 표시되므로 데스크탑이지만 모바일 브라우저를보고합니다. 보다 정확한 검사를하는 방법은 여러 가지가 있지만 여전히 필요한 경우의 99 %를 처리하기 때문에 사용합니다. 당신은 항상 그 라인을 더 강력한 것으로 대체 할 수 있습니다.


아론 스

if (PhoneGap.available){
    do PhoneGap stuff;
}

GeorgeW의 솔루션은 정상이지만 실제 장치에서도 PhoneGap.available은 PhoneGap의 항목이로드 된 후에 만 ​​true입니다 (예 : document.addEventListener ( 'deviceready', onDeviceReady, false)의 onDeviceReady)가 호출되었습니다.

그 전에 알기 원하면 다음과 같이 할 수 있습니다.

runningInPcBrowser =
    navigator.userAgent.indexOf('Chrome')  >= 0 ||
    navigator.userAgent.indexOf('Firefox') >= 0

이 솔루션은 대부분의 개발자가 Chrome 또는 Firefox를 사용하여 개발한다고 가정합니다.


나는 같은 문제가 있습니다.

Cordova 클라이언트가로드 한 URL에 # cordova = true를 추가하고 웹 페이지에서 location.hash.indexOf ( "cordova = true")> -1을 테스트하려고합니다.


다음은 가장 최근의 PhoneGap / Cordova (2.1.0)에서 작동합니다.

작동 방식 :

  • 개념 상 매우 간단
  • 위의 시간 초과 솔루션 중 일부의 논리를 뒤집 었습니다.
  • device_ready 이벤트 등록 ( PhoneGap 문서에서 권장하는 대로 )
    • 시간 초과 후에도 이벤트가 계속 발생하지 않으면 브라우저를 가정하여 폴백합니다.
    • 반대로 위의 다른 솔루션은 일부 PhoneGap 기능 또는 기타 테스트 및 테스트 중단 관찰에 의존합니다.

장점 :

  • PhoneGap 권장 device_ready 이벤트를 사용합니다.
  • 모바일 앱에는 지연이 없습니다. device_ready 이벤트가 발생하자마자 진행합니다.
  • 사용자 에이전트 스니핑 없음 (앱을 모바일 웹 사이트로 테스트하여 브라우저 스니핑이 옵션이 아니 었습니다).
  • 문서화되지 않은 (따라서 취하기 쉬운) PhoneGap 기능 / 속성에 의존하지 않습니다.
  • 데스크탑 또는 모바일 브라우저를 사용하는 경우에도 cordova.js를 코드베이스에 유지하십시오. 따라서 이것은 OP의 질문에 대답합니다.
  • Wytze는 다음과 같이 언급했다. "코르도바가"지원되는 장치를 찾고 포기했다 "고 말하는 곳에 매개 변수를 설정하길 원하지만 그러한 매개 변수가없는 것 같습니다." 그래서 여기에 하나를 제공합니다.

단점 :

  • 시간이 초과되었습니다. 그러나 모바일 앱 로직은 지연에 의존하지 않습니다. 웹 브라우저 모드에서는 대체로 사용됩니다.

==

새로운 빈 PhoneGap 프로젝트를 만듭니다. 제공된 샘플 index.js에서 맨 아래의 "app"변수를 다음으로 바꾸십시오.

var app = {
    // denotes whether we are within a mobile device (otherwise we're in a browser)
    iAmPhoneGap: false,
    // how long should we wait for PhoneGap to say the device is ready.
    howPatientAreWe: 10000,
    // id of the 'too_impatient' timeout
    timeoutID: null,
    // id of the 'impatience_remaining' interval reporting.
    impatienceProgressIntervalID: null,

    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // `load`, `deviceready`, `offline`, and `online`.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
        // after 10 seconds, if we still think we're NOT phonegap, give up.
        app.timeoutID = window.setTimeout(function(appReference) {
            if (!app.iAmPhoneGap) // jeepers, this has taken too long.
                // manually trigger (fudge) the receivedEvent() method.   
                appReference.receivedEvent('too_impatient');
        }, howPatientAreWe, this);
        // keep us updated on the console about how much longer to wait.
        app.impatienceProgressIntervalID = window.setInterval(function areWeThereYet() {
                if (typeof areWeThereYet.howLongLeft == "undefined") { 
                    areWeThereYet.howLongLeft = app.howPatientAreWe; // create a static variable
                } 
                areWeThereYet.howLongLeft -= 1000; // not so much longer to wait.

                console.log("areWeThereYet: Will give PhoneGap another " + areWeThereYet.howLongLeft + "ms");
            }, 1000);
    },
    // deviceready Event Handler
    //
    // The scope of `this` is the event. In order to call the `receivedEvent`
    // function, we must explicity call `app.receivedEvent(...);`
    onDeviceReady: function() {
        app.iAmPhoneGap = true; // We have a device.
        app.receivedEvent('deviceready');

        // clear the 'too_impatient' timeout .
        window.clearTimeout(app.timeoutID); 
    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        // clear the "areWeThereYet" reporting.
        window.clearInterval(app.impatienceProgressIntervalID);
        console.log('Received Event: ' + id);
        myCustomJS(app.iAmPhoneGap); // run my application.
    }
};

app.initialize();

function myCustomJS(trueIfIAmPhoneGap) {
    // put your custom javascript here.
    alert("I am "+ (trueIfIAmPhoneGap?"PhoneGap":"a Browser"));
}

몇 달 전 앱을 시작할 때이 문제를 우연히 발견했습니다. 왜냐하면 앱을 " browser-compatible"(그 시나리오에서는 일부 기능 (오디오 녹음, 나침반 등)이 차단 될 것이라는 점을 이해 하기 위해)이되기를 원했기 때문 입니다.

100%앱 실행 컨텍스트를 미리 결정하는 유일한 (그리고 100 퍼센트 조건을 주장하는) 솔루션은 다음과 같습니다.

  • 모든 웹 컨텍스트에서 JS "flag"변수를 true로 초기화하고 false로 변경하십시오.

  • 따라서 " willIBeInPhoneGapSometimesInTheNearFuture()" 와 같은 호출을 사용할 수 있습니다 (물론 PRE-PG입니다. 물론 PG API를 호출 할 수 있는지 확인하는 POST-PG 방법이 필요하지만 그 방법은 사소합니다).

  • 그런 다음 " but how do you determine the execution context?"; 대답은 : "당신은하지 않습니다"(PG의 훌륭한 사람들이 API 코드에서 그렇게하지 않는 한, 당신이 믿을 수 있다고 생각하지 않기 때문에);

  • 이를 위해 빌드 스크립트를 작성합니다. 하나는 두 개의 변형이있는 하나의 코드베이스입니다.


아니 정말 데스크톱 브라우저에서 I 시험 butwhen 질문에 대한 답변은, 그냥 응용 프로그램에 견디는는 deviceready fireing하지 브라우저 부하를 만들 수있는 로컬 스토리지의 값을 설정합니다.

function main() {

    // Initiating the app here.
};

/* Listen for ready events from pheongap */
document.addEventListener("deviceready", main, false);

// When testing outside ipad app, use jquerys ready event instead. 
$(function() {

    if (localStorage["notPhonegap"]) {

        main();
    }
});

데스크톱 버전의 앱에서 PhoneGap Javascript 파일을 제거하지 않는 한 어떤 코드도 작동하지 않습니다.

다른 옵션은 병합 폴더 를 사용하는 것 입니다. 아래 스크린 샷을 참조하십시오.

플랫폼 별 파일을 추가하거나 기본 파일을 재정의 할 수 있습니다.

(일부 시나리오에서는 트릭을 수행해야 함)

여기에 이미지 설명을 입력하십시오


즉, 브라우저를 감지하는 대신 데스크탑 빌드를위한 특정 파일을 포함하지 않고 iOS 전용 파일을 첨부합니다.


에뮬레이션 장치가 활성화 된 경우에도 데스크탑 브라우저 감지

Windows 및 Mac 컴퓨터에서 작동합니다. Linux 용 솔루션을 찾아야합니다. 세부 정보보기

var mobileDevice = false;
if(navigator.userAgent.match(/iPhone|iPad|iPod|Android|BlackBerry|IEMobile/))
    mobileDevice = true; 

if(mobileDevice && navigator.platform.match(/Win|Mac/i))
    mobileDevice = false; // This is desktop browser emulator

if(mobileDevice) {
    // include cordova files
}

실제로 여기에 나열된 두 가지 기술의 조합이 가장 효과적이라는 것을 알았습니다. 먼저 Cordova / phonegap에 액세스 할 수 있는지 확인하고 장치를 사용할 수 있는지 확인하십시오. 이렇게 :

function _initialize() {
    //do stuff
}

if (window.cordova && window.device) {
    document.addEventListener('deviceready', function () {
      _initialize();
    }, false);
} else {
   _initialize();
}

이 접근법을 시도하십시오 :

/**
 * Returns true if the application is running on an actual mobile device.
 */
function isOnDevice(){
    return navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry)/);
}

function isDeviceiOS(){
    return navigator.userAgent.match(/(iPhone)/);
}

/**
 * Method for invoking functions once the DOM and the device are ready. This is
 * a replacement function for the JQuery provided method i.e.
 * $(document).ready(...).
 */
function invokeOnReady(callback){
    $(document).ready(function(){
        if (isOnDevice()) {
            document.addEventListener("deviceready", callback, false);
        } else {
            invoke(callback);
        }
    });
}

GeorgeWmkprogramming이 제안한 조합을 사용합니다 .

   if (!navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry)/)) {
      onDeviceReady();
   } else if (Phonegap.available){
      onDeviceReady();
   } else {
      console.log('There was an error loading Phonegap.')
   }

어쨌든 그들은 다르지 않은 것 같아요? 하하 .. 재미 없어 이것이 문제가되지 않을 것이라고 누가 생각하지 않았습니까? 고려할 가장 간단한 솔루션은 다음과 같습니다. 다른 파일을 서버로 푸시 한 다음 PhoneGap으로 이동하십시오. 나는 또한 일시적으로 http : check check 위에서 제안했다.

var isMobileBrowserAndNotPhoneGap = (document.location.protocol == "http:");

내 관심은 브라우저 탐색 메뉴를 위로 올리는 것입니다. 따라서 실제로 격리 된 스크립트의 태그를 삭제하고 [DW에서] 다시 빌드를 누를 수 있습니다 (어쨌든 배포를위한 정리가 수행되므로 이러한 작업 중 하나 일 수 있습니다). PG로 푸시 할 때 isMobileBrowserAndNotPhoneGap을 사용하여 수동으로 주석을 효율적으로 주석 처리하는 것이 좋은 옵션입니다. 내 상황에서 다시 한 번 나는 모바일 브라우저 일 때 navbar를 올리는 (격리 된 코드) 파일의 태그를 간단하게 삭제합니다 (훨씬 빠르고 작습니다). [그래서 최적화되었지만 수동 솔루션을 위해 코드를 분리 할 수 ​​있다면.]


약간 수정되었지만 문제없이 완벽하게 작동합니다.

의도는 데스크탑이 아닌 내장 장치에있을 때만 Cordova를로드하는 것이므로 데스크탑 브라우저에서 Cordova를 완전히 피합니다. UI와 MVVM의 테스트와 개발은 매우 편안합니다.

이 코드를 예로 들어 보자. cordovaLoader.js 파일에

function isEmbedded() {
    return  
    // maybe you can test for better conditions
    //&& /^file:\/{3}[^\/]/i.test(window.location.href) && 
     /ios|iphone|ipod|ipad|android/i.test(navigator.userAgent);
}

if ( isEmbedded() )
{
   var head= document.getElementsByTagName('head')[0];
   var script= document.createElement('script');
   script.type= 'text/javascript';
   script.src= 'cordova-2.7.0.js';
   head.appendChild(script);
}

그런 다음 cordova javascript 자체를 포함하는 대신 cordovaLoader.js를 포함하십시오.

<head>
  <script src="js/cordovaLoader.js"></script>
  <script src="js/jquery.js"></script>
  <script src="js/iscroll.js"></script>
  <script src="js/knockout-2.3.0.js"></script>
</head> 

당신의 일을 편하게하십시오! :)


if ( "device" in window ) {
    // phonegap
} else {
    // browser
}

그냥 정보를 원하시면의 방법 폰갭은 모바일 응용 프로그램 개발 핫샷을 3.X

var userLocale = "en-US";
function startApp()
{
// do translations, format numbers, etc.
}
function getLocaleAndStartApp()
{
    navigator.globalization.getLocaleName (
        function (locale) {
            userLocale = locale.value;
            startApp();
        },
        function () {
            // error; start app anyway
            startApp();
        });
}
function executeWhenReady ( callback ) {
    var executed = false;
    document.addEventListener ( "deviceready", function () {
        if (!executed) {
            executed = true;
            if (typeof callback === "function") {
                callback();
            }
        }
    }, false);
    setTimeout ( function () {
        if (!executed) {
            executed = true;
            if (typeof callback === "function") {
                callback();
            }
        }
    }, 1000 );
};
executeWhenReady ( function() {
    getLocaleAndStartApp();
} );

그리고 YASMF 프레임 워크에서

https://github.com/photokandyStudios/YASMF-Next/blob/master/lib/yasmf/util/core.js#L152


창 개체로 시도했지만 InAppBrowser에서 원격 URL을 열 때 작동하지 않았습니다. 완료하지 못했습니다. 그래서 그것을 달성하는 가장 쉽고 쉬운 방법은 phonegap 앱에서 열어야 할 URL에 문자열을 추가하는 것이 었습니다. 그런 다음 문서 위치에 문자열이 추가되어 있는지 확인하십시오.

아래는 간단한 코드입니다.

var ref = window.open('http://yourdomain.org#phonegap', '_blank', 'location=yes');

URL "#phonegap"에 문자열이 추가 된 것을 볼 수 있습니다. 따라서 도메인 URL에서 다음 스크립트를 추가하십시오.

if(window.location.indexOf("#phonegap") > -1){
     alert("Url Loaded in the phonegap App");
}

참고 URL : https://stackoverflow.com/questions/8068052/phonegap-detect-if-running-on-desktop-browser

반응형