Webapp guide#

Как веб-приложение встраивается в оболочку#

Веб-приложение представлено в формате в веб-контейнера, который запускается как приложение Ubuntu в оболочке Ubuntu/Unity.

Рассмотрим поближе:

At the innermost level, there is a website that the developer identifies by URL. The website is rendered and runs in a Qt WebEngine based webview. The webview is provided by the pre-installed Morph browser and automatically handles things like file dialogs (using ContentHub), downloads, permissions, etc.

Запуск#

Можно запустить веб-приложение из терминала командой::

webapp-container URL

Например::

webapp-container https://www.ubuntu.com

This simple form works, but almost every webapp uses other features as well, such as URL containment with URL patterns as described below.

Пользовательский интерфейс#

Веб-приложение обычно разворачивается на все рабочее пространство на экране устройства без необходимости использования элементов управления пользовательского интерфейса стандартных браузеров.

In some cases some navigation controls are appropriate, such as Back and Forward buttons, or an address bar. These are enabled with command line arguments:

  • --enable-back-forward. Включение отображение кнопок «назад» и «вперед» на панели инструментов (в нижней части окна веб-приложения)

  • --enable-addressbar. Включение отображение адресной строки (внизу окна веб-приложения)

URL-шаблоны#

Разработчики веб-приложений часто хотят ограничить доступ к сайту-источнику. То есть разработчик хочет контролировать URL-адреса, которые можно открыть в веб-приложении (все остальные URL-адреса открываются в браузере). Это делается с помощью URL-шаблонов в командной строке через ключи для запуска webapp.

Однако многие веб-приложения используют страницы, размещенные на нескольких сайтах или внешних ресурсах.

Both containment and access to specified external URLs are implemented with URL patterns provided as arguments at launch time. Let’s take a closer look.

По умолчанию - нет контейнера#

По умолчанию, URL отсутствует. Предположим, Вы запускаете веб-приложение без каких-либо шаблонов, и в нём есть только URL-адрес, например::

webapp-container https://www.ubuntu.com

Пользователь может перейти на любой сайт без ограничений. Например, если нажать на кнопку «Developer» ( «режим разработчика») вверху, то откроется сайт developer.ubuntu.com.

Примечание: можно увидеть URL-адрес, если включить адресную строку командой --enable-addressbar.

Простые методики ограничения пользовательской активности на сайте#

Часто хочется ограничить активность пользователя только одним сайтом. Например, веб-сайт www.ubuntu.com не пускает пользователей своего веб-приложения дальше домена ubuntu.com. Это можно сделать, если добавить шаблонURL-адреса с подстановочными символами в команду запуска, как показано ниже ::

webapp-container --webappUrlPatterns=https://www.ubuntu.com/* https://www.ubuntu.com
--webappUrlPatterns= указывает на то, что шаблон следующий

https://www.ubuntu.com/* is the pattern The asterisk is a wildcard that matches any valid sequence of characters in a URL

With this launch command and URL pattern, the user can navigate to and open in the webapp any URL that starts with https://www.ubuntu.com/. For example, they can click on the Phone button (https://www.ubuntu.com/phone) in the banner and it opens in the webapp, or the Tablet button (https://www.ubuntu.com/tablet). But, clicking Developer opens the corresponding URL in the browser.

Tip: Make sure to specify the protocol in your starting URL, that is, use https://www.ubuntu.com instead of www.ubuntu.com. Not specifying the protocol would create an ambiguous URL and thus introduce security concerns.

Более сложные шаблоны#

Может возникнуть необходимость ограничить доступ к некоторым разделам сайта из веб-приложения. Это легко делается с помощью подстановочных шаблонов (wildcards). Ссылки на другие под-домены открываются в браузере. Например, вот как получить доступ к страницам www.ubuntu.com/desktop/features и www.ubuntu.com/phone/features, но при этом запретить открывать страницы www.ubuntu.com/desktop или www.ubuntu.com/phone:

webapp-container --webappUrlPatterns=https://www.ubuntu.com/*/features https://www.ubuntu.com

Использование нескольких шаблонов одновременно#

Можно использовать несколько шаблонов, разделяя их запятой. Например, в этом примере разрешим доступ только к страницам www.ubuntu.com/desktop/features и www.ubuntu.com/phone/features::

webapp-container --webappUrlPatterns=https://www.ubuntu.com/desktop/features,https://www.ubuntu.com/phone/features  https://www.ubuntu.com

Примечание: использование нескольких шаблонов обычно необходимо, чтобы корректно работала необходимая политика ограничения доступа к ресурсам.

Добавление определенного под-домена#

У многих URL-адресов имеется один или несколько поддоменов. (Например, в дальнейших примерах «developer» - это поддомен сайта developer.ubuntu.com). Можно разрешить доступ к одному поддомену (и всем его подстраницам) с помощью шаблона::

--webappUrlPatterns=https://developer.ubuntu.com/*

However, one usually wants the user to be able to navigate back to the starting URL (and its subpages). So, if the starting URL is https://www.ubuntu.com, a second pattern is needed::

--webappUrlPatterns=https://developer.ubuntu.com/*,https://www.ubuntu.com/*

Putting these together, here’s an example that starts on https://www.ubuntu.com and allows navigation to https://developer.ubuntu.com and subpages and back to https://www.ubuntu.com and subpages::

webapp-container --webappUrlPatterns=https://developer.ubuntu.com/*,https://www.ubuntu.com/*  https://www.ubuntu.com

Добавление под-доменов с помощью шаблона#

В некоторых URL содержится под-доменов. Например, в состав www.ubuntu.com входят также ресурсы design.ubuntu.com, developer.ubuntu.com и другие. Можно разрешить доступ ко всем поддоменам с помощью специального символа-шаблона в строке с под-доменами::

webapp-container --webappUrlPatterns=https://*.ubuntu.com/*  https://www.ubuntu.com

Note: An asterisk in the subdomain position matches any valid single subdomain. This single pattern is sufficient to enable browsing to any subdomain and subpages, including back to the starting URL (https://www.ubuntu.com) and its subpages.

Adding http#

Sometimes a site uses http for some of its URLs. In general this is unsafe and should be avoided, but here is an example that allows access to www.launchpad.net on both https and http inside the webapp (and all subpages due to the wildcard)::

webapp-container --webappUrlPatterns=https?://www.launchpad.net/* https://www.launchpad.net

Примечание: для чего нужен знак вопроса после https? Это значит, что предыдущий символ («s») является необязательным. Если нужно использовать только https, знак вопроса указывать не нужно.

Аргументы командной строки#

У контейнера webapp есть множество опций для точной настройки различных веб-приложений.

Все команды можно посмотреть в справке::

webapp-container --help

Примечание. К версии Ubuntu с режимом конвергентности применяются только следующие параметры:

--fullscreen Display full screen
--inspector[=PORT] Run a remote inspector on a specified port or 9221 as the default port
--app-id=APP_ID Run the application with a specific APP_ID
--name=NAME Display name of the webapp, shown in the splash screen
--icon=PATH Icon to be shown in the splash screen. PATH can be an absolute or path relative to CWD
--webappUrlPatterns=URL_PATTERNS List of comma-separated url patterns (wildcard based) that the webapp is allowed to navigate to
--accountProvider=PROVIDER_NAME Online account provider for the application if the application is to reuse a local account.
--accountSwitcher Enable switching between different Online Accounts identities
--store-session-cookies Store session cookies on disk
--enable-media-hub-audio Enable media-hub for audio playback
--user-agent-string=USER_AGENT Overrides the default User Agent with the provided one.

Параметры браузера Chrome (браузер Chrome по умолчанию отключен)::

--enable-back-forward Enable the display of the back and forward buttons (implies --enable-addressbar)
--enable-addressbar Enable the display of a minimal chrome (favicon and title)

Примечание. Другие доступные параметры относятся только к веб-приложениям для настольных компьютеров. Не рекомендуем их использовать.

Изменение строки User-Agent#

Некоторые веб-сайты проверяют строку-идентификатора веб-браузер, так называемый «User-Agent», чтобы включить определенные функции или адаптировать дизайн. Иногда требуется изменить User-Agent, отправляемый веб-приложением.

Из командной строки это можно сделать с помощью следующей команды::

--user-agent-string='<string>' Replaces the default user-agent string by the string specified as a parameter

Хранение данных браузера#

The webapp experience is contained and isolated from the browser data point of view. That is webapps do not access data from any other installed browser, such as history, cookies and so on. Other browsers on the system do not access the webapp’s data.

Хранилище данных#

Following storage options are supported: Local/Session Storage, IndexedDB and the deprecated WebSQL. FileSystem API is not supported because apps cannot access the filesystem directly.