如何将文本区域的内容发送到新窗口

How to send the content of a textarea into a new window

本文关键字:新窗口 窗口 文本 区域      更新时间:2023-09-26

我想知道如何使用 Window open() 方法将文本区域的内容发送到新窗口中。

这是我的小代码:

.HTML

 <textarea name="textcode"></textarea>
 <button  type="submit" onclick="myFunction()">Open in New window</button>

爪哇语

function myFunction() {
    window.open("insert the new window path here");
}

使用jquery使用以下代码。

.HTML

<textarea name="textcode" id="text"></textarea>
<button  type="button" id="openwindow">Open in New window</button>

jquery

$(document).ready(function(){
    $('#openwindow').click(function(){
      var value  = $('#text').val();
      window.open('https://www.google.co.in/?#q='+value);
    });
});

您将在查询字符串中获取文本区域的值.使用 PHP $_GET['param'],您将在新窗口中打印数据。

使用纯JavaScript.HTML

<textarea name="textcode" id="text"></textarea>
<button  type="button" onclick="myFunction();">Open in New window</button>

JavaScript

 function myFunction(){
    var value  = document.getElementById("text").value;
    window.open('https://www.google.co.in/?#q='+value);
 }

如果可以直接访问父窗口的内容/DOM,为什么要尝试在窗口之间发送数据?当您的文本区域的内容可以更改时,这将为您带来优势。"子页面"将保留对打开它的页面的引用!

父母.html

<textarea id="mytext" name="textcode"></textarea>
<button  type="submit" onclick="myFunction()">Open in New window</button>
<script>
function myFunction() {
    //open popup/window on the same domain
    window.open('newwindow.html','newwindow','width=350,height=350');
}
</script>

当新窗口打开时,只有当父 DOM 位于同一域中时,您才能访问它们的父 DOM。

在您的newwindow.html中,您可以使用window.opener访问您的文本区域(或任何其他 DOM 元素):

window.opener.document.getElementById("mytext").value

就像我说的,这仅在您的父窗口和子窗口位于同一域中时才有效。当父级和子级不在同一域中时,您会遇到"同源策略错误"。

但是!您可以使用Window.postMessage在不在同一域中的窗口之间安全地传递数据。并非所有浏览器都很好地支持此功能。

otherWindow.postMessage(message, targetOrigin, [transfer]);

您可以在Mozilla的开发页面上找到示例和其他信息(如浏览器支持等) 这里