Javascript window.opener.location.indexOf()函数问题

Javascript window.opener.location.indexOf()函数问题,javascript,indexof,window.opener,Javascript,Indexof,Window.opener,我试图关闭子窗口,若主机名是相同的父和子,但它的 <script type="text/javascript"> $(document).ready(function () { if (window.opener) { if (window.opener.location.indexOf(document.location.hostname) != -1) { window.opener.location

我试图关闭子窗口,若主机名是相同的父和子,但它的

<script type="text/javascript">
    $(document).ready(function () {
        if (window.opener) {
            if (window.opener.location.indexOf(document.location.hostname) != -1) {
                window.opener.location = window.location;
                window.close();
            }
        }
    });
</script>

不是字符串、数组或任何其他具有
indexOf
方法的对象。也许您想使用
opener.location.href.indexOf(…)

问题在于
location
不是
String
,而是
location
对象。您可以使用
toString
location
方法将其转换为字符串:

window.opener.location.toString().indexOf(document.location.hostname)

抓取特定属性(如href)比调用toString()更好,因为使用哪个值更明显,并且属性访问比调用方法更有效。
window.opener.location.toString().indexOf(document.location.hostname)