Extension:MobileFrontend/ru

Category:GPL licensed extensions/ru
Справка по расширениям MediaWiki
MobileFrontend
Статус релиза: стабильноCategory:Stable extensions/ru
Реализация Пользовательский интерфейсCategory:User interface extensions/ru, Хук Category:Hook extensions/ru
Описание Обеспечивает удобный вид на мобильных устройствах
Автор(ы)
Последняя версия 2.4.1
Политика совместимости Снэпшоты выходят вместе с MediaWiki. Мастер не имеет обратной совместимости.
MediaWiki 1.33+[1]Category:Extensions with manual MediaWiki version/ru
PHP 5.5.9+
Лицензия GNU General Public License 2.0 или позднее
Скачать Category:Extensions in Wikimedia version control/ru
README
Пример m.mediawiki.org
  • $wgMFSearchGenerator
  • $wgMFStopRedirectCookieHost
  • $wgMFShowMobileViewToTablets
  • $wgMFLazyLoadImages
  • $wgMFRSSFeedLink
  • $wgMFNamespacesWithLeadParagraphs
  • $wgMFAmcOutreachMinEditCount
  • $wgMFEnableMobilePreferences
  • $wgMFMobileFormatterOptions
  • $wgMFRemovableClasses
  • $wgMFNoindexPages
  • $wgMFShowFirstParagraphBeforeInfobox
  • $wgMFEnableVEWikitextEditor
  • $wgMFVaryOnUA
  • $wgMFLogWrappedInfoboxes
  • $wgMFDisplayWikibaseDescriptions
  • $wgMFEnableJSConsoleRecruitment
  • $wgMobileFrontendFormatCookieExpiry
  • $wgMFLazyLoadSkipSmallImages
  • $wgMFSearchAPIParams
  • $wgMFMobileHeader
  • $wgMFCustomSiteModules
  • $wgMFEnableXAnalyticsLogging
  • $wgMFAutodetectMobileView
  • $wgMFSiteStylesRenderBlocking
  • $wgDefaultMobileSkin
  • $wgMFUseDesktopSpecialEditWatchlistPage
  • $wgMFEnableFontChanger
  • $wgMFScriptPath
  • $wgMFEditNoticesConflictingGadgetName
  • $wgMFAdvancedMobileContributions
  • $wgMFFallbackEditor
  • $wgMFStopMobileRedirectCookieSecureValue
  • $wgMFSpecialPageTaglines
  • $wgMFQueryPropModules
  • $wgMFNamespacesWithoutCollapsibleSections
  • $wgMFBetaFeedbackLink
  • $wgMFDefaultEditor
  • $wgMFAmcOutreach
  • $wgMFManifestBackgroundColor
  • $wgMFManifestThemeColor
  • $wgMFEnableManifest
  • $wgMFEnableWikidataDescriptions
  • $wgMFUseWikibase
  • $wgMFTrackBlockNotices
  • $wgMFEnableBeta
  • $wgMobileUrlCallback
Переведите расширение MobileFrontend, если оно доступно на translatewiki.net
Проблемы Открытые задачи · Сообщить об ошибке
Category:All extensions/ru

Расширение MobileFrontend помогает улучшить мобильное присутствие экземпляра MediaWiki.

В число возможностей входят:

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

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

Необходимые компоненты

Если вы активно используете шаблоны и/или встроенные стили (атрибут style), перед установкой MobileFrontend вам следует просмотреть свой контент на предмет его оптимизации под мобильные устройства. Расширение TemplateStyles можно использовать для стилизации контента, чтобы он хорошо отображался на мобильных и настольных компьютерах. MobileFrontend не исправит это за вас волшебным образом!

В частности, вы можете пересмотреть вашу домашнюю страницу (главную страницу). См. Форматирование главной страницы для мобильных устройств.

Установка

  • Скачайте и распакуйте файл(ы) в папку с названием MobileFrontend в вашей папке extensions/.
    Вместо этого разработчикам и соавторам кода следует установить расширение из Git, используя:
    cd extensions/
    git clone https://gerrit.wikimedia.org/r/mediawiki/extensions/MobileFrontend
    
  • Добавьте следующий код в конце вашего файла LocalSettings.php :
    wfLoadExtension( 'MobileFrontend' );
    
  • Настройте на свой манер при необходимости
  • Yes Готово – Перейдите на страницу Special:Version на своей вики, чтобы удостовериться в том, что расширение успешно установлено.


Установка Vagrant:

  • Если вы используете Vagrant , установите с помощью vagrant roles enable mobilefrontend --provision

Установка раздела «Поблизости»

The Nearby feature in MobileFrontend has been removed in MediaWiki 1.40. Instead, a rewritten version of this feature is available at Extension:NearbyPages .

MobileFronted предоставляет страницу Служебная:Nearby с возможностью донастройки. Требуется выполнить несколько необязательных шагов, чтобы эта служебная страница заработала у вас.

  1. Из-за системы безопасности браузеров вам будет нужно запустить безопасный сайт через SSL — через HTTP невозможно запросить геолокацию пользователя.
  2. Установите расширение GeoData
  3. Запустите update.php
  4. В LocalSettings.php добавьте $nearby
  5. Определите координаты статьи:
    1. Добавляйте геопозиционные данные в ваши статьи через функцию парсера coordinates; например, {{#coordinates:37.786971|-122.399677|primary}}. For syntax details, see the documentation for GeoData.
    2. Alternatively, you can use a separate MediaWiki installation for Nearby by setting $wgMFNearbyEndpoint in your LocalSettings.php file. Например, $wgMFNearbyEndpoint = 'https://en.m.wikipedia.org/w/api.php'; будет использовать координаты из статей Википедии на английском языке. The nearby endpoint will be used to find content related to a given location.

Установка темы оформления

MobileFrontend provides you with a mobile formatted website to go alongside your existing desktop website. You can skin it however you want.

// Choose one of these pairs of lines and add chosen code to bottom of LocalSettings.php file:
wfLoadSkin( 'MinervaNeue' );
$wgDefaultMobileSkin = 'minerva'; // use Minerva skin (You need to download and install it separately in 1.37 and older, otherwise you'll get an exception)
wfLoadSkin( 'Vector' );
$wgDefaultMobileSkin = 'vector'; // use Vector skin
wfLoadSkin( 'Timeless' );
$wgDefaultMobileSkin = 'timeless'; // use Timeless skin

The following skins are compatible with MobileFrontend:

  • Skin:Vector (default desktop skin, uses an experimental responsive mode for mobile)

Настройки конфигурации

Смотрите Extension:MobileFrontend/Configuration

All configuration options are detailed in the README.md file.

Дополнительные настройки

Get the most out of MobileFrontend by adding these optional compatible extensions:

Локальная подстройка

Оформление через CSS

Версия MediaWiki:
1.40

To apply CSS to your mobile theme, edit MediaWiki:Mobile.css, the counterpart of MediaWiki:Common.css. In order for the stylesheet to function you may have to add mw.loader.using('mobile.site.styles') to your MediaWiki:Mobile.js.

MobileFrontend does not load the global MediaWiki:Common.css, neither does it load any of the user stylesheets.

Больше информации

If you would like to test the mobile extension on a desktop browser or your device doesn't render the mobile version, you can append the following key-value pair to the URL query string: ?useformat=mobile. For example: https://en.wikipedia.org/wiki/MediaWiki?useformat=mobile

If you would like to view the mobile version of a page without enabling the extension across the entire site you can append the string to the URL on that page, too.

Legacy features of MobileFrontend

MobileFrontend has traditionally been a very large extension. Many features have either surpassed their requirements or will do at some future date. These are listed below.

API

APIs are provided by the MobileFrontend extension, but long term we expect to deprecate them in favour of Page Content Service. Use these APIs at your own risk. They may disappear (although we will give you sufficient notice when they do)!

Extended action=parse

action=parse accepts extra parameters:

mobileformat=
Return rendered page HTML in a mobile format 1.23+.
mainpage
Apply mobile main page transformations.

Пример:

Результат
{
    "parse": {
        "title": "Therion (band)",
	    "text": {
            "*": "<div><table class=\"infobox vcard plainlist\" style=\"width:22em\"><tr><th colspan=\"2\" style=\"text-align:center;font-size:125%;font-weight:bold;background-color: #b0c4de\"><span class=\"fn org\">Therion</span></th>\n</tr><tr><td colspan=\"2\" style=\"text-align:center\"><a href=\"/wiki/File:2130860153_281d30b3bf_b.jpg\" class=\"image\">
            ...

meta=siteinfo

The domain of the mobile version of the site (which might or might not be the same as the normal domain) is available under the mobileserver key of the general siteinfo information.

Для разработчиков/администраторов

Установка

You may need to run npm install and install php composer to get the precommit hook to run, depending on what you're doing with the extension.

Тестирование со статьями во внешней вики (живые данные)

См. Extension:MobileFrontendContentProvider.

Использование мобильного режима просмотра

WMF sites

On Wikimedia Foundation-run sites, we use Varnish caching servers to check the user agent of your device.

Non-WMF sites

For non-WMF sites, you can either set up your configuration to mimic how things are done at the WMF (doing device detection at the proxy layer and setting specific X-Device headers), or you can simply use "?useformat=mobile" to switch an article to use the mobile view. See Extension:MobileFrontend/Configuring browser auto-detection.

Starting from the snapshot version 1.28, the default $wgMFMobileHeader was changed from X-WAP to X-Subdomain. You could either set $wgMFMobileHeader = 'X-WAP'; or modify your cache (Varnish) header setting, as long as they match.

Using Apache (.htaccess or httpd.conf)

To set up a mobile domain, add the following rule to .htaccess or httpd.conf

<IfModule mod_headers.c>
<If "req('Host') =~ /^mobile./i">
RequestHeader set X-Subdomain "mobile"
</If>
</IfModule>

In your hosts file (assuming your desktop site is on localhost):

127.0.0.1  mobile.localhost

In LocalSettings.php:

wfLoadExtension('MobileFrontend');

$wgMFAutodetectMobileView = true;
$wgMobileUrlCallback = fn( $domain ) => "mobile.$domain";

Now if you navigate to mobile.localhost you should see the mobile site.

ЧаВО

На нашей странице обсуждения часто появляются следующие вопросы. Please check this list before posting about them on the talk page or use the existing talk topic, if available, to receive clarifications.

Q: How do I detect the mobile site in frontend code?

A: Ideally you shouldn't need to do this. It is preferable to use mw.config.get('skin') or window.matchMedia('(max-width: 1119px)').matches to detect a mobile user. You can also make use of the stable mw-mf class which is present on the BODY element if the mobile site is active.

If your code makes modifications to content, you may need to update your code to consider MobileFrontend markup by inspecting the DOM for presence of certain elements.

Please note while mw.config.get( 'wgMFMode' ) exists and can be used by extensions as a last resort (for now) it should not be considered stable for use by gadgets.

Q: How do I customise the main menu of the Minerva skin?

Q: How do I add HTML to the Minerva skin, for example to add ads or additional script tags?

A: You can do this by editing the template file for the skin (currently include/skins/minerva.mustache). See this discussion for details.

Q: The extension I am using doesn't seem to work on MobileFrontend. Why?

A: It's likely the extension is old and needs to add compatibility to MobileFrontend. Please contact the developer of the extension and point them to ResourceLoader/Writing a MobileFrontend friendly ResourceLoader module. Please do not post to the talk page, as in this case it would be better to file a bug on Phabricator (you can login using your MediaWiki.org username) for a quicker response.

Q: I upgraded MobileFrontend and now I'm getting a fatal exception!

A: You are probably using incompatible versions of MobileFrontend and MediaWiki. In most cases, we can't help you here. Try upgrading MobileFrontend or MediaWiki to resolve your issue.

Q: After upgrading MediaWiki I'm getting an exception wgMFDefaultSkinClass is not setup correctly.

A: MobileFrontend currently assumes you have the MinervaNeue skin installed. If you don't you'll need to install this or configure your mobile skin per instructions above.

Для разработчиков расширений

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

Should a module need to be loaded while in mobile view this guide on writing MobileFrontend friendly modules will be of help.

Смотрите также

Примечания

  1. Fatal error: Uncaught ExtensionDependencyError: MobileFrontend is not compatible with the current MediaWiki core (version 1.32.2), it requires: >= 1.33.0.
Category:Extensions used on Wikimedia/ru#MobileFrontend/ru Category:MobileFrontend/ru#%20
Category:APIGetAllowedParams extensions/ru Category:APIQuerySiteInfoGeneralInfo extensions/ru Category:AbuseFilter-builder extensions/ru Category:AbuseFilter-generateUserVars extensions/ru Category:AfterBuildFeedLinks extensions/ru Category:All extensions/ru Category:ApiBeforeMain extensions/ru Category:ArticleParserOptions extensions/ru Category:AuthChangeFormFields extensions/ru Category:BeforeDisplayNoArticleText extensions/ru Category:BeforePageDisplay extensions/ru Category:BeforePageRedirect extensions/ru Category:CentralAuthLoginRedirectData extensions/ru Category:CentralAuthSilentLoginRedirect extensions/ru Category:ChangeTagsListActive extensions/ru Category:CustomEditor extensions/ru Category:Extensions in Wikimedia version control/ru Category:Extensions included in Canasta/ru Category:Extensions included in Fandom/ru Category:Extensions included in Miraheze/ru Category:Extensions included in MyWikis/ru Category:Extensions included in ShoutWiki/ru Category:Extensions included in Telepedia/ru Category:Extensions included in WikiForge/ru Category:Extensions used on Wikimedia/ru Category:Extensions with manual MediaWiki version/ru Category:GPL licensed extensions/ru Category:GetCacheVaryCookies extensions/ru Category:GetPreferences extensions/ru Category:HTMLFileCache::useFileCache extensions/ru Category:Hook extensions/ru Category:ListDefinedTags extensions/ru Category:LoginFormValidErrorMessages extensions/ru Category:MakeGlobalVariablesScript extensions/ru Category:ManualLogEntryBeforePublish extensions/ru Category:MediaWikiPerformAction extensions/ru Category:MobileFrontend/ru Category:OutputPageBeforeHTML extensions/ru Category:OutputPageBodyAttributes extensions/ru Category:OutputPageParserOutput extensions/ru Category:PostLoginRedirect extensions/ru Category:RecentChange save extensions/ru Category:RequestContextCreateSkin extensions/ru Category:ResourceLoaderSiteModulePages extensions/ru Category:ResourceLoaderSiteStylesModulePages extensions/ru Category:SkinAddFooterLinks extensions/ru Category:SkinAfterBottomScripts extensions/ru Category:SpecialPageBeforeExecute extensions/ru Category:SpecialPage initList extensions/ru Category:Stable extensions/ru Category:TitleSquidURLs extensions/ru Category:UserGetDefaultOptions extensions/ru Category:User interface extensions/ru