<!DOCTYPE html>
<script src="/js-test-resources/js-test.js"></script>
<base href="foo/bar/">
<body></body>
<script>

description("Test for HTMLBaseElement's href attribute.");
jsTestIsAsync = true;

function endsWith(string, substring)
{
    var length = string.length - substring.length;
    return length >= 0 && string.indexOf(substring, length) === length;
}

onload = () => {
    base = document.querySelector('base');
    shouldBeTrue("endsWith(document.querySelector('base').href, 'foo/bar/')");
    shouldBeFalse("endsWith(document.querySelector('base').href, 'foo/bar/foo/bar/')");

    base.href = null;
    shouldBeTrue("document.querySelector('base').hasAttribute('href')");
    shouldBeTrue("endsWith(document.querySelector('base').href, '/null')");

    base.removeAttribute('href');
    shouldBeFalse("document.querySelector('base').hasAttribute('href')");
    shouldBeTrue("endsWith(document.querySelector('base').href, '/href-attribute-resolves-with-respect-to-document.html')");

    // When a document does not have a URL, base cannot be resolved

    // Make sure that we don't use the creator document as the base.
    documentWithoutAView = document.implementation.createHTMLDocument('');
    base = documentWithoutAView.head.appendChild(documentWithoutAView.createElement('base'));
    base.setAttribute('href', 'foo/bar/');
    shouldBeEqualToString("documentWithoutAView.querySelector('base').href", 'foo/bar/');
    base.setAttribute('href', 'http://webkit.org/');
    shouldBeEqualToString("documentWithoutAView.querySelector('base').href", 'http://webkit.org/');

    // Make sure that we use the parent document as the base.
    iframe = document.body.appendChild(document.createElement('iframe'));
    base = iframe.contentDocument.head.appendChild(iframe.contentDocument.createElement('base'));
    base.setAttribute('href', 'foo/bar/');
    shouldBeEqualToString("iframe.contentDocument.querySelector('base').href", 'http://127.0.0.1:8000/misc/foo/bar/');

    // Make sure that we use the opener document as the base.
    newWindow = window.open('about:blank');
    base = newWindow.document.head.appendChild(newWindow.document.createElement('base'));
    base.setAttribute('href', 'foo/bar/');
    shouldBeEqualToString("newWindow.document.querySelector('base').href", 'http://127.0.0.1:8000/misc/foo/bar/');
    newWindow.close();

    setTimeout(finishJSTest, 0);
}
</script>
