JS デバイスタイプを取得する

  • 作成者:ayuan0625
  • 編集回数:13次
  • 最終更新:ayuan0625 于 2020-12-17
  • I. Overview

    1.1 Problem

    Sometimes it is necessary to determine whether the currently logged-in device is PC or mobile. The effect is as follows:

    1) PC:

    2020-11-03_16-27-42.png

    2) Mobile APP:

    2020-11-03_16-50-38.png

    3) Mobile H5

    2020-11-03_16-56-27.png


    1.2 Solution

    You can use JavaScript to determine the current device type:

    The navigator is an independent object in JavaScript, used to provide information such as the browser and operating system used by the user, in the form of navigator object properties. All browsers support this object. 

    The navigator object has a userAgent attribute, which will return the user's device operating system and browser information. At this time, userAgent can be used to determine whether it is an H5 browser or a PC browser.                                 

    The Mobile App cannot obtain the browser object navigator of Window. Then you can judge whether there is a navigator before, and if it does not exist, it is an App.

    II. Example

    2.1 Template design

    Create a new template and add button widget in the parameter pane, as shown below:

    2020-11-03_16-58-41.png

    Modify the button name to "Current Device Type", as shown below:

    2020-11-03_17-03-02.png


    2.2 JS event

    Add a click event to the button widget, as shown below:

    image.png

    if(!window.navigator) {  
        FR.Msg.alert("Message","Current Device:Mobile APP")
        }
        else{
            if(/Mobile|Android|webOS|iPhone|iPad|Phone/i.test(navigator.userAgent)){
                       FR.Msg.alert("Message","Current Device:Mobile H5");
           }
           else{
                   FR.Msg.alert("Message","Current Device:PC");
           }
    }


    2.3 Preview effect

    Save the template, select the pagination preview on PC, and when you click the button, the current device type will pop up, as shown in the figure at the beginning.

    For mobile devices, please click Mobile preview.

    III. Download template

    Attachment List


    Theme: FineReport カスタム開発
    既に最初
    既に最後
    • いいね
    • 良くない
    • 閲覧しただけ