当我输入window控制台时。控制台显示window是的实例Window。是否可以使用创建新的窗口对象new Window()。我试过了,但抛出错误TypeError:非法构造函数
我的问题与Location对象有关。我可以使用创建一个新对象Location吗?我需要它,以便可以将location对象上可用的方法应用于链接。
我试图访问Location对象,但没有成功。
我正在使用Chrome console。
尽管这个问题已经很老了,但无论如何发布答案,因为使用本机 HTML Web API 被认为是一个很好的做法。
interface URL {
hash: string;
host: string;
hostname: string;
href: string;
readonly origin: string;
password: string;
pathname: string;
port: string;
protocol: string;
search: string;
username: string;
readonly searchParams: URLSearchParams;
toString(): string;
}
Run Code Online (Sandbox Code Playgroud)
举个例子,
var url = new URL('http://localhost:8081/route1/route2?q=test#route3/route4');
Run Code Online (Sandbox Code Playgroud)
给你以下对象-
{
hash: "#route3/route4"
host: "localhost:8081"
hostname: "localhost"
href: "http://localhost:8081/route1/route2?q=test#route3/route4"
origin: "http://localhost:8081"
password: ""
pathname: "/route1/route2"
port: "8081"
protocol: "http:"
search: "?q=test"
searchParams: URLSearchParams {}
username: ""
}
Run Code Online (Sandbox Code Playgroud)
使用前检查兼容性。
我希望这个解决方案对您有用。
不,你不能。一个浏览器窗口有一个 实例window,一个窗口有一个location. 尝试创建windowor的多个实例window.location似乎表明存在概念错误。
如果我理解你想要正确执行的操作,你应该创建一个anchor使用 javascript 进行操作的元素:
var url = document.createElement(\'a\');\nurl.href = "http://www.example.com/some/path?name=value#anchor";\nvar protocol = url.protocol;\nvar hash = url.hash;\n\nalert(\'protocol: \' + protocol);\nalert(\'hash: \' + hash);\nRun Code Online (Sandbox Code Playgroud)\n\n或者,如果您已经有锚点,则可以使用
\n\nvar url = document.getElementById(\'myanchorid\');\nRun Code Online (Sandbox Code Playgroud)\n\n\xe2\x80\x8b
\n小智 5
尝试用于Location操作任意 URI 将无法按预期工作。的Location对象/类型是不是一个一般URI容器,相反却是一个特殊的合同与DOM和其导航状态。
我通过google,YMMV通过webr3找到了这个URI JavaScript类型:
javascript 的 URI 类型
- 支持各种URI(URL、URN、任何方案)。
- 相对 URI 解析
- 所有类都扩展了本机 String 实现。
- URI 规范 (RFC-3986) 的纯 ECMA-262 实现
- Works 客户端或服务器端,(V8 / node.js 兼容)。