--- title: Location.replace() slug: Web/API/Location/replace tags: - API - DOM - Location - 参考 - 导航 - 方法 translation_of: Web/API/Location/replace --- <p>{{ APIRef("Location") }}</p> <p><code><strong>Location</strong></code><strong><code>.replace()</code></strong> 方法以给定的URL来替换当前的资源。 与{{domxref("Location.assign","assign()")}} 方法 不同的是,调用 <code>replace()</code> 方法后,当前页面不会保存到会话历史中(session {{domxref("History")}}),这样,用户点击<em>回退</em>按钮时,将不会再跳转到该页面。</p> <p>因违反安全规则导致的赋值失败,浏览器将会抛出类型为 <code>SECURITY_ERROR</code> 的 {{domxref("DOMException")}} 异常。当调用该方法的脚本所属的源与拥有 {{domxref("Location")}} 对象所属源不同时,通常情况会发生这种异常,此时通常该脚本是存在不同的域下。</p> <p>如果 URL 无效,浏览器也会抛出 <code>SYNTAX_ERROR</code> 类型的 {{domxref("DOMException")}} 异常。</p> <h2 id="语法">语法</h2> <pre class="syntaxbox notranslate"><em>object</em>.replace(<em>url</em>); </pre> <h3 id="参数">参数</h3> <dl> <dt><em>url</em></dt> <dd> {{domxref("DOMString")}} 类型,指定所导航到的页面的 URL 地址。</dd> </dl> <h2 id="示例">示例</h2> <pre class="brush: js notranslate">// Navigate to the Location.reload article by replacing this page window.location.replace('https://developer.mozilla.org/en-US/docs/Web/API/Location/reload');</pre> <h2 id="标准">标准</h2> <table class="standard-table"> <tbody> <tr> <th scope="col">Specification</th> <th scope="col">Status</th> <th scope="col">Comment</th> </tr> <tr> <td>{{SpecName('HTML WHATWG', "history.html#dom-location-replace", "Location.replace()")}}</td> <td>{{Spec2('HTML WHATWG')}}</td> <td>No change from {{SpecName("HTML5 W3C")}}.</td> </tr> <tr> <td>{{SpecName('HTML5 W3C', "browsers.html#dom-location-replace", "Location.replace()")}}</td> <td>{{Spec2('HTML5 W3C')}}</td> <td>Initial definition.</td> </tr> </tbody> </table> <h2 id="浏览器兼容性">浏览器兼容性</h2> <p>{{Compat("api.Location.replace")}}</p> <h2 id="参见">参见</h2> <ul> <li>{{domxref("Location")}} 对象。</li> <li>类似方法: {{domxref("Location.assign()")}} 和 {{domxref("Location.reload()")}}。</li> </ul>