- window.open()
- Кратко
- Простой пример
- Как пишется
- Значения:
- Примеры использования
- Возможности
- Особенности применения
- Window open()
- See Also:
- Syntax
- Parameters
- Deprecated
- Warning
- Return Value
- More Examples
- Browser Support
- Load a new page in javascript
- Load a new page in javascript
- load a new page in javascript
- Loading javascript after html page load
- JQuery .load() html page with javascript inside
- Javascript onclick div element load page similar to link
window.open()
Открывает ссылку в новом окне, в новой вкладке или в iframe.
Время чтения: меньше 5 мин
Это незавершённая статья. Вы можете помочь её закончить! Почитайте о том, как контрибьютить в Доку.
Кратко
Скопировать ссылку «Кратко» Скопировано
Метод open ( ) объекта window позволяет открывать ссылки в новом окне, в новой вкладке или в iframe.
Простой пример
Скопировать ссылку «Простой пример» Скопировано
window.open('https://practicum.yandex.ru/');
window.open('https://practicum.yandex.ru/');
Как пишется
Скопировать ссылку «Как пишется» Скопировано
Метод open ( ) имеет три опциональных параметра:
window.open(url, target, windowFeatures);
window.open(url, target, windowFeatures);
url – строка, которая содержит относительный или абсолютный URL.
target – строка, которая указывает где откроется новое окно. Он может принимать те же значения, что и атрибут target тега : имя окна или одно из ключевых слов _self , _blank , _parent , _top .
window Features – строка, которая позволяет детально описать, как будет выглядеть новое окно. Опции в строке указываются через запятую в формате name = value , для булевых типов значение можно опустить.
Вызвать метод без параметров тоже можно, по умолчанию будет открыта чистая вкладка about : blank .
Значения:
Скопировать ссылку «Значения:» Скопировано
width or inner Width / height or inner Height — определит ширину и высоту содержимого окна включая полосы прокрутки. Минимальное возможное значения — 100px.
left or screen X / top or screen Y — здесь можно указать расстояние от левой верхней части (или рабочей области) экрана пользователя, на котором откроется окно.
popup — открывает ссылку в новом окне
menubar — отвечает за отображение строки меню
toolbar — управляет показом кнопок панели инструментов и панели закладок
location — отвечает за показ адресной строки
resizable — позволяет включить/выключить возможность пользователям изменять размеры окна
scrollbars — отображение полос прокрутки
status — отображение строки состояния
noopener — помогает повысить безопасность сайта, так как предотвращает доступ открываемого ресурса к текущей странице (через сеанс браузера).
При использовании noopener значения второго параметра метода open ( ) (кроме _top , _self , _parent ), будут обработаны как _blank
noreferrer — предотвращает передачу информации об исходном ресурсе на целевой. При установке этого значения как true noopener также становится true .
Примеры использования
Скопировать ссылку «Примеры использования» Скопировано
window.open("https://ya.ru/", "_self"); // ссылка откроется в текущем окне window.open("https://ya.ru/", "yandex", "popup"); // ссылка откроется в новом окне, которое примет имя "yandex" window.open("https://ya.ru/", "_blank", "top=100, left=100, width=400, height=500"); // ссылка откроется в новом окне, величина отступов и размеры окна будут соответствовать указанным
window.open("https://ya.ru/", "_self"); // ссылка откроется в текущем окне window.open("https://ya.ru/", "yandex", "popup"); // ссылка откроется в новом окне, которое примет имя "yandex" window.open("https://ya.ru/", "_blank", "top=100, left=100, width=400, height=500"); // ссылка откроется в новом окне, величина отступов и размеры окна будут соответствовать указанным
Возможности
Скопировать ссылку «Возможности» Скопировано
Использование метода open ( ) позволяет получить ссылку на новое окно и взаимодействовать с ним, например:
const newWindow = window.open("", "new window", "popup");newWindow.document.write("
Hello, World!
");// откроется новое окно с текстом "Hello, World!"const newWindow = window.open("", "new window", "popup"); newWindow.document.write("
Hello, World!
"); // откроется новое окно с текстом "Hello, World!"
Особенности применения
Скопировать ссылку «Особенности применения» Скопировано
Авторы MDN рекомендуют использовать метод open ( ) в крайних случаях и (никогда!) не прибегать к встроенному (inline) использованию window . open ( ) .
a href='#' onclick='window.open(`any url`)'>
У метода open ( ) есть несколько недостатков:
- многие браузеры блокируют попапы.
- open ( ) решает за пользователя, как именно открыть ссылку. Улучшится ли пользовательский опыт, если чтению контента будут мешать неожиданно всплывающие окна или переходы на новую вкладку (вместо открытия их в фоновом режиме)? Вряд ли.
- инлайновые значения вызывают неожиданное поведение ссылки при взаимодействии с ней (и не только). Важно и то, что они также передают неправильную семантику скринридерам.
Window open()
The open() method opens a new browser window, or a new tab, depending on your browser settings and the parameter values.
See Also:
Syntax
Parameters
Deprecated
- true — URL replaces the current document in the history list
- false — URL creates a new entry in the history list
Warning
Chrome throws an exception when using this parameter.
Return Value
More Examples
Open an about:blank page in a new window/tab:
Open a new window called «MsgWindow», and write some text into it:
var myWindow = window.open(«», «MsgWindow», «width=200,height=100»);
myWindow.document.write(«
This is ‘MsgWindow’. I am 200px wide and 100px tall!
«);
Replace the current window with a new window:
var myWindow = window.open(«», «_self»);
myWindow.document.write(«
I replaced the current window.
«);
Open a new window and control its appearance:
window.open(«https://www.w3schools.com», «_blank», «toolbar=yes,scrollbars=yes,resizable=yes,top=500,left=500,width=400,height=400»);
Open a new window. Use close() to close the new window:
function openWin() <
myWindow = window.open(«», «myWindow», «width=200,height=100»); // Opens a new window
>
function closeWin() myWindow.close(); // Closes the new window
>
Open a new window. Use the name property to return the name of the new window:
var myWindow = window.open(«», «MsgWindow», «width=200,height=100»);
myWindow.document.write(«
This window’s name is: » + myWindow.name + «
«);
Using the opener property to return a reference to the window that created the new window:
var myWindow = window.open(«», «myWindow», «width=200,height=100»); // Opens a new window
myWindow.document.write(«
This is ‘myWindow’
«); // Text in the new window
myWindow.opener.document.write(«
This is the source window!
«); // Text in the window that created the new window
Browser Support
open() is supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |
Load a new page in javascript
Solution 1: your script does not make sense is better and will execute javascrit page loaded from ajax Solution 2: Are the jQuery event handlers binded with ? http://api.jquery.com/live/ If javascript/jquery is attached to the dom after the page has loaded, normal , events wont be attached/executed. Question: i have a problem with loading .html pages (with JavaScript inside) into a div element.
Load a new page in javascript
load a new page in javascript
// Cross browser compatable redirect window.location.href = url; // Short hand not supported by all browsers window.location = url; // Set the location of the topmost window of the current window. top.location = url;
How To Add JavaScript to HTML, Adding JavaScript into an HTML Document You can add JavaScript code in an HTML document by employing the dedicated HTML tag
Loading javascript after html page load
I’m trying to make sure that an external javascript file loads last on the page.
The javascript file «script.js» (which controls the image slider) should be last. I suspect it’s not loading last right now because my webpage is covered with a red background image, which is defined in the file. When I remove the script.js file, my webpage shows up normally, but the slider functions don’t work.
On first load, the proper layout shows up for a second before being covered by the red background image.
Currently, at the end of my html file, I have:
This website is using the same exact slider, and has the javascript files in the same order, but mine doesn’t work.
My live website is here. I’ve tried
var script = document.createElement('script'); script.setAttribute('src', 'http://learningbycreating.com/js/script.js'); script.setAttribute('type', 'text/javascript'); document.getElementsByTagName('head')[0].appendChild(script);
I then tried require.js, but got pretty lost given my beginning level of javascript.
but received errors due to the use of jQuery.
This is the javascript file that’s causing problems:
(function() < var pages = [].slice.call(document.querySelectorAll('.pages >.page')), currentPage = 0, revealerOpts = < // the layers are the elements that move from the sides nmbLayers: 3, // bg color of each layer bgcolor: ['#0092DD', '#fff', 'red'], // effect classname effect: 'anim--effect-1', onStart: function(direction) < // next page gets class page--animate-[direction] var nextPage = pages[currentPage === 0 ? 0 : currentPage]; classie.add(nextPage, 'page--animate-' + direction); >, onEnd: function(direction) < // remove class page--animate-[direction] from next page var nextPage = pages[currentPage === 0 ? pages.length - 1 : 0]; nextPage.className = 'page'; >>; revealer = new Revealer(revealerOpts); // clicking the page nav buttons document.querySelector('button.pagenav__button--top').addEventListener('click', function() < reveal('top'); >); document.querySelector('button.pagenav__button--bottom').addEventListener('click', function() < reveal('bottom'); >); // triggers the effect by calling instance.reveal(direction, callbackTime, callbackFn) function reveal(direction) < var callbackTime = 750, callbackFn = function() < classie.remove(pages[currentPage], 'page--current'); currentPage = currentPage < pages.length - 1 ? currentPage + 1 : 0; classie.add(pages[currentPage], 'page--current'); >; revealer.reveal(direction, callbackTime, callbackFn); > >)();
Any chance there’s a simpler fix I’m missing?
Thanks for the details! It helps seeing the problem on the live site. It looks like you’re using WordPress, so I’d recommend enqueueing this script using the functions.php file and the wp_enqueue_script function.
Using this, you can control where the script loads and specify it if has any dependencies, like jQuery.
Here is some documentation on usage.
If this seems confusing, let me know and I can try to help further.
Thanks for the help! Once I set the 10 second window delay, I realized the trouble is not actually with javascript load order, as it’s an issue with flexbox. (The «color» slide that overlays as the transition is taking up 100% of the screen vs only 70%.) I’ll ask a separate question about that!
How do I call a JavaScript function on page load?, The first approach for calling a function on the page load is the use an onload event inside the HTML
tag. As you know, the HTML bodyJQuery .load() html page with javascript inside
i have a problem with loading .html pages (with JavaScript inside) into a div element.
var default_content=""; $(document).ready(function()< checkURL(); $('ul li a').click(function (e)< checkURL(this.hash); >); //filling in the default content default_content = $('.content').html(); setInterval("checkURL()",250); >); var lasturl=""; function checkURL(hash) < if(!hash) hash=window.location.hash; if(hash != lasturl) < lasturl=hash; // FIX - if we've used the history buttons to return to the homepage, // fill the pageContent with the default_content if(hash=="") $('.content').html(default_content); else loadPage(hash); >> function loadPage(url) < url=url.replace('#page',''); $('.content').css('visibility','visible'); $.ajax(< type: "POST", url: "load_page.php", data: 'page='+url, dataType: "html", success: function(msg)< if(parseInt(msg)!=0) < $('.content').html(msg); >> >); >
When the page is loaded the JavaScript code inside the .html page isn’t executed. If i click on the browser reload button the JavaScript code is executed.
How can i execute the JavaScript inside the pages using jquery?
your script does not make sense
is better and will execute javascrit page loaded from ajax
Are the jQuery event handlers binded with live() ?
If javascript/jquery is attached to the dom after the page has loaded, normal click() , change() events wont be attached/executed.
You need to attach these events using live() .
$('#some_element').live('click', function()<>);
live() will initialize the event handler whenever an element is attached to the page.
Window: load event, 6 days ago · The load event is fired when the whole page has loaded, including all dependent resources such as stylesheets and images. This is in
Javascript onclick div element load page similar to link
How do I load another page on the onClick event in Javascript?
The code above is not working. Please explain. I am sure it’s quite simple. Thanks in advance!
Here’s a working example: http://jsfiddle.net/ArtBIT/EEjyP/
How to run a function when the page is loaded in JavaScript, The onload property processes load events after the element has finished loading. This is used with the window element to execute a script after