window.open()传参,window.open传递多个参数

5,780 阅读1分钟

1、window.open是什么? (what)🩺🩺🩺

  • js提供的跳转页面api

2、如何使用以及传参? (HOW)✨✨✨

2.1、简单使用 💎💍🏆🎯

复杂使用,菜鸟传送门🚪

window.open(URL)

   window.open("http://www.baidu.com");

2.2、如何传参 👓👓

  • 参数较少时 🎯🛠🎯
    • 直接在url中传递,(拼接url)
        const hello = 'world';
        const url = `http://www.baidu.com/s?wd=${hello}&test=test`;
        window.open(url);
    
  • 参数较多时,或者要传递数组或者对象时 ⚒🛠⚗💊
    • 可以使用operner去获取上一个页面(父级页面)的全局属性值
    • 利用浏览器缓存,存到localStorage,或者sessionStorage中 A页面,父页面,上级页面 📔📕📗📘
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    A页面跳转B页面,父页面,上级页面,上一级页面
    <script>
     
      //  要传递的数据
      // 方式1、发送 这里必须使用var
      var  toB = { a: "1", b: 2 };
      
      // 方式2、利用localStorage
      const toBData = [{a:1},{b:2}]
      localStorage.setItem('toBData',JSON.stringify(toBData))
      
      // 方式3、利用sessionStorage
      const toBDatas = [{c:1},{d:2}]
      sessionStorage.setItem('toBDatas',JSON.stringify(toBDatas))
      // 跳转
      window.open("./B.html");
    </script>
  </body>
</html>

B页面(跳转之后的页面)(子页面)📃📜📄📑

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    B页面,子页面,跳转后页面,下一级页面
    <script>
        // 方式1、接收
        const parent_toB = window.opener.toB;
        console.log(parent_toB) //{ a: "1", b: 2 }
        
        // 方式2、接收
        const parent_toBData = localStorage.getItem('toBData');
        console.log(parent_toBData); //[{a:1},{b:2}]
        
         // 方式3、接收
        const parent_toBDatas = window.opener.toB;
        console.log(parent_toBDatas); //[{c:1},{d:2}]
    </script>
</body>
</html>

3、什么时候使用 (when) ⌚⏰⏱⏲

  • 使用window.open(url)打开页面,打开后的页面需要从上级页面获取数据时

4、在什么环境中使用 (where)🏕🏝🏜🌎🌏

  • JS、TS的语言环境中
  • 开发页面时使用
  • 后缀以js、ts、jsx、tsx、vue、html结尾的文件

5、谁来使用 (who)👨‍🎓👩‍💻👨‍💻👩‍🔬👨‍💼👩‍💼

  • js,ts相关开发者,前端开发者

6、为什么使用 (why)🙋‍♀️🙋‍♂️💁‍♂️💁‍♀️💇‍♂️💇‍♀️

  • 需要使用js去控制页面的跳转,而不是通过用户点击某个标签
  • 基础标签中,除了A标签,其他标签没有跳转功能。
    • 给没有页面跳转功能的其他标签,增加跳转功能