Window open html file

window.open()

open() — метод объекта window позволяет открыть ссылки в новом или всплывающем окне или новой вкладке.

Синтаксис

 window.open(url, target, windowFeatures) 

url необязательный — относительный или полный путь до страницы в формате строки — заключается в одинарные или двойные кавычки. Если оставить строку пустой » или пропустить параметр, откроется пустая страница.

target необязательный — можно указать имя нового окна — window.name , если метод найдет окно с таким же именем, тогда URL откроется в нем, если нет, то откроется новое. Также параметр может принимать те же значения, что и атрибут target тега , с отличием, что по умолчанию идет _blank :

  • _blank — страница будет загружена в новом окне браузера;
  • _self — страница загрузиться в том же самом окне;
  • _parent — загрузиться в родительской странице текущего элемента. Например если действие происходит во фрейме, ссылка откроется на странице куда он вставлен. Если родительской нет, то работает, как _self .
  • _top — страница откроется в окне высшего уровня, какая бы вложенность элементов не была. Если родителя нет, то ведёт себя как _self .
Читайте также:  Find by class selenium java

windowFeatures необязательный — здесь можно детально описать, как будет выглядеть новое окно и где располагаться. Параметры записываются через запятую в формате name=value , для булевых можно просто name . Доступные параметры:

  • width или innerWidth — ширина содержимого, в том числе полоса прокрутки, минимум 100px;
  • height или innerHeight — высота содержимого, в том числе полоса прокрутки, минимум 100px;
  • left или screenX — расстояние в пикселях от левой части рабочей области пользователя;
  • top или screenY — расстояние в пикселях от верхней части рабочей области пользователя.
  • popup — при true ссылка откроется в новом окне.
  • noopener — параметр предотвращает доступ новому окну к исходной странице и возвращает null . Все значения второго параметра метода open() , кроме _top , _self и _parent обрабатываются, как _blank .
  • noreferrer — блокирует передачу информации о исходной странице и устанавливает noopener=true .

Открыть страницу в новой вкладке

 open('https://learnjs.ru/journal/knigi-javascript/', 'BooksJS') 

Большинство браузеров блокируют всплывающие окна, которые были вызваны не в результате действий пользователя.

  

В данном случае ссылка откроется при клике на кнопку без проблем.

Pop-up с заданными размерами

 window.open('https://learnjs.ru/', 'LearnJS', 'width=500,height=500,left=650,top=200') 

Для удобства третий параметр можно записать в переменную и при вызове метода open() , использовать уже его.

 let paramsPopUp = `width=500,height=500,left=650,top=200` window.open('https://learnjs.ru/', 'LearnJS', paramsPopUp) 

Взаимодействие с новым окном

open() возвращает ссылку на новое окно, тем самым позволяя манипулировать им с помощью вызова определенных методов и получения значений свойств.

 let newWindow = window.open('', 'createWindow', 'popup') newWindow.document.write('

Практикуйтесь в написании кода каждый день

')

Здесь мы записали ссылку в переменную newWindow , а затем с помощью write() вывели в новом окне наш текст.

Получить доступ к странице из нового окна

Получить ссылку из нового окна на родителя можно с помощью свойства opener

 let myWindow = window.open('','newPopUp','width=200,height=200,left=400,top=200') myWindow.document.write('

Закрыть окно с помощью close()

 let newWindow = window.open('https://learnjs.ru', 'LearnJS', 'width=500,height=500') setTimeout(() => newWindow.close(), 3000) 

Код откроет всплывающее окно, а через 3 секунды его закроет.

Проверить закрыто ли окно — свойство closed

 let newWindow = window.open('', 'newPopUp', 'width=500,height=500') newWindow.document.write('

Закрой меня

') let timerId = setInterval(() => < if(newWindow.closed) < alert('Pop-up закрыт') clearInterval(timerId) >>, 1000)

Свойство closed содержит значение true — окно закрыто или false — окно открыто. В нашем примере мы сначала открываем pop-up и далее запускаем проверку — закрыто ли окно. Когда пользователь его закроет, тогда сработает alert(‘Pop-up закрыт’) .

Передать фокус — focus()

Для выполнения задачи есть метод focus()

  

Здесь мы передали фокус на поле ввода.

Убрать фокус - blur()

Для того, чтобы убрать фокус есть метод blur()

  

Здесь мы наоборот каждый 0,1 секунду убираем фокус с поля ввода в новом окне. Придется постараться, чтобы туда что-то напечатать.

Изменить размеры или переместить окно

newWindow.moveBy(x,y) - переместить окно в пикселях, x - вправо, y - вниз. Возможны отрицательные значения.

newWindow.moveTo(x,y) - переместить в заданную координату.

newWindow.resizeBy(width,height) - изменить размер окна на указанную величину. Возможны отрицательные значения.

newWindow.resizeTo(width,height) - изменить размер окна на заданное значение.

  

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

Прокрутка окна

newWindow.scrollBy(x,y) - прокрутка окна в пикселях, x - вперед, y - назад. Возможны отрицательные значения.

newWindow.scrollTo(x,y) - прокрутить окно к указанным координатам.

element.scrollIntoView(top) - прокрутить окно так, чтобы был полностью виден указанный элемент. Если значение top равно true или не задано, тогда верх элемента совпадает с верхом экрана, если false , тогда низ с низом.

Популярные события

onresize - изменение размера окна

onload - страница загружена

onfocus - фокус установлен

  

По клику создаем pop-up, а далее отслеживаем, когда input получит фокус. При достижении события добавляем в наше всплывающее окно заветное Пора учить JavaScript.

Итого

1. Метод open() позволяет открывать всплывающие окна и новые вкладки, а также получать ссылки на них, тем самым давая возможность манипулировать ими.

2. Не только родитель имеет доступ к новому окну, но и новое окно может получить доступ к исходному с помощью свойства opener .

3. Браузеры настороженно относятся к новым окнам, которые были открыты или изменены без ведома пользователя, поэтому подобные события часто блокируются.

4. Создавая новое окно с помощью метода open() , можно указать через параметры его размер, а также как и где оно будет открыто.

5. Полезные методы для взаимодействия в новым окном:

  • close() - закрыть окно;
  • focus() - передать фокус;
  • blur() - убрать фокус;
  • moveBy(x,y) , moveTo(x,y) , resizeBy(width,height) , resizeTo(width,height) - изменение размеров и перемещение;
  • scrollBy(x,y) , scrollTo(x,y) , scrollIntoView(top) - прокрутка окна.

Skypro - научим с нуля

Источник

How to trigger a file download when clicking an HTML button or JavaScript?

Nowadays, many applications allow their users to upload and download files. For example, plagiarism checker tools allow users to upload a document file with some text. After that, it checks for plagiarism and generates a report, and users can download it.

Everyone knows to create an upload file button using the input type file, but there are few developers who know to create a file download button using JavaScript/ JQuery.

This tutorial will teach various approaches to trigger a file download when clicking an HTML button or JavaScript.

Use the download attribute with HTML tag to trigger a file download on the button click

Syntax

Users can follow the syntax below to use the tag to create a file download button.

In the above syntax, we have added the download attribute and file name as a value of the download attribute.

Parameters

Example 1

In the example below, we have taken the image URL and passed it as a value of the href attribute of the HTML tag. We have used the download button as an anchor text of tag.

Whenever users click the button, they can see that it triggers the file download.

   

Using the download attribute of tag to create file download button using JavaScript.

Click the below button to download the image file

Use the window.open() method

The window.open() method opens a URL in the new tab. We can pass the URL as a parameter of the open() method.

If the open() method can’t open the URL, it triggers the file download.

Syntax

Users can follow the syntax below to use the window.open() method to create a file download button.

In the above syntax, we have passed the file URL as a parameter of the window.open() method.

Example 2

In the example below, whenever the user clicks the button, it triggers the downloadFile() function. In the downloadFile() function window.open() method triggers the file download.

   

Using the window.open() method to create a file download button using JavaScript.

Click the below button to download the image file

Take user input, create a file using that and allow users to download the file

This approach will allow users to write texts in the input field. After that, using the input texts, we will create a new file and allow users to download that file.

Syntax

Users can follow the syntax below to create a file from the custom text and allow users to download it.

var hidden_a = document.createElement('a'); hidden_a.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(texts)); hidden_a.setAttribute('download', "text_file"); document.body.appendChild(hidden_a); hidden_a.click();

In the above syntax, we encoded the text to append it to the file and used tag to create it.

Algorithm

  • Step 1 − Get the texts from the input by accessing the HTML input.
  • Step 2 − Create a custom HTML tag using JavaScript createElement() method.
  • Step 3 − Use the setAttribute() method, and set the href attribute for the hidden_a HTML element. Use the encoded texts as a value of the href attribute.
  • Step 4 − Again, use the setAttribute() method and set the download attribute with the download file name value to the hidden_a element.
  • Step 5 − Append the hidden_a element to the body.
  • Step 6 − Use the click() method to trigger a click on the hidden_a element. When it invokes the click() method, it starts the download.
  • Step 7 − Remove the hidden_a element from the document body using the removeChild() method.

Example 3

In the example below, users can enter any custom text in the input field and click the button to trigger file download using JavaScript. We have implemented the above algorithm to trigger a file download.

   

Create the file from the custom text and allow users to download that file

Click the below button to download the file with custom text.

Use the axios library to create a download file button

The axios library allows us to fetch data from any URL. So, we will fetch data from any URL or file path, and after that, we will set that data as a value of the href attribute of tag. Also, we will add a download attribute to the tag using the setAttribute() method and trigger a click() method to start the file download.

Syntax

Users can follow the syntax below to use axios to trigger a file download using JavaScript.

let results = await axios(< url: 'file_path', method: 'GET', responseType: 'blob' >) // use results as a value of href attribute of tag to download file hidden_a.href = window.URL.createObjectURL(new Blob([results.data]));

In the above syntax, axios.get() method allows us to fetch data from the file_path stored in the results variable. After that, we converted the data to the Bolb object using the new Blob() constructor.

Example 4

In the example below, we fetch data from the URL using axios, convert it to the Blob object, and set it as a value of the href attribute.

      

Using the axios library to trigger a download file.

Click the below button to download the file with custom text.

Источник

Оцените статью