WebKit should set Original URL of a download request correctly
https://bugs.webkit.org/show_bug.cgi?id=166394
<rdar://problem/25391382>

Reviewed by Alex Christensen.

WebKit should set Original URL of a download request correctly if the download
is initiated by clicking on a link with target=_blank.

Manually tested as the requested test infrastructure doesn't exist yet. We need actual
loading process for API test such that we could simulate the real situation which
PolicyDownload is only set when we receive responds. Currently we can only set
PolicyDownload in a NavigationDelegate when the load starts. Hence we cannot simulate
the following process: load starts -> PolicyUse -> creates a new WebView ->
respond receives -> PolicyDownload -> downloads.

* loader/FrameLoader.cpp:
(WebCore::FrameLoader::setOriginalURLForDownloadRequest):

git-svn-id: http://svn.webkit.org/repository/webkit/trunk@210083 268f45cc-cd09-0410-ab3c-d52691b4dbfc
diff --git a/Source/WebCore/loader/FrameLoader.cpp b/Source/WebCore/loader/FrameLoader.cpp
index 57401d3..ad63d09 100644
--- a/Source/WebCore/loader/FrameLoader.cpp
+++ b/Source/WebCore/loader/FrameLoader.cpp
@@ -2363,7 +2363,14 @@
 {
     // FIXME: Rename firstPartyForCookies back to mainDocumentURL. It was a mistake to think that it was only used for cookies.
     // The originalURL is defined as the URL of the page where the download was initiated.
-    URL originalURL = m_frame.document() ? m_frame.document()->firstPartyForCookies() : URL();
+    URL originalURL;
+    if (m_frame.document()) {
+        originalURL = m_frame.document()->firstPartyForCookies();
+        // If there is no main document URL, it means that this document is newly opened and just for download purpose.
+        // In this case, we need to set the originalURL to this document's opener's main document URL.
+        if (originalURL.isEmpty() && opener() && opener()->document())
+            originalURL = opener()->document()->firstPartyForCookies();
+    }
     // If the originalURL is the same as the requested URL, we are processing a download
     // initiated directly without a page and do not need to specify the originalURL.
     if (originalURL == request.url())