简体   繁体   English

当用户选择“在新选项卡中打开”/“在新窗口中打开”而不是使用 html/javascript 点击时如何到达所需的页面

[英]How to have desired page reached when a user selects “Open in New Tab”/“Open in New Window” rather than clicks with html/javascript

I am grabbing parameters from the URL and passing them to other pages on the site, so I've used this code to do it...我正在从 URL 获取参数并将它们传递到网站上的其他页面,所以我使用此代码来执行此操作...

For...为了...

https://example.com/page1/?Id=12345&Email=email@email.com

I can pass the parameters "Id" and "Email" to the next page with the code below...我可以使用下面的代码将参数“Id”和“Email”传递到下一页......

<script>
const params = new URLSearchParams(document.location.search);
const infusionId = params.get("Id");
const infusionEmail = params.get("Email");
const page2 =()=>window.location.assign(`https://example.com/page2/?Id=${infusionId}&Email=${infusionEmail}`);
</script>
<a href="#" onclick="page2()">Click here to get to Page 2</a>

This works fine when I click the link to get to next page, but if I right-click the link and select "Open in New Tab" "Open in New Window" "Open in Incognito"... the same page reloads...当我单击链接进入下一页时,这工作正常,但是如果我右键单击链接和 select “在新选项卡中打开”“在新窗口中打开”“以隐身方式打开”......相同的页面重新加载.. .

How can I set this up to work for right clicking the link and selecting to view the destination page (Page 2 in this example) in the new tab or window or incognito... or whichever way browsers can allow the destination page to show up in the browser?如何将其设置为右键单击链接并选择在新选项卡或 window 或隐身模式中查看目标页面(本例中为第 2 页)...在浏览器中?

You can set the path to page2 in the href and copy all the params directly to the search property of the <a> element from location.search .您可以在href中设置 page2 的路径,并将所有参数直接从location.search复制到<a>元素的search属性。

An <a> element has all the same properties as location does. <a>元素具有与location相同的所有属性。

If you need to remove some of the params from current page before passing to the <a> you can loop through a URLSearchParams() object and remove them from the object and pass the object itself to如果您需要在传递到<a>之前从当前页面删除一些参数,您可以循环通过 URLSearchParams URLSearchParams() object 并将它们从 object 中删除并将 object 本身传递给

 linkElement.search = mySearchParamsObject

also without needing to parse to string也无需解析为字符串

 // demo only add search params to url history.pushState(null, null, '/?Id=12345&Email=email@email.com') const link = document.querySelector('a') link.search = location.search; console.log('Updated href:\n', link.href)
 <a href="https://example.com/page2/" >Click here to get to Page 2</a>

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

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