简体   繁体   English

打开一个新页面并在该新页面中运行 javascript function

[英]To open a new page and run a javascript function in that new page

Hi i am trying to open a new page using button click from page 1 and in the page 2 i want to have a popup message using alert.嗨,我正在尝试使用第 1 页的按钮单击打开一个新页面,在第 2 页中我想使用警报弹出消息。 But the alert is executed in my page 1 itself.但是警报是在我的第 1 页本身中执行的。 Please let me know if i am doing anything wrong.如果我做错了什么,请告诉我。

function sendemail(){
alert('success');
var popup = window.open();
window.onload = test();
function test(){
alert('new');
}
}
sndWelcomEmail.addEventListener('click',sendemail);

You can try one thing, when you create a new window append a script tag in it.您可以尝试一件事,当您在其中创建一个新的 window append 脚本标签时。 Create a test.js file and add that in.创建一个 test.js 文件并将其添加进去。

var newWindow = window.open('');
newWindow.document.createElement('script');
script.src = 'js/sample.js';
newWindow.document.head.appendChild(script);

Or,或者,

var newWindow = window.open('') // open a blank tab;
newWindow.document.write('<script>alert("Hello World!")</script>');

Use something like websockets for that, sync user and sent data between pages, executing scripts from one page directly on another is prohibited, its pure xss.为此使用 websockets 之类的东西,在页面之间同步用户和发送数据,禁止从一个页面直接在另一个页面上执行脚本,它是纯 xss。

I cannot test it right now but try using我现在无法测试,但尝试使用

popup.onload = test()

imstead of而不是

window.onload = test()

In the page 2第 2 页

First, Add an onload function in body tag首先,在body标签中添加一个onload function

<body onload="myFunction()">

Second, Add this JS Script二、添加这个JS脚本

<script>
function myFunction() {
  alert("Page is loaded");
}
</script>

Simply alert the new window not the old one:只需提醒新的 window 而不是旧的:

function sendemail() {
    var popup = window.open();
    window.onload = test();
    function test() {
        popup.alert('new');
    }
}

sndWelcomEmail.addEventListener('click', sendemail);

The main problem is how does the page 2 knows that user is coming from page 1 and wants a popUp.主要问题是第 2 页如何知道用户来自第 1 页并想要一个弹出窗口。 There are plenty of ways to solve this issues.有很多方法可以解决这个问题。

  1. Add a hash value, which can be passed to page 2, using the address bar.添加一个 hash 值,可以使用地址栏传递到第 2 页。 (Page 2 looks at the hash value in the address bar, then does whats needed. EG.http:kdsjhf.com/#openAlert (第 2 页查看地址栏中的 hash 值,然后执行所需的操作。EG.http:kdsjhf.com/#openAlert
  2. Use more refined approach using pop-state and history object to pass data between navigating pages.使用更精细的方法使用弹出状态和历史 object 在导航页面之间传递数据。 3.PWA. 3.PWA。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM