Коммит adde8d69 создал по автору OMP Education's avatar OMP Education
Просмотр файлов

[Project] Implement the WebViewAPI application.

владелец 548e4e89
# Use target-compatible line endings as the safe default for cross compilation.
* text=auto eol=lf
......@@ -2,4 +2,18 @@
* Kirill Chuvilin, <k.chuvilin@omp.ru>
* Product owner, 2024
* Konstantin Zvyagin, <k.zvyagin@omp.ru>
* Maintainer, 2024
* Reviewer, 2024
* Rinat Dobrokhotov, <r.dobrokhotov@omp.ru>
* Developer, 2024
* Nikolay Kavetskiy, <n.kavetskiy@omp.ru>
* Developer, 2024
* Alexey Tolchinskiy, <a.tolchinskiy@omp.ru>
* Developer, 2024
* Vsevolod Mikulik, <v.mikulik@omp.ru>
* Developer, 2024
* Dmitriy Klimov
* Developer, 2024
* Alexander Lukyanov
* Developer, 2024
......@@ -79,5 +79,5 @@ please contact <community@omp.ru>.
This work is licensed under a Creative Commons Attribution 3.0 Unported License
For attribution requirements:
«Open Mobile Platform Code of Conduct»
Copyright (c) 2021 Open Mobile Platform LLC,
Copyright (c) 2024 Open Mobile Platform LLC,
used under a [Creative Commons Attribution Unported license](http://creativecommons.org/licenses/by/3.0/).
# Chromium WebView
# WebView API
Chromium WebView is a project that provides examples of Aurora Chromium
WebView APIs usage.
## This document in Russian / Перевод этого документа на русский язык
- [README.ru.md](README.ru.md)
## Contents
- [Application description](#Application-description)
- [Build and use features](#Build-and-use-features)
- [Installation and build](#Installation-and-build)
- [Screenshots](#Screenshots)
- [Use cases](#Use-cases)
- [Known errors](#Known-errors)
- [Compatibility](#Compatibility)
- [Project Structure](#Project-structure)
- [Terms of Use and Participation](#Terms-of-Use-and-Participation)
<a name="Application-description"></a>
## Application description
The application is an example of using the WebView API. It shows how to run
JavaScript script, filter URL addresses, send and receive async messages from
the web, use SSL-providers, use JavaScript dialogs, use private WebView mode.
<a name="Build-and-use-features"></a>
## Build and use features
The project is built using the
[ru.auroraos.WebViewAPI.pro](ru.auroraos.WebViewAPI.pro) file.
<a name="Installation-and-build"></a>
## Installation and build
The project is built in the usual way using the Aurora SDK.
<a name="Screenshots"></a>
## Screenshots
![Screenshots](screenshots/screenshots.png)
<a name="Use-cases"></a>
## Use cases
### Running the JavaScript script
* To demonstrate the JavaScript script execution, select the "JS script
execution" option on the main screen.
* A page will be opened showing the status of the job.
### URL filtering
* To demonstrate URL filtering, select "URL filtering" on the main screen.
* You can select the desired page and click on the appropriate button, and the
page will be displayed at the bottom of the screen.
### Async messages usage
* To demonstrate the async messages usage, select "Async messages" on the main
screen.
* On the opened page you can send messages by clicking on the appropriate
buttons. At the same time, the received messages will be counted.
### Using the SSL provider
* To demonstrate the SSL provider usage, select "SSL Provider" on the main
screen.
* On the opened page you can select the type of SSL provider: Embedded or
CryptoPro.
### Using JavaScript dialogs
* To demonstrate the JavaScript dialogs usage, select the "JS dialogs" item on
the main screen.
* On the opened page select the type of dialog, click on the button "OK" and
get information about the corresponding event at the bottom of the screen.
### Using the private mode
* To demonstrate the private mode usage, select "Private Mode" on the main
screen.
* One of the opened page WebViews will show a private window, and the second
one will show a not private one.
### Uploading a file to an HTML form
* To demonstrate uploading a file to an HTML form, select
the "Upload file to HTML form" on the main screen.
* On the opened page you can open a file selection dialog and upload an image
to the HTML form.
### Downloading a file
* To demonstrate downloading a file, select the "Download file" on the main
screen.
* On the opened page you can download a file and use the dialog to select
the directory where the file will be saved.
<a name="Known-errors"></a>
## Known errors
No known errors have been found in the project.
<a name="Compatibility"></a>
## Compatibility
The application is working correctly since 5.1.3 version of Aurora OS.
<a name="Project-structure"></a>
## Project structure
The project has a standard structure of an application based on C++ and QML
for Aurora OS.
* [ru.auroraos.WebViewAPI.pro](ru.auroraos.WebViewAPI.pro) file
describes the project structure for the qmake build system.
* [html](html) directory contains accessory html pages.
* [icons](icons) directory contains the application icons for different screen
resoulions.
* [qml](qml) directory contains the QML source code and the UI resources.
* [cover](qml/cover) directory contains the application cover implementations.
* [pages](qml/pages) directory contains the application pages.
* [WebViewAPI.qml](qml/WebViewAPI.qml) file
provides the application window implementation.
* [rpm](rpm) directory contains the rpm-package build settings.
* [ru.auroraos.WebViewAPI.spec](rpm/ru.auroraos.WebViewAPI.spec)
file is used by rpmbuild tool.
* [src](src) directory contains the C++ source code.
* [main.cpp](src/main.cpp) file is the application entry point.
* [translations](translations) directory contains the UI translation files.
* [ru.auroraos.WebViewAPI.desktop](ru.auroraos.WebViewAPI.desktop)
file defines the display and parameters for launching the application.
<a name="Terms-of-Use-and-Participation"></a>
## Terms of Use and Participation
The source code of the project is provided under
[the license](LICENSE.BSD-3-Clause.md), which allows its use in third-party
applications.
The [contributor agreement](CONTRIBUTING.md) documents the rights granted by
contributors of the Open Mobile Platform.
Information about the contributors is specified in the [AUTHORS](AUTHORS.md)
file.
[Code of conduct](CODE_OF_CONDUCT.md) is a current set of rules of the
Open Mobile Platform which informs you how we expect the members of the
community will interact while contributing and communicating.
# WebView API
## Этот документ на английском языке / This document in English
- [README.md](README.md)
## Оглавление
- [Описание приложения](#Описание-приложения)
- [Особенности использования и сборки](#Особенности-использования-и-сборки)
- [Установка и сборка](#Установка-и-сборка)
- [Скриншоты](#Скриншоты)
- [Варианты использования](#Варианты-использования)
- [Известные ошибки](#Известные-ошибки)
- [Совместимость](#Совместимость)
- [Структура проекта](#Структура-проекта)
- [Правила использования и участие в разработке](#Правила-использования-и-участие-в-разработке)
<a name="Описание-приложения"></a>
## Описание приложения
Приложение является примером использования WebView API. Приложение показывает,
как выполнять скрипт JavaScript, осуществлять фильтрацию URL адресов,
отправлять и получать асинхронные сообщения из сети, использовать
SSL-провайдер, использовать JavaScript диалоги, использовать приватный режим
WebView.
<a name="Особенности-использования-и-сборки"></a>
## Особенности использования и сборки
Сборка проекта осуществляется через файл
[ru.auroraos.WebViewAPI.pro](ru.auroraos.WebViewAPI.pro).
<a name="Установка-и-сборка"></a>
## Установка и сборка
Проект собирается обычным образом с помощью Аврора SDK.
<a name="Скриншоты"></a>
## Скриншоты
![Скриншоты](screenshots/screenshots.png)
<a name="Варианты-использования"></a>
## Варианты использования
### Выполнение скрипта JavaScript
* Для демонстрации выполнения скрипта JavaScript на главном экране необходимо
выбрать пункт «Выполнение скрипта JS».
* Откроется страница, на которой будет показан статус работы.
### Фильтрация URL адресов
* Для демонстрации фильтрации URL адресов на главном экране необходимо выбрать
пункт «Фильтрация URL».
* Можно выбрать желаемую страницу и нажать на соответствующую кнопку, после
чего страница отобразится в нижней части экрана.
### Использование асинхронных сообщений
* Для демонстрации использования асинхронных сообщений на главном экране
необходимо выбрать пункт «Асинхронные сообщения».
* Откроется страница, на которой можно отправлять сообщения нажатием на
соответсвующие кнопки. При этом будет вестись подсчет полученных сообщений.
### Использование SSL-провайдера
* Для демонстрации использования SSL-провайдера на главном экране необходимо
выбрать пункт «SSL-провайдер».
* Откроется страница, на которой можно выбрать тип SSL-провайдера: Встроенный
или CryptoPro.
### Использование JavaScript диалогов
* Для демонстрации использования JavaScript диалогов на главном экране
необходимо выбрать пункт «Диалоги JS».
* Откроется страница, на которой можно выбрать тип диалога, нажать на кнопку
«Ок» и получить информацию о соответствующем событии внизу экрана.
### Использование приватного режима
* Для демонстрации использования приватного режима на главном экране
необходимо выбрать пункт «Приватный режим».
* Откроется страница, на которой один из WebView будет показывать приватное
окно, а второй - не приватное.
### Загрузка файла в html-форму
* Для демонстрации загрузки файла в html-форму на главном экране необходимо
выбрать пункт «Загрузить файл в html-форму».
* Откроется страница, на которой можно открыть диалог выбора файла и
загрузить изображение в html-форму.
### Скачивание файла
* Для демонстрации скачивания файла на главном экране необходимо выбрать
пункт «Скачать файл».
* Откроется страница, на которой можно скачать файл и с помощью диалога
выбрать директорию, куда файл будет сохранён.
<a name="Известные-ошибки"></a>
## Известные ошибки
В проекте не обнаружены известные ошибки.
<a name="Совместимость"></a>
## Совместимость
Приложение корректно работает начиная с 5.1.3 версии ОС Авроры.
<a name="Структура-проекта"></a>
## Структура проекта
Проект имеет стандартную структуру приложения на базе C++ и QML для ОС Аврора.
* Файл [ru.auroraos.WebViewAPI.pro](ru.auroraos.WebViewAPI.pro)
описывает структуру проекта системы сборки qmake.
* Каталог [html](html) содержит вспомогательные html страницы.
* Каталог [icons](icons) содержит значки приложений для разных разрешений
экрана.
* Каталог [qml](qml) содержит исходный код QML и ресурсы пользовательского
интерфейса.
* Каталог [cover](qml/cover) содержит реализации обложек приложений.
* Каталог [pages](qml/pages) содержит страницы приложения.
* файл [WebViewAPI.qml](qml/WebViewAPI.qml) обеспечивает реализацию
окна приложения.
* Каталог [rpm](rpm) содержит настройки сборки rpm-пакета.
* [ru.auroraos.WebViewAPI.spec](rpm/ru.auroraos.WebViewAPI.spec)
используется инструментом rpmbuild.
* Каталог [src](src) содержит исходный код C++.
* [main.cpp](src/main.cpp) файл является точкой входа в приложение.
* Каталог [translations](translations) содержит файлы перевода
пользовательского интерфейса.
* Файл [ru.auroraos.WebViewAPI.desktop](ru.auroraos.WebViewAPI.desktop)
определяет отображение и параметры для запуска приложения.
<a name="Правила-использования-и-участие-в-разработке"></a>
## Правила использования и участие в разработке
Исходный код проекта предоставляется по [лицензии](LICENSE.BSD-3-Clause.md),
которая позволяет использовать его в сторонних приложениях.
[Соглашение участника](CONTRIBUTING.md) регламентирует права, предоставляемые
участниками компании «Открытая Мобильная Платформа».
Информация об участниках указана в файле [AUTHORS](AUTHORS.md).
[Кодекс поведения](CODE_OF_CONDUCT.md) — это действующий набор правил компании
«Открытая Мобильная Платформа», который информирует об ожиданиях по
взаимодействию между членами сообщества при общении и работе над проектами.
<!--SPDX-FileCopyrightText: 2024 Open Mobile Platform LLC <community@omp.ru>
SPDX-License-Identifier: BSD-3-Clause-->
<html>
<head>
<title>Async messages</title>
<style type="text/css">
.box {
height: 100px;
border:1px solid black;
}
</style>
<script>
function receiveMessage(counter) {
const elem = document.getElementById("nativeCounter");
elem.innerText = "Received from native: " + counter;
}
let counter = 0;
window.addEventListener('load', function() {
const elem = document.getElementById("webCounter");
elem.addEventListener('click', function () {
sendAsyncMessage("appMessageHandler2", counter);
counter++;
});
})
</script>
</head>
<body bgcolor="white">
<button id="webCounter" class="box">
Click me to send async message
</button>
<p></p>
<div id="nativeCounter">
Received from native: -
</div>
</body></html>
<!--SPDX-FileCopyrightText: 2024 Open Mobile Platform LLC <community@omp.ru>
SPDX-License-Identifier: BSD-3-Clause-->
<html>
<body>
<h1>The download attribute</h1>
<p>Press and hold the image to open context menu, then click the "save image" button to download it:<p>
<a href="https://img.goodfon.ru/original/2048x1365/4/49/gory-zima-yanvar-severnye.jpg"
download
target="_blank">
<img src="https://img.goodfon.ru/original/2048x1365/4/49/gory-zima-yanvar-severnye.jpg" width="95%">
</a>
<p>Click link to download file:<p>
<p><a href="https://developer.auroraos.ru/static/regular_key.pem" download>
Download link
</a></p>
<p><b>Note:</b> The download attribute is not supported in IE or Edge (prior version 18), or in Safari (prior version 10.1).</p>
</body>
</html>
<!--SPDX-FileCopyrightText: 2024 Open Mobile Platform LLC <community@omp.ru>
SPDX-License-Identifier: BSD-3-Clause-->
<html><head>
<meta http-equiv="content-type" content="text/html; charset=windows-1251">
<title>Test Web Prompts</title>
<script>
function dispPrompt() {
var inputtxt=prompt("Please enter something", "a word or two")
document.getElementById("msg").innerHTML=inputtxt
}
function dispShortAlert() {
alert("Lorem ipsum.")
document.getElementById("msg").innerHTML="Short Alert pressed"
}
function dispMediumAlert() {
alert("Lorem ipsum dolor sit amet.")
document.getElementById("msg").innerHTML="Medium Alert pressed"
}
function dispLongAlert() {
alert("Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor" +
"incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis " +
"nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. " +
"Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu " +
"fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in " +
"culpa qui officia deserunt mollit anim id est laborum." +
"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor" +
"incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis " +
"nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. " +
"Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu " +
"fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in " +
"culpa qui officia deserunt mollit anim id est laborum." +
"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor" +
"incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis " +
"nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. " +
"Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu " +
"fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in " +
"culpa qui officia deserunt mollit anim id est laborum." +
"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor" +
"incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis " +
"nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. " +
"Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu " +
"fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in " +
"culpa qui officia deserunt mollit anim id est laborum.")
document.getElementById("msg").innerHTML="Long Alert pressed"
}
function multiplePopups() {
alert("Alert 1/9")
alert("Alert 2/9")
alert("Alert 3/9")
confirm("Confirm 4/9")
confirm("Confirm 5/9")
confirm("Confirm 6/9")
prompt("Prompt 7/9")
prompt("Prompt 8/9")
prompt("Prompt 9/9")
}
function dispShortConfirm() {
var inputtxt = confirm("Ok or cancel?") ? "ok" : "cancel"
document.getElementById("msg").innerHTML=inputtxt
}
function dispMediumConfirm() {
var inputtxt = confirm("Lorem ipsum ok or cancel?") ? "ok" : "cancel"
document.getElementById("msg").innerHTML=inputtxt
}
function dispLongConfirm() {
var inputtxt = confirm("Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor" +
"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor" +
"incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis " +
"nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. " +
"Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu " +
"fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in " +
"culpa qui officia deserunt mollit anim id est laborum." +
"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor" +
"incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis " +
"nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. " +
"Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu " +
"fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in " +
"culpa qui officia deserunt mollit anim id est laborum." +
"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor" +
"incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis " +
"nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. " +
"Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu " +
"fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in " +
"culpa qui officia deserunt mollit anim id est laborum." +
"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor" +
"incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis " +
"nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. " +
"Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu " +
"fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in " +
"culpa qui officia deserunt mollit anim id est laborum. Ok or cancel?") ? "ok" : "cancel"
document.getElementById("msg").innerHTML=inputtxt
}
function handleEnter(event, element)
{
var code = (event.keyCode ? event.keyCode : event.which);
if(code == 13) { //Enter keycode
switch (element.id) {
case "promptTriggerer":
dispPrompt()
break
}
}
}
window.onbeforeunload = function() {
return "";
}
</script>
<style>
button {
font-size: 40pt
}
div, a {
font-size: 40pt;
}
p {
font-size: 40pt;
}
input {
width:100%;
height:80px;
font-size: 60px;
}
.styledLink {
color: blue;
font-style: italic;
text-decoration: none;
}
</style>
</head>
<body>
<button onclick="dispShortAlert()">Short Alert</button> <br><br>
<button onclick="dispMediumAlert()">Medium Alert</button> <br><br>
<button onclick="dispLongAlert()">Long Alert</button> <br><br>
<button onclick="multiplePopups()">Multiple popups</button> <br><br>
<button onclick="dispShortConfirm()">Short Confirm</button> <br><br>
<button onclick="dispMediumConfirm()">Medium Confirm</button> <br><br>
<button onclick="dispLongConfirm()">Long Confirm</button> <br><br>
<button onclick="dispPrompt()">Prompt</button>
<div id="msg">The result will be shown here</div>
<p><a href="http://www.omp.ru/">Leave page</a> </p>
</body></html>
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<title>Пример использования target="_blank"</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
padding-top: 50px;
font-size: 20px;
}
.button {
display: inline-block;
margin-top: 30px;
margin-bottom: 30px;
padding: 20px 40px;
font-size: 32px;
color: white;
background-color: #007BFF;
border: none;
border-radius: 5px;
text-decoration: none;
cursor: pointer;
}
.button:hover {
background-color: #0056b3;
}
</style>
</head>
<body>
<div>
<p><strong>Пример открытия ссылки с <code>target="_blank"</code>.</strong><br>
Для того чтобы открыть новую страницу, нажмите кнопку <strong>"Открыть страницу"</strong>.</p>
</div>
<a href="https://example.com" target="_blank" class="button">Открыть страницу</a>
<div class="back-text">
Для возвращения на предыдущую страницу — смахните вправо
</div>
</body>
</html>
<!--SPDX-FileCopyrightText: 2024 Open Mobile Platform LLC <community@omp.ru>
SPDX-License-Identifier: BSD-3-Clause-->
<html>
<head>
<title>Run JS</title>
<script>
let counter = 0;
function counterPlus1() {
const elem = document.getElementById("counter");
elem.innerText = counter;
counter++;
}
</script>
</head>
<body bgcolor="white">
<div id="counter"></div>
</body></html>
<!--SPDX-FileCopyrightText: 2024 Open Mobile Platform LLC <community@omp.ru>
SPDX-License-Identifier: BSD-3-Clause-->
<html>
<head>
<title>Run JS</title>
<style type="text/css">
.box {
width: 30px;
height: 30px;
}
.green {
width: 30px;
height: 30px;
}
</style>
<script>
function documentAvailable() {
const elem = document.getElementById("available");
elem.innerText = "AVAILABLE";
}
function startedToLoad() {
const elem = document.getElementById("started");
elem.innerText = "STARTED";
}
function finishedToLoad() {
const elem = document.getElementById("finished");
elem.innerText = "FINISHED";
}
</script>
</head>
<body bgcolor="white">
<div id="available" class="box">
</div>
<div id="started" class="box">
</div>
<div id="finished" class="box">
</div>
</body></html>
// SPDX-FileCopyrightText: 2024 Open Mobile Platform LLC <community@omp.ru>
// SPDX-License-Identifier: BSD-3-Clause
finishedToLoad();
<!--SPDX-FileCopyrightText: 2024 Open Mobile Platform LLC <community@omp.ru>
SPDX-License-Identifier: BSD-3-Clause-->
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Test page 1</title>
</head>
<body>
<font size="14">
<p><b>Test page 1</b></p>
</font>
</body>
</html>
<!--SPDX-FileCopyrightText: 2024 Open Mobile Platform LLC <community@omp.ru>
SPDX-License-Identifier: BSD-3-Clause-->
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Test page 2</title>
</head>
<body>
<font size="14">
<p><b>Test page 2</b></p>
</font>
<font color="red" size="10">
<p>This page should be filtered and should not be loaded during the test</p>
</font>
</body>
</html>
<!--SPDX-FileCopyrightText: 2024 Open Mobile Platform LLC <community@omp.ru>
SPDX-License-Identifier: BSD-3-Clause-->
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Test page 3</title>
</head>
<body>
<font size="14">
<p><b>Test page 3</b></p>
</font>
<h3>Phone URI</h3>
<a href="tel:+7-999-999-9999">+7-999-999-9999</a>
<p>This must run a system intent when nativeSchemeHandling is true; It must not run a system intent when nativeSchemeHandling is off OR when overrideTelUri is on</p>
<h3>Email URI</h3>
<a href="mailto:email@email.com">email@email.com</a>
<p>This must run a system intent when nativeSchemeHandling is true</p>
</body>
</html>
<!--SPDX-FileCopyrightText: 2024 Open Mobile Platform LLC <community@omp.ru>
SPDX-License-Identifier: BSD-3-Clause-->
<html>
<head>
<meta charset="utf-8">
<title>input element</title>
</head>
<body>
<h1>Upload file</h1>
<form>
<input type="file" id="fileInput">
</form>
<p>Click the "Show Image" button and the selected image will be displayed below</p>
<image id="selectedImage"/>
</body>
<script>
document.getElementById('fileInput').onchange = function () {
document.getElementById('fileInput').innerHTML = 'Selected file: ' + this.value;
};
function setSelectedImage(fileUrl) {
if(fileUrl !== "") {
document.getElementById("selectedImage").src = fileUrl;
document.getElementById("selectedImage").style.width = '95%';
}
}
function clearSelectedFile() {
document.getElementById("selectedImage").src = "";
document.getElementById("selectedImage").style.width = '0%';
document.getElementById('fileInput').value = "";
}
</script>
</html>
Поддерживает Markdown
0% или .
You are about to add 0 people to the discussion. Proceed with caution.
Сначала завершите редактирование этого сообщения!
Пожалуйста, зарегистрируйтесь или чтобы прокомментировать