简体   繁体   English

设置使用window.open()打开的空白页的哈希

[英]Set hash of blank page opened with window.open()

I have a page that was dynamically made using javascript's window.open(); 我有一个页面是使用javascript的window.open();动态创建的window.open(); function. 功能。 This opens a new window with a URL of about:blank and then I inject the rest of the code into the page. 这将打开一个新的URL为about:blank窗口,然后将其余代码注入页面。 I'm trying to detect whether or not the user refreshes the page and then in a later script tell the opener that the task was completed (hence why this page isn't a static one, it needs to communicate with another open tab) 我正在尝试检测用户是否刷新页面,然后在以后的脚本中告诉启动器任务已完成(因此,该页面不是静态页面,它需要与另一个打开的选项卡进行通信)

The problem is, is doesn't seem to be setting the hash on the end of the URL. 问题是,似乎没有在URL末尾设置哈希值。 I'm not even sure if its even possible to do this since it's not an actual URL. 我什至不知道是否有可能这样做,因为它不是实际的URL。

if (document.location.hash=="#one") {
    alert('Good Job!')
} else {
    document.onunload=function() {
        window.location.href = window.location.href+encodeURIComponent("#one");
    }
 }

I had used encodeURIComponent() because i had heard somewhere that it was good practice to do so in case of non-alphanumerics. 我之所以使用encodeURIComponent()是因为我听说某处是非字母数字的良好做法。 I'm not sure if this is the problem or if I should have used href=#one but neither seemed to work. 我不确定这是否是问题,还是应该使用href=#one但都没有用。

Any solutions? 有什么办法吗?

encodeURIComponent converts characters with special meaning in a URL (such as # ) to encoded versions that don't have that special meaning, so that is the problem (because you need the special meaning "starts the fragment identifier"). encodeURIComponent将URL中具有特殊含义的字符(例如# )转换为没有特殊含义的编码版本,因此这就是问题所在(因为您需要特殊含义“启动片段标识符”)。

one has no special characters, so it doesn't need encoding. one没有特殊字符,因此不需要编码。 If you were taking input and you didn't know if it contained special characters then you would exclude the # from the encoding. 如果您正在输入,并且不知道其中是否包含特殊字符,则可以从编码中排除#。

window.location.href + "#" + encodeURIComponent(some_string_here);

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

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