1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468 9469 9470 9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566 9567 9568 9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 9581 9582 9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593 9594 9595 9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609 9610 9611 9612 9613 9614 9615 9616 9617 9618 9619 9620 9621 9622 9623 9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 9634 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655 9656 9657 9658 9659 9660 9661 9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684 9685 9686 9687 9688 9689 9690 9691 9692 9693 9694 9695 9696 9697 9698 9699 9700 9701 9702 9703 9704 9705 9706 9707 9708 9709 9710 9711 9712 9713 9714 9715 9716 9717 9718 9719 9720 9721 9722 9723 9724 9725 9726 9727 9728 9729 9730 9731 9732 9733 9734 9735 9736 9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753 9754 9755 9756 9757 9758 9759 9760 9761 9762 9763 9764 9765 9766 9767 9768 9769 9770 9771 9772 9773 9774 9775 9776 9777 9778 9779 9780 9781 9782 9783 9784 9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800 9801 9802 9803 9804 9805 9806 9807 9808 9809 9810 9811 9812 9813 9814 9815 9816 9817 9818 9819 9820 9821 9822 9823 9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836 9837 9838 9839 9840 9841 9842 9843 9844 9845 9846 9847 9848 9849 9850 9851 9852 9853 9854 9855 9856 9857 9858 9859 9860 9861 9862 9863 9864 9865 9866 9867 9868 9869 9870 9871 9872 9873 9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890 9891 9892 9893 9894 9895 9896 9897 9898 9899 9900 9901 9902 9903 9904 9905 9906 9907 9908 9909 9910 9911 9912 9913 9914 9915 9916 9917 9918 9919 9920 9921 9922 9923 9924 9925 9926 9927 9928 9929 9930 9931 9932 9933 9934 9935 9936 9937 9938 9939 9940 9941 9942 9943 9944 9945 9946 9947 9948 9949 9950 9951 9952 9953 9954 9955 9956 9957 9958 9959 9960 9961 9962 9963 9964 9965 9966 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980 9981 9982 9983 9984 9985 9986 9987 9988 9989 9990 9991 9992 9993 9994 9995 9996 9997 9998 9999 10000 10001 10002 10003 10004 10005 10006 10007 10008 10009 10010 10011 10012 10013 10014 10015 10016 10017 10018 10019 10020 10021 10022 10023 10024 10025 10026 10027 10028 10029 10030 10031 10032 10033 10034 10035 10036 10037 10038 10039 10040 10041 10042 10043 10044 10045 10046 10047 10048 10049 10050 10051 10052 10053 10054 10055 10056 10057 10058 10059 10060 10061 10062 10063 10064 10065 10066 10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089 10090 10091 10092 10093 10094 10095 10096 10097 10098 10099 10100 10101 10102 10103 10104 10105 10106 10107 10108 10109 10110 10111 10112 10113 10114 10115 10116 10117 10118 10119 10120 10121 10122 10123 10124 10125 10126 10127 10128 10129 10130 10131 10132 10133 10134 10135 10136 10137 10138 10139 10140 10141 10142 10143 10144 10145 10146 10147 10148 10149 10150 10151 10152 10153 10154 10155 10156 10157 10158 10159 10160 10161 10162 10163 10164 10165 10166 10167 10168 10169 10170 10171 10172 10173 10174 10175 10176 10177 10178 10179 10180 10181 10182 10183 10184 10185 10186 10187 10188 10189 10190 10191 10192 10193 10194 10195 10196 10197 10198 10199 10200 10201 10202 10203 10204 10205 10206 10207 10208 10209 10210 10211 10212 10213 10214 10215 10216 10217 10218 10219 10220 10221 10222 10223 10224 10225 10226 10227 10228 10229 10230 10231 10232 10233 10234 10235 10236 10237 10238 10239 10240 10241 10242 10243 10244 10245 10246 10247 10248 10249 10250 10251 10252 10253 10254 10255 10256 10257 10258 10259 10260 10261 10262 10263 10264 10265 10266 10267 10268 10269 10270 10271 10272 10273 10274 10275 10276 10277 10278 10279 10280 10281 10282 10283 10284 10285 10286 10287 10288 10289 10290 10291 10292 10293 10294 10295 10296 10297 10298 10299 10300 10301 10302 10303 10304 10305 10306 10307 10308 10309 10310 10311 10312 10313 10314 10315 10316 10317 10318 10319 10320 10321 10322 10323 10324 10325 10326 10327 10328 10329 10330 10331 10332 10333 10334 10335 10336 10337 10338 10339 10340 10341 10342 10343 10344 10345 10346 10347 10348 10349 10350 10351 10352 10353 10354 10355 10356 10357 10358 10359 10360 10361 10362 10363 10364 10365 10366 10367 10368 10369 10370 10371 10372 10373 10374 10375 10376 10377 10378 10379 10380 10381 10382 10383 10384 10385 10386 10387 10388 10389 10390 10391 10392 10393 10394 10395 10396 10397 10398 10399 10400 10401 10402 10403 10404 10405 10406 10407 10408 10409 10410 10411 10412 10413 10414 10415 10416 10417 10418 10419 10420 10421 10422 10423 10424 10425 10426 10427 10428 10429 10430 10431 10432 10433 10434 10435 10436 10437 10438 10439 10440 10441 10442 10443 10444 10445 10446 10447 10448 10449 10450 10451 10452 10453 10454 10455 10456 10457 10458 10459 10460 10461 10462 10463 10464 10465 10466 10467 10468 10469 10470 10471 10472 10473 10474 10475 10476 10477 10478 10479 10480 10481 10482 10483 10484 10485 10486 10487 10488 10489 10490 10491 10492 10493 10494 10495 10496 10497 10498 10499 10500 10501 10502 10503 10504 10505 10506 10507 10508 10509 10510 10511 10512 10513 10514 10515 10516 10517 10518 10519 10520 10521 10522 10523 10524 10525 10526 10527 10528 10529 10530 10531 10532 10533 10534 10535 10536 10537 10538 10539 10540 10541 10542 10543 10544 10545 10546 10547 10548 10549 10550 10551 10552 10553 10554 10555 10556 10557 10558 10559 10560 10561 10562 10563 10564 10565 10566 10567 10568 10569 10570 10571 10572 10573 10574 10575 10576 10577 10578 10579 10580 10581 10582 10583 10584 10585 10586 10587 10588 10589 10590 10591 10592 10593 10594 10595 10596 10597 10598 10599 10600 10601 10602 10603 10604 10605 10606 10607 10608 10609 10610 10611 10612 10613 10614 10615 10616 10617 10618 10619 10620 10621 10622 10623 10624 10625 10626 10627 10628 10629 10630 10631 10632 10633 10634 10635 10636 10637 10638 10639 10640 10641 10642 10643 10644 10645 10646 10647 10648 10649 10650 10651 10652 10653 10654 10655 10656 10657 10658 10659 10660 10661 10662 10663 10664 10665 10666 10667 10668 10669 10670 10671 10672 10673 10674 10675 10676 10677 10678 10679 10680 10681 10682 10683 10684 10685 10686 10687 10688 10689 10690 10691 10692 10693 10694 10695 10696 10697 10698 10699 10700 10701 10702 10703 10704 10705 10706 10707 10708 10709 10710 10711 10712 10713 10714 10715 10716 10717 10718 10719 10720 10721 10722 10723 10724 10725 10726 10727 10728 10729 10730 10731 10732 10733 10734 10735 10736 10737 10738 10739 10740 10741 10742 10743 10744 10745 10746 10747 10748 10749 10750 10751 10752 10753 10754 10755 10756 10757 10758 10759 10760 10761 10762 10763 10764 10765 10766 10767 10768 10769 10770 10771 10772 10773 10774 10775 10776 10777 10778 10779 10780 10781 10782 10783 10784 10785 10786 10787 10788 10789 10790 10791 10792 10793 10794 10795 10796 10797 10798 10799 10800 10801 10802 10803 10804 10805 10806 10807 10808 10809 10810 10811 10812 10813 10814 10815 10816 10817 10818 10819 10820 10821 10822 10823 10824 10825 10826 10827 10828 10829 10830 10831 10832 10833 10834 10835 10836 10837 10838 10839 10840 10841 10842 10843 10844 10845 10846 10847 10848 10849 10850 10851 10852 10853 10854 10855 10856 10857 10858 10859 10860 10861 10862 10863 10864 10865 10866 10867 10868 10869 10870 10871 10872 10873 10874 10875 10876 10877 10878 10879 10880 10881 10882 10883 10884 10885 10886 10887 10888 10889 10890 10891 10892 10893 10894 10895 10896 10897 10898 10899 10900 10901 10902 10903 10904 10905 10906 10907 10908 10909 10910 10911 10912 10913 10914 10915 10916 10917 10918 10919 10920 10921 10922 10923 10924 10925 10926 10927 10928 10929 10930 10931 10932 10933 10934 10935 10936 10937 10938 10939 10940 10941 10942 10943 10944 10945 10946 10947 10948 10949 10950 10951 10952 10953 10954 10955 10956 10957 10958 10959 10960 10961 10962 10963 10964 10965 10966 10967 10968 10969 10970 10971 10972 10973 10974 10975 10976 10977 10978 10979 10980 10981 10982 10983 10984 10985 10986 10987 10988 10989 10990 10991 10992 10993 10994 10995 10996 10997 10998 10999 11000 11001 11002 11003 11004 11005 11006 11007 11008 11009 11010 11011 11012 11013 11014 11015 11016 11017 11018 11019 11020 11021 11022 11023 11024 11025 11026 11027 11028 11029 11030 11031 11032 11033 11034 11035 11036 11037 11038 11039 11040 11041 11042 11043 11044 11045 11046 11047 11048 11049 11050 11051 11052 11053 11054 11055 11056 11057 11058 11059 11060 11061 11062 11063 11064 11065 11066 11067 11068 11069 11070 11071 11072 11073 11074 11075 11076 11077 11078 11079 11080 11081 11082 11083 11084 11085 11086 11087 11088 11089 11090 11091 11092 11093 11094 11095 11096 11097 11098 11099 11100 11101 11102 11103 11104 11105 11106 11107 11108 11109 11110 11111 11112 11113 11114 11115 11116 11117 11118 11119 11120 11121 11122 11123 11124 11125 11126 11127 11128 11129 11130 11131 11132 11133 11134 11135 11136 11137 11138 11139 11140 11141 11142 11143 11144 11145 11146 11147 11148 11149 11150 11151 11152 11153 11154 11155 11156 11157 11158 11159 11160 11161 11162 11163 11164 11165 11166 11167 11168 11169 11170 11171 11172 11173 11174 11175 11176 11177 11178 11179 11180 11181 11182 11183 11184 11185 11186 11187 11188 11189 11190 11191 11192 11193 11194 11195 11196 11197 11198 11199 11200 11201 11202 11203 11204 11205 11206 11207 11208 11209 11210 11211 11212 11213 11214 11215 11216 11217 11218 11219 11220 11221 11222 11223 11224 11225 11226 11227 11228 11229 11230 11231 11232 11233 11234 11235 11236 11237 11238 11239 11240 11241 11242 11243 11244 11245 11246 11247 11248 11249 11250 11251 11252 11253 11254 11255 11256 11257 11258 11259 11260 11261 11262 11263 11264 11265 11266 11267 11268 11269 11270 11271 11272 11273 11274 11275 11276 11277 11278 11279 11280 11281 11282 11283 11284 11285 11286 11287 11288 11289 11290 11291 11292 11293 11294 11295 11296 11297 11298 11299 11300 11301 11302 11303 11304 11305 11306 11307 11308 11309 11310 11311 11312 11313 11314 11315 11316 11317 11318 11319 11320 11321 11322 11323 11324 11325 11326 11327 11328 11329 11330 11331 11332 11333 11334 11335 11336 11337 11338 11339 11340 11341 11342 11343 11344 11345 11346 11347 11348 11349 11350 11351 11352 11353 11354 11355 11356 11357 11358 11359 11360 11361 11362 11363 11364 11365 11366 11367 11368 11369 11370 11371 11372 11373 11374 11375 11376 11377 11378 11379 11380 11381 11382 11383 11384 11385 11386 11387 11388 11389 11390 11391 11392 11393 11394 11395 11396 11397 11398 11399 11400 11401 11402 11403 11404 11405 11406 11407 11408 11409 11410 11411 11412 11413 11414 11415 11416 11417 11418 11419 11420 11421 11422 11423 11424 11425 11426 11427 11428 11429 11430 11431 11432 11433 11434 11435 11436 11437 11438 11439 11440 11441 11442 11443 11444 11445 11446 11447 11448 11449 11450 11451 11452 11453 11454 11455 11456 11457 11458 11459 11460 11461 11462 11463 11464 11465 11466 11467 11468 11469 11470 11471 11472 11473 11474 11475 11476 11477 11478 11479 11480 11481 11482 11483 11484 11485 11486 11487 11488 11489 11490 11491 11492 11493 11494 11495 11496 11497 11498 11499 11500 11501 11502 11503 11504 11505 11506 11507 11508 11509 11510 11511 11512 11513 11514 11515 11516 11517 11518 11519 11520 11521 11522 11523 11524 11525 11526 11527 11528 11529 11530 11531 11532 11533 11534 11535 11536 11537 11538 11539 11540 11541 11542 11543 11544 11545 11546 11547 11548 11549 11550 11551 11552 11553 11554 11555 11556 11557 11558 11559 11560 11561 11562 11563 11564 11565 11566 11567 11568 11569 11570 11571 11572 11573 11574 11575 11576 11577 11578 11579 11580 11581 11582 11583 11584 11585 11586 11587 11588 11589 11590 11591 11592 11593 11594 11595 11596 11597 11598 11599 11600 11601 11602 11603 11604 11605 11606 11607 11608 11609 11610 11611 11612 11613 11614 11615 11616 11617 11618 11619 11620 11621 11622 11623 11624 11625 11626 11627 11628 11629 11630 11631 11632 11633 11634 11635 11636 11637 11638 11639 11640 11641 11642 11643 11644 11645 11646 11647 11648 11649 11650 11651 11652 11653 11654 11655 11656 11657 11658 11659 11660 11661 11662 11663 11664 11665 11666 11667 11668 11669 11670 11671 11672 11673 11674 11675 11676 11677 11678 11679 11680 11681 11682 11683 11684 11685 11686 11687 11688 11689 11690 11691 11692 11693 11694 11695 11696 11697 11698 11699 11700 11701 11702 11703 11704 11705 11706 11707 11708 11709 11710 11711 11712 11713 11714 11715 11716 11717 11718 11719 11720 11721 11722 11723 11724 11725 11726 11727 11728 11729 11730 11731 11732 11733 11734 11735 11736 11737 11738 11739 11740 11741 11742 11743 11744 11745 11746 11747 11748 11749 11750 11751 11752 11753 11754 11755 11756 11757 11758 11759 11760 11761 11762 11763 11764 11765 11766 11767 11768 11769 11770 11771 11772 11773 11774 11775 11776 11777 11778 11779 11780 11781 11782 11783 11784 11785 11786 11787 11788 11789 11790 11791 11792 11793 11794 11795 11796 11797 11798 11799 11800 11801 11802 11803 11804 11805 11806 11807 11808 11809 11810 11811 11812 11813 11814 11815 11816 11817 11818 11819 11820 11821 11822 11823 11824 11825 11826 11827 11828 11829 11830 11831 11832 11833 11834 11835 11836 11837 11838 11839 11840 11841 11842 11843 11844 11845 11846 11847 11848 11849 11850 11851 11852 11853 11854 11855 11856 11857 11858 11859 11860 11861 11862 11863 11864 11865 11866 11867 11868 11869 11870 11871 11872 11873 11874 11875 11876 11877 11878 11879 11880 11881 11882 11883 11884 11885 11886 11887 11888 11889 11890 11891 11892 11893 11894 11895 11896 11897 11898 11899 11900 11901 11902 11903 11904 11905 11906 11907 11908 11909 11910 11911 11912 11913 11914 11915 11916 11917 11918 11919 11920 11921 11922 11923 11924 11925 11926 11927 11928 11929 11930 11931 11932 11933 11934 11935 11936 11937 11938 11939 11940 11941 11942 11943 11944 11945 11946 11947 11948 11949 11950 11951 11952 11953 11954 11955 11956 11957 11958 11959 11960 11961 11962 11963 11964 11965 11966 11967 11968 11969 11970 11971 11972 11973 11974 11975 11976 11977 11978 11979 11980 11981 11982 11983 11984 11985 11986 11987 11988 11989 11990 11991 11992 11993 11994 11995 11996 11997 11998 11999 12000 12001 12002 12003 12004 12005 12006 12007 12008 12009 12010 12011 12012 12013 12014 12015 12016 12017 12018 12019 12020 12021 12022 12023 12024 12025 12026 12027 12028 12029 12030 12031 12032 12033 12034 12035 12036 12037 12038 12039 12040 12041 12042 12043 12044 12045 12046 12047 12048 12049 12050 12051 12052 12053 12054 12055 12056 12057 12058 12059 12060 12061 12062 12063 12064 12065 12066 12067 12068 12069 12070 12071 12072 12073 12074 12075 12076 12077 12078 12079 12080 12081 12082 12083 12084 12085 12086 12087 12088 12089 12090 12091 12092 12093 12094 12095 12096 12097 12098 12099 12100 12101 12102 12103 12104 12105 12106 12107 12108 12109 12110 12111 12112 12113 12114 12115 12116 12117 12118 12119 12120 12121 12122 12123 12124 12125 12126 12127 12128 12129 12130 12131 12132 12133 12134 12135 12136 12137 12138 12139 12140 12141 12142 12143 12144 12145 12146 12147 12148 12149 12150 12151 12152 12153 12154 12155 12156 12157 12158 12159 12160 12161 12162 12163 12164 12165 12166 12167 12168 12169 12170 12171 12172 12173 12174 12175 12176 12177 12178 12179 12180 12181 12182 12183 12184 12185 12186 12187 12188 12189 12190 12191 12192 12193 12194 12195 12196 12197 12198 12199 12200 12201 12202 12203 12204 12205 12206 12207 12208 12209 12210 12211 12212 12213 12214 12215 12216 12217 12218 12219 12220 12221 12222 12223 12224 12225 12226 12227 12228 12229 12230 12231 12232 12233 12234 12235 12236 12237 12238 12239 12240 12241 12242 12243 12244 12245 12246 12247 12248 12249 12250 12251 12252 12253 12254 12255 12256 12257 12258 12259 12260 12261 12262 12263 12264 12265 12266 12267 12268 12269 12270 12271 12272 12273 12274 12275 12276 12277 12278 12279 12280 12281 12282 12283 12284 12285 12286 12287 12288 12289 12290 12291 12292 12293 12294 12295 12296 12297 12298 12299 12300 12301 12302 12303 12304 12305 12306 12307 12308 12309 12310 12311 12312 12313 12314 12315 12316 12317 12318 12319 12320 12321 12322 12323 12324 12325 12326 12327 12328 12329 12330 12331 12332 12333 12334 12335 12336 12337 12338 12339 12340 12341 12342 12343 12344 12345 12346 12347 12348 12349 12350 12351 12352 12353 12354 12355 12356 12357 12358 12359 12360 12361 12362 12363 12364 12365 12366 12367 12368 12369 12370 12371 12372 12373 12374 12375 12376 12377 12378 12379 12380 12381 12382 12383 12384 12385 12386 12387 12388 12389 12390 12391 12392 12393 12394 12395 12396 12397 12398 12399 12400 12401 12402 12403 12404 12405 12406 12407 12408 12409 12410 12411 12412 12413 12414 12415 12416 12417 12418 12419 12420 12421 12422 12423 12424 12425 12426 12427 12428 12429 12430 12431 12432 12433 12434 12435 12436 12437 12438 12439 12440 12441 12442 12443 12444 12445 12446 12447 12448 12449 12450 12451 12452 12453 12454 12455 12456 12457 12458 12459 12460 12461 12462 12463 12464 12465 12466 12467 12468 12469 12470 12471 12472 12473 12474 12475 12476 12477 12478 12479 12480 12481 12482 12483 12484 12485 12486 12487 12488 12489 12490 12491 12492 12493 12494 12495 12496 12497 12498 12499 12500 12501 12502 12503 12504 12505 12506 12507 12508 12509 12510 12511 12512 12513 12514 12515 12516 12517 12518 12519 12520 12521 12522 12523 12524 12525 12526 12527 12528 12529 12530 12531 12532 12533 12534 12535 12536 12537 12538 12539 12540 12541 12542 12543 12544 12545 12546 12547 12548 12549 12550 12551 12552 12553 12554 12555 12556 12557 12558 12559 12560 12561 12562 12563 12564 12565 12566 12567 12568 12569 12570 12571 12572 12573 12574 12575 12576 12577 12578 12579 12580 12581 12582 12583 12584 12585 12586 12587 12588 12589 12590 12591 12592 12593 12594 12595 12596 12597 12598 12599 12600 12601 12602 12603 12604 12605 12606 12607 12608 12609 12610 12611 12612 12613 12614 12615 12616 12617 12618 12619 12620 12621 12622 12623 12624 12625 12626 12627 12628 12629 12630 12631 12632 12633 12634 12635 12636 12637 12638 12639 12640 12641 12642 12643 12644 12645 12646 12647 12648 12649 12650 12651 12652 12653 12654 12655 12656 12657 12658 12659 12660 12661 12662 12663 12664 12665 12666 12667 12668 12669 12670 12671 12672 12673 12674 12675 12676 12677 12678 12679 12680 12681 12682 12683 12684 12685 12686 12687 12688 12689 12690 12691 12692 12693 12694 12695 12696 12697 12698 12699 12700 12701 12702 12703 12704 12705 12706 12707 12708 12709 12710 12711 12712 12713 12714 12715 12716 12717 12718 12719 12720 12721 12722 12723 12724 12725 12726 12727 12728 12729 12730 12731 12732 12733 12734 12735 12736 12737 12738 12739 12740 12741 12742 12743 12744 12745 12746 12747 12748 12749 12750 12751 12752 12753 12754 12755 12756 12757 12758 12759 12760 12761 12762 12763 12764 12765 12766 12767 12768 12769 12770 12771 12772 12773 12774 12775 12776 12777 12778 12779 12780 12781 12782 12783 12784 12785 12786 12787 12788 12789 12790 12791 12792 12793 12794 12795 12796 12797 12798 12799 12800 12801 12802 12803 12804 12805 12806 12807 12808 12809 12810 12811 12812 12813 12814 12815 12816 12817 12818 12819 12820 12821 12822 12823 12824 12825 12826 12827 12828 12829 12830 12831 12832 12833 12834 12835 12836 12837 12838 12839 12840 12841 12842 12843 12844 12845 12846 12847 12848 12849 12850 12851 12852 12853 12854 12855 12856 12857 12858 12859 12860 12861 12862 12863 12864 12865 12866 12867 12868 12869 12870 12871 12872 12873 12874 12875 12876 12877 12878 12879 12880 12881 12882 12883 12884 12885 12886 12887 12888 12889 12890 12891 12892 12893 12894 12895 12896 12897 12898 12899 12900 12901 12902 12903 12904 12905 12906 12907 12908 12909 12910 12911 12912 12913 12914 12915 12916 12917 12918 12919 12920 12921 12922 12923 12924 12925 12926 12927 12928 12929 12930 12931 12932 12933 12934 12935 12936 12937 12938 12939 12940 12941 12942 12943 12944 12945 12946 12947 12948 12949 12950 12951 12952 12953 12954 12955 12956 12957 12958 12959 12960 12961 12962 12963 12964 12965 12966 12967 12968 12969 12970 12971 12972 12973 12974 12975 12976 12977 12978 12979 12980 12981 12982 12983 12984 12985 12986 12987 12988 12989 12990 12991 12992 12993 12994 12995 12996 12997 12998 12999 13000 13001 13002 13003 13004 13005 13006 13007 13008 13009 13010 13011 13012 13013 13014 13015 13016 13017 13018 13019 13020 13021 13022 13023 13024 13025 13026 13027 13028 13029 13030 13031 13032 13033 13034 13035 13036 13037 13038 13039 13040 13041 13042 13043 13044 13045 13046 13047 13048 13049 13050 13051 13052 13053 13054 13055 13056 13057 13058 13059 13060 13061 13062 13063 13064 13065 13066 13067 13068 13069 13070 13071 13072 13073 13074 13075 13076 13077 13078 13079 13080 13081 13082 13083 13084 13085 13086 13087 13088 13089 13090 13091 13092 13093 13094 13095 13096 13097 13098 13099 13100 13101 13102 13103 13104 13105 13106 13107 13108 13109 13110 13111 13112 13113 13114 13115 13116 13117 13118 13119 13120 13121 13122 13123 13124 13125 13126 13127 13128 13129 13130 13131 13132 13133 13134 13135 13136 13137 13138 13139 13140 13141 13142 13143 13144 13145 13146 13147 13148 13149 13150 13151 13152 13153 13154 13155 13156 13157 13158 13159 13160 13161 13162 13163 13164 13165 13166 13167 13168 13169 13170 13171 13172 13173 13174 13175 13176 13177 13178 13179 13180 13181 13182 13183 13184 13185 13186 13187 13188 13189 13190 13191 13192 13193 13194 13195 13196 13197 13198 13199 13200 13201 13202 13203 13204 13205 13206 13207 13208 13209 13210 13211 13212 13213 13214 13215 13216 13217 13218 13219 13220 13221 13222 13223 13224 13225 13226 13227 13228 13229 13230 13231 13232 13233 13234 13235 13236 13237 13238 13239 13240 13241 13242 13243 13244 13245 13246 13247 13248 13249 13250 13251 13252 13253 13254 13255 13256 13257 13258 13259 13260 13261 13262 13263 13264 13265 13266 13267 13268 13269 13270 13271 13272 13273 13274 13275 13276 13277 13278 13279 13280 13281 13282 13283 13284 13285 13286 13287 13288 13289 13290 13291 13292 13293 13294 13295 13296 13297 13298 13299 13300 13301 13302 13303 13304 13305 13306 13307 13308 13309 13310 13311 13312 13313 13314 13315 13316 13317 13318 13319 13320 13321 13322 13323 13324 13325 13326 13327 13328 13329 13330 13331 13332 13333 13334 13335 13336 13337 13338 13339 13340 13341 13342 13343 13344 13345 13346 13347 13348 13349 13350 13351 13352 13353 13354 13355 13356 13357 13358 13359 13360 13361 13362 13363 13364 13365 13366 13367 13368 13369 13370 13371 13372 13373 13374 13375 13376 13377 13378 13379 13380 13381 13382 13383 13384 13385 13386 13387 13388 13389 13390 13391 13392 13393 13394 13395 13396 13397 13398 13399 13400 13401 13402 13403 13404 13405 13406 13407 13408 13409 13410 13411 13412 13413 13414 13415 13416 13417 13418 13419 13420 13421 13422 13423 13424 13425 13426 13427 13428 13429 13430 13431 13432 13433 13434 13435 13436 13437 13438 13439 13440 13441 13442 13443 13444 13445 13446 13447 13448 13449 13450 13451 13452 13453 13454 13455 13456 13457 13458 13459 13460 13461 13462 13463 13464 13465 13466 13467 13468 13469 13470 13471 13472 13473 13474 13475 13476 13477 13478 13479 13480 13481 13482 13483 13484 13485 13486 13487 13488 13489 13490 13491 13492 13493 13494 13495 13496 13497 13498 13499 13500 13501 13502 13503 13504 13505 13506 13507 13508 13509 13510 13511 13512 13513 13514 13515 13516 13517 13518 13519 13520 13521 13522 13523 13524 13525 13526 13527 13528 13529 13530 13531 13532 13533 13534 13535 13536 13537 13538 13539 13540 13541 13542 13543 13544 13545 13546 13547 13548 13549 13550 13551 13552 13553 13554 13555 13556 13557 13558 13559 13560 13561 13562 13563 13564 13565 13566 13567 13568 13569 13570 13571 13572 13573 13574 13575 13576 13577 13578 13579 13580 13581 13582 13583 13584 13585 13586 13587 13588 13589 13590 13591 13592 13593 13594 13595 13596 13597 13598 13599 13600 13601 13602 13603 13604 13605 13606 13607 13608 13609 13610 13611 13612 13613 13614 13615 13616 13617 13618 13619 13620 13621 13622 13623 13624 13625 13626 13627 13628 13629 13630 13631 13632 13633 13634 13635 13636 13637 13638 13639 13640 13641 13642 13643 13644 13645 13646 13647 13648 13649 13650 13651 13652 13653 13654 13655 13656 13657 13658 13659 13660 13661 13662 13663 13664 13665 13666 13667 13668 13669 13670 13671 13672 13673 13674 13675 13676 13677 13678 13679 13680 13681 13682 13683 13684 13685 13686 13687 13688 13689 13690 13691 13692 13693 13694 13695 13696 13697 13698 13699 13700 13701 13702 13703 13704 13705 13706 13707 13708 13709 13710 13711 13712 13713 13714 13715 13716 13717 13718 13719 13720 13721 13722 13723 13724 13725 13726 13727 13728 13729 13730 13731 13732 13733 13734 13735 13736 13737 13738 13739 13740 13741 13742 13743 13744 13745 13746 13747 13748 13749 13750 13751 13752 13753 13754 13755 13756 13757 13758 13759 13760 13761 13762 13763 13764 13765 13766 13767 13768 13769 13770 13771 13772 13773 13774 13775 13776 13777 13778 13779 13780 13781 13782 13783 13784 13785 13786 13787 13788 13789 13790 13791 13792 13793 13794 13795 13796 13797 13798 13799 13800 13801 13802 13803 13804 13805 13806 13807 13808 13809 13810 13811 13812 13813 13814 13815 13816 13817 13818 13819 13820 13821 13822 13823 13824 13825 13826 13827 13828 13829 13830 13831 13832 13833 13834 13835 13836 13837 13838 13839 13840 13841 13842 13843 13844 13845 13846 13847 13848 13849 13850 13851 13852 13853 13854 13855 13856 13857 13858 13859 13860 13861 13862 13863 13864 13865 13866 13867 13868 13869 13870 13871 13872 13873 13874 13875 13876 13877 13878 13879 13880 13881 13882 13883 13884 13885 13886 13887 13888 13889 13890 13891 13892 13893 13894 13895 13896 13897 13898 13899 13900 13901 13902 13903 13904 13905 13906 13907 13908 13909 13910 13911 13912 13913 13914 13915 13916 13917 13918 13919 13920 13921 13922 13923 13924 13925 13926 13927 13928 13929 13930 13931 13932 13933 13934 13935 13936 13937 13938 13939 13940 13941 13942 13943 13944 13945 13946 13947 13948 13949 13950 13951 13952 13953 13954 13955 13956 13957 13958 13959 13960 13961 13962 13963 13964 13965 13966 13967 13968 13969 13970 13971 13972 13973 13974 13975 13976 13977 13978 13979 13980 13981 13982 13983 13984 13985 13986 13987 13988 13989 13990 13991 13992 13993 13994 13995 13996 13997 13998 13999 14000 14001 14002 14003 14004 14005 14006 14007 14008 14009 14010 14011 14012 14013 14014 14015 14016 14017 14018 14019 14020 14021 14022 14023 14024 14025 14026 14027 14028 14029 14030 14031 14032 14033 14034 14035 14036 14037 14038 14039 14040 14041 14042 14043 14044 14045 14046 14047 14048 14049 14050 14051 14052 14053 14054 14055 14056 14057 14058 14059 14060 14061 14062 14063 14064 14065 14066 14067 14068 14069 14070 14071 14072 14073 14074 14075 14076 14077 14078 14079 14080 14081 14082 14083 14084 14085 14086 14087 14088 14089 14090 14091 14092 14093 14094 14095 14096 14097 14098 14099 14100 14101 14102 14103 14104 14105 14106 14107 14108 14109 14110 14111 14112 14113 14114 14115 14116 14117 14118 14119 14120 14121 14122 14123 14124 14125 14126 14127 14128 14129 14130 14131 14132 14133 14134 14135 14136 14137 14138 14139 14140 14141 14142 14143 14144 14145 14146 14147 14148 14149 14150 14151 14152 14153 14154 14155 14156 14157 14158 14159 14160 14161 14162 14163 14164 14165 14166 14167 14168 14169 14170 14171 14172 14173 14174 14175 14176 14177 14178 14179 14180 14181 14182 14183 14184 14185 14186 14187 14188 14189 14190 14191 14192 14193 14194 14195 14196 14197 14198 14199 14200 14201 14202 14203 14204 14205 14206 14207 14208 14209 14210 14211 14212 14213 14214 14215 14216 14217 14218 14219 14220 14221 14222 14223 14224 14225 14226 14227 14228 14229 14230 14231 14232 14233 14234 14235 14236 14237 14238 14239 14240 14241 14242 14243 14244 14245 14246 14247 14248 14249 14250 14251 14252 14253 14254 14255 14256 14257 14258 14259 14260 14261 14262 14263 14264 14265 14266 14267 14268 14269 14270 14271 14272 14273 14274 14275 14276 14277 14278 14279 14280 14281 14282 14283 14284 14285 14286 14287 14288 14289 14290 14291 14292 14293 14294 14295 14296 14297 14298 14299 14300 14301 14302 14303 14304 14305 14306 14307 14308 14309 14310 14311 14312 14313 14314 14315 14316 14317 14318 14319 14320 14321 14322 14323 14324 14325 14326 14327 14328 14329 14330 14331 14332 14333 14334 14335 14336 14337 14338 14339 14340 14341 14342 14343 14344 14345 14346 14347 14348 14349 14350 14351 14352 14353 14354 14355 14356 14357 14358 14359 14360 14361 14362 14363 14364 14365 14366 14367 14368 14369 14370 14371 14372 14373 14374 14375 14376 14377 14378 14379 14380 14381 14382 14383 14384 14385 14386 14387 14388 14389 14390 14391 14392 14393 14394 14395 14396 14397 14398 14399 14400 14401 14402 14403 14404 14405 14406 14407 14408 14409 14410 14411 14412 14413 14414 14415 14416 14417 14418 14419 14420 14421 14422 14423 14424 14425 14426 14427 14428 14429 14430 14431 14432 14433 14434 14435 14436 14437 14438 14439 14440 14441 14442 14443 14444 14445 14446 14447 14448 14449 14450 14451 14452 14453 14454 14455 14456 14457 14458 14459 14460 14461 14462 14463 14464 14465 14466 14467 14468 14469 14470 14471 14472 14473 14474 14475 14476 14477 14478 14479 14480 14481 14482 14483 14484 14485 14486 14487 14488 14489 14490 14491 14492 14493 14494 14495 14496 14497 14498 14499 14500 14501 14502 14503 14504 14505 14506 14507 14508 14509 14510 14511 14512 14513 14514 14515 14516 14517 14518 14519 14520 14521 14522 14523 14524 14525 14526 14527 14528 14529 14530 14531 14532 14533 14534 14535 14536 14537 14538 14539 14540 14541 14542 14543 14544 14545 14546 14547 14548 14549 14550 14551 14552 14553 14554 14555 14556 14557 14558 14559 14560 14561 14562 14563 14564 14565 14566 14567 14568 14569 14570 14571 14572 14573 14574 14575 14576 14577 14578 14579 14580 14581 14582 14583 14584 14585 14586 14587 14588 14589 14590 14591 14592 14593 14594 14595 14596 14597 14598 14599 14600 14601 14602 14603 14604 14605 14606 14607 14608 14609 14610 14611 14612 14613 14614 14615 14616 14617 14618 14619 14620 14621 14622 14623 14624 14625 14626 14627 14628 14629 14630 14631 14632 14633 14634 14635 14636 14637 14638 14639 14640 14641 14642 14643 14644 14645 14646 14647 14648 14649 14650 14651 14652 14653 14654 14655 14656 14657 14658 14659 14660 14661 14662 14663 14664 14665 14666 14667 14668 14669 14670 14671 14672 14673 14674 14675 14676 14677 14678 14679 14680 14681 14682 14683 14684 14685 14686 14687 14688 14689 14690 14691 14692 14693 14694 14695 14696 14697 14698 14699 14700 14701 14702 14703 14704 14705 14706 14707 14708 14709 14710 14711 14712 14713 14714 14715 14716 14717 14718 14719 14720 14721 14722 14723 14724 14725 14726 14727 14728 14729 14730 14731 14732 14733 14734 14735 14736 14737 14738 14739 14740 14741 14742 14743 14744 14745 14746 14747 14748 14749 14750 14751 14752 14753 14754 14755 14756 14757 14758 14759 14760 14761 14762 14763 14764 14765 14766 14767 14768 14769 14770 14771 14772 14773 14774 14775 14776 14777 14778 14779 14780 14781 14782 14783 14784 14785 14786 14787 14788 14789 14790 14791 14792 14793 14794 14795 14796 14797 14798 14799 14800 14801 14802 14803 14804 14805 14806 14807 14808 14809 14810 14811 14812 14813 14814 14815 14816 14817 14818 14819 14820 14821 14822 14823 14824 14825 14826 14827 14828 14829 14830 14831 14832 14833 14834 14835 14836 14837 14838 14839 14840 14841 14842 14843 14844 14845 14846 14847 14848 14849 14850 14851 14852 14853 14854 14855 14856 14857 14858 14859 14860 14861 14862 14863 14864 14865 14866 14867 14868 14869 14870 14871 14872 14873 14874 14875 14876 14877 14878 14879 14880 14881 14882 14883 14884 14885 14886 14887 14888 14889 14890 14891 14892 14893 14894 14895 14896 14897 14898 14899 14900 14901 14902 14903 14904 14905 14906 14907 14908 14909 14910 14911 14912 14913 14914 14915 14916 14917 14918 14919 14920 14921 14922 14923 14924 14925 14926 14927 14928 14929 14930 14931 14932 14933 14934 14935 14936 14937 14938 14939 14940 14941 14942 14943 14944 14945 14946 14947 14948 14949 14950 14951 14952 14953 14954 14955 14956 14957 14958 14959 14960 14961 14962 14963 14964 14965 14966 14967 14968 14969 14970 14971 14972 14973 14974 14975 14976 14977 14978 14979 14980 14981 14982 14983 14984 14985 14986 14987 14988 14989 14990 14991 14992 14993 14994 14995 14996 14997 14998 14999 15000 15001 15002 15003 15004 15005 15006 15007 15008 15009 15010 15011 15012 15013 15014 15015 15016 15017 15018 15019 15020 15021 15022 15023 15024 15025 15026 15027 15028 15029 15030 15031 15032 15033 15034 15035 15036 15037 15038 15039 15040 15041 15042 15043 15044 15045 15046 15047 15048 15049 15050 15051 15052 15053 15054 15055 15056 15057 15058 15059 15060 15061 15062 15063 15064 15065 15066 15067 15068 15069 15070 15071 15072 15073 15074 15075 15076 15077 15078 15079 15080 15081 15082 15083 15084 15085 15086 15087 15088 15089 15090 15091 15092 15093 15094 15095 15096 15097 15098 15099 15100 15101 15102 15103 15104 15105 15106 15107 15108 15109 15110 15111 15112 15113 15114 15115 15116 15117 15118 15119 15120 15121 15122 15123 15124 15125 15126 15127 15128 15129 15130 15131 15132 15133 15134 15135 15136 15137 15138 15139 15140 15141 15142 15143 15144 15145 15146 15147 15148 15149 15150 15151 15152 15153 15154 15155 15156 15157 15158 15159 15160 15161 15162 15163 15164 15165 15166 15167 15168 15169 15170 15171 15172 15173 15174 15175 15176 15177 15178 15179 15180 15181 15182 15183 15184 15185 15186 15187 15188 15189 15190 15191 15192 15193 15194 15195 15196 15197 15198 15199 15200 15201 15202 15203 15204 15205 15206 15207 15208 15209 15210 15211 15212 15213
|
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <cstdint>
#include <optional>
#include <tuple>
#include "base/barrier_closure.h"
#include "base/base_switches.h"
#include "base/command_line.h"
#include "base/containers/flat_map.h"
#include "base/containers/flat_set.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/functional/callback_forward.h"
#include "base/functional/callback_helpers.h"
#include "base/memory/memory_pressure_monitor.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/metrics/metrics_hashes.h"
#include "base/run_loop.h"
#include "base/scoped_observation.h"
#include "base/strings/escape.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/synchronization/lock.h"
#include "base/task/single_thread_task_runner.h"
#include "base/test/bind.h"
#include "base/test/gtest_util.h"
#include "base/test/run_until.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/test_mock_time_task_runner.h"
#include "base/test/test_timeouts.h"
#include "base/thread_annotations.h"
#include "base/values.h"
#include "build/build_config.h"
#include "cc/base/features.h"
#include "components/input/render_widget_host_input_event_router.h"
#include "components/services/storage/public/mojom/storage_service.mojom.h"
#include "components/services/storage/public/mojom/test_api.test-mojom.h"
#include "components/ukm/test_ukm_recorder.h"
#include "content/browser/back_forward_cache_test_util.h"
#include "content/browser/preloading/prefetch/prefetch_features.h"
#include "content/browser/preloading/prefetch/prefetch_service.h"
#include "content/browser/preloading/prefetch/prefetch_test_util_internal.h"
#include "content/browser/preloading/preloading.h"
#include "content/browser/preloading/preloading_attempt_impl.h"
#include "content/browser/preloading/preloading_data_impl.h"
#include "content/browser/preloading/preloading_decider.h"
#include "content/browser/preloading/prerender/prerender_features.h"
#include "content/browser/preloading/prerender/prerender_final_status.h"
#include "content/browser/preloading/prerender/prerender_host.h"
#include "content/browser/preloading/prerender/prerender_host_registry.h"
#include "content/browser/preloading/prerender/prerender_metrics.h"
#include "content/browser/preloading/prerender/prerender_no_vary_search_hint_commit_deferring_condition.h"
#include "content/browser/renderer_host/back_forward_cache_impl.h"
#include "content/browser/renderer_host/frame_tree_node.h"
#include "content/browser/renderer_host/navigation_request.h"
#include "content/browser/renderer_host/navigation_type.h"
#include "content/browser/renderer_host/render_frame_host_impl.h"
#include "content/browser/renderer_host/render_process_host_impl.h"
#include "content/browser/storage_partition_impl.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/common/content_navigation_policy.h"
#include "content/common/features.h"
#include "content/common/input/synthetic_tap_gesture.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/disallow_activation_reason.h"
#include "content/public/browser/document_user_data.h"
#include "content/public/browser/global_routing_id.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/prerender_web_contents_delegate.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/isolated_world_ids.h"
#include "content/public/test/back_forward_cache_util.h"
#include "content/public/test/background_color_change_waiter.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/browsing_data_remover_test_util.h"
#include "content/public/test/content_browser_test.h"
#include "content/public/test/content_browser_test_content_browser_client.h"
#include "content/public/test/content_browser_test_utils.h"
#include "content/public/test/file_system_chooser_test_helpers.h"
#include "content/public/test/mock_client_hints_controller_delegate.h"
#include "content/public/test/mock_web_contents_observer.h"
#include "content/public/test/mojo_capability_control_test_interfaces.mojom.h"
#include "content/public/test/mojo_capability_control_test_util.h"
#include "content/public/test/navigation_handle_observer.h"
#include "content/public/test/no_renderer_crashes_assertion.h"
#include "content/public/test/prefetch_test_util.h"
#include "content/public/test/preloading_test_util.h"
#include "content/public/test/prerender_test_util.h"
#include "content/public/test/scoped_accessibility_mode_override.h"
#include "content/public/test/test_navigation_observer.h"
#include "content/public/test/test_navigation_throttle.h"
#include "content/public/test/test_utils.h"
#include "content/public/test/theme_change_waiter.h"
#include "content/public/test/url_loader_interceptor.h"
#include "content/shell/browser/shell.h"
#include "content/shell/browser/shell_browser_context.h"
#include "content/test/content_browser_test_utils_internal.h"
#include "content/test/mock_commit_deferring_condition.h"
#include "content/test/render_document_feature.h"
#include "mojo/public/cpp/bindings/receiver_set.h"
#include "mojo/public/cpp/bindings/remote_set.h"
#include "mojo/public/cpp/system/functions.h"
#include "net/dns/mock_host_resolver.h"
#include "net/test/embedded_test_server/controllable_http_response.h"
#include "net/test/embedded_test_server/default_handlers.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "net/test/embedded_test_server/http_request.h"
#include "net/test/embedded_test_server/http_response.h"
#include "net/test/embedded_test_server/request_handler_util.h"
#include "services/metrics/public/cpp/metrics_utils.h"
#include "services/metrics/public/cpp/ukm_builders.h"
#include "services/network/public/cpp/web_sandbox_flags.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "third_party/blink/public/common/features.h"
#include "third_party/blink/public/common/loader/loader_constants.h"
#include "third_party/blink/public/common/navigation/preloading_headers.h"
#include "third_party/blink/public/mojom/browser_interface_broker.mojom.h"
#include "third_party/blink/public/mojom/frame/fullscreen.mojom.h"
#include "third_party/blink/public/mojom/page/display_cutout.mojom.h"
#include "ui/color/color_id.h"
#include "ui/events/base_event_utils.h"
#include "ui/shell_dialogs/select_file_dialog.h"
#include "ui/shell_dialogs/select_file_dialog_factory.h"
#include "url/gurl.h"
#include "url/url_constants.h"
#if BUILDFLAG(ENABLE_PLUGINS)
#include "content/common/pepper_plugin.mojom.h"
#endif // BUILDFLAG(ENABLE_PLUGINS)
using ::testing::Exactly;
namespace content {
namespace {
enum class BackForwardCacheType {
kDisabled,
kEnabled,
};
constexpr char kPagehideEventPath[] = "/pagehideFired";
std::string ToString(const testing::TestParamInfo<BackForwardCacheType>& info) {
switch (info.param) {
case BackForwardCacheType::kDisabled:
return "Disabled";
case BackForwardCacheType::kEnabled:
return "Enabled";
}
}
int32_t InterfaceNameHasher(const std::string& interface_name) {
return static_cast<int32_t>(base::HashMetricNameAs32Bits(interface_name));
}
RenderFrameHost* FindRenderFrameHost(Page& page, const GURL& url) {
return FrameMatchingPredicate(page,
base::BindRepeating(&FrameHasSourceUrl, url));
}
ukm::SourceId ToSourceId(int64_t navigation_id) {
return ukm::ConvertToSourceId(navigation_id,
ukm::SourceIdType::NAVIGATION_ID);
}
// A fake implementation of base::MemoryPressureMonitor. An instance of this
// class is used via a global variable. The base class sets itself in the
// global variable on the constructor and unsets it on the destructor.
// base::MemoryPressureMonitor::Get() provides access to the instance.
class FakeMemoryPressureMonitor : public base::MemoryPressureMonitor {
public:
FakeMemoryPressureMonitor(MemoryPressureLevel level) : level_(level) {}
MemoryPressureLevel GetCurrentPressureLevel() const override {
return level_;
}
private:
const MemoryPressureLevel level_ =
MemoryPressureLevel::MEMORY_PRESSURE_LEVEL_NONE;
};
// Example class which inherits the DocumentUserData, all the data is
// associated to the lifetime of the document.
class DocumentData : public DocumentUserData<DocumentData> {
public:
~DocumentData() override = default;
base::WeakPtr<DocumentData> GetWeakPtr() {
return weak_ptr_factory_.GetWeakPtr();
}
private:
explicit DocumentData(RenderFrameHost* render_frame_host)
: DocumentUserData<DocumentData>(render_frame_host) {}
friend class DocumentUserData<DocumentData>;
base::WeakPtrFactory<DocumentData> weak_ptr_factory_{this};
DOCUMENT_USER_DATA_KEY_DECL();
};
DOCUMENT_USER_DATA_KEY_IMPL(DocumentData);
using UkmEntry = ukm::TestUkmRecorder::HumanReadableUkmEntry;
using ukm::builders::Preloading_Attempt;
using ukm::builders::Preloading_Attempt_PreviousPrimaryPage;
using ukm::builders::Preloading_Prediction;
using ukm::builders::Preloading_Prediction_PreviousPrimaryPage;
static const auto kMockElapsedTime =
base::ScopedMockElapsedTimersForTest::kMockElapsedTime;
// Utility class to make building expected
// TestUkmRecorder::HumanReadableUkmEntry for EXPECT_EQ for
// PreloadingAttemptPreviousPrimaryPage.
class PreloadingAttemptPreviousPrimaryPageUkmEntryBuilder {
public:
explicit PreloadingAttemptPreviousPrimaryPageUkmEntryBuilder(
PreloadingPredictor predictor)
: predictor_(predictor) {}
// Unlike PreloadingAttemptUkmEntryBuilder, this method assumes a navigation
// has not occurred thus `TimeToNextNavigation` is not set.
//
// Optional `ready_time` should be set by the caller, if this attempt ever
// reaches `PreloadingTriggeringOutcome::kReady` state, at the time of
// reporting. Install `base::ScopedMockElapsedTimersForTest` into the test
// fixture to assert the entry's latency values' correctness.
ukm::TestUkmRecorder::HumanReadableUkmEntry BuildEntry(
ukm::SourceId source_id,
PreloadingType preloading_type,
PreloadingEligibility eligibility,
PreloadingHoldbackStatus holdback_status,
PreloadingTriggeringOutcome triggering_outcome,
PreloadingFailureReason failure_reason,
bool accurate,
std::optional<base::TimeDelta> ready_time = std::nullopt,
std::optional<blink::mojom::SpeculationEagerness> eagerness =
std::nullopt) const {
std::map<std::string, int64_t> metrics = {
{Preloading_Attempt::kPreloadingTypeName,
static_cast<int64_t>(preloading_type)},
{Preloading_Attempt::kPreloadingPredictorName, predictor_.ukm_value()},
{Preloading_Attempt::kEligibilityName,
static_cast<int64_t>(eligibility)},
{Preloading_Attempt::kHoldbackStatusName,
static_cast<int64_t>(holdback_status)},
{Preloading_Attempt::kTriggeringOutcomeName,
static_cast<int64_t>(triggering_outcome)},
{Preloading_Attempt::kFailureReasonName,
static_cast<int64_t>(failure_reason)},
{Preloading_Attempt::kAccurateTriggeringName, accurate ? 1 : 0}};
if (ready_time) {
metrics.insert({Preloading_Attempt::kReadyTimeName,
ukm::GetExponentialBucketMinForCounts1000(
ready_time->InMilliseconds())});
}
if (eagerness) {
metrics.insert({Preloading_Attempt::kSpeculationEagernessName,
static_cast<int64_t>(eagerness.value())});
}
return UkmEntry{source_id, std::move(metrics)};
}
private:
PreloadingPredictor predictor_;
};
// Utility class to make building expected
// TestUkmRecorder::HumanReadableUkmEntry for EXPECT_EQ for
// PreloadingPredictionPreviousPrimaryPage.
class PreloadingPredictionPreviousPrimaryPageUkmEntryBuilder {
public:
explicit PreloadingPredictionPreviousPrimaryPageUkmEntryBuilder(
PreloadingPredictor predictor)
: predictor_(predictor) {}
// Unlike PreloadingPredictionUkmEntryBuilder, this method assumes a
// navigation has not occurred thus `TimeToNextNavigation` is not set.
ukm::TestUkmRecorder::HumanReadableUkmEntry
BuildEntry(ukm::SourceId source_id, int confidence, bool accurate) const {
std::map<std::string, int64_t> metrics = {
{Preloading_Prediction::kConfidenceName,
static_cast<int64_t>(confidence)},
{Preloading_Attempt::kPreloadingPredictorName,
static_cast<int64_t>(predictor_.ukm_value())},
{Preloading_Prediction::kAccuratePredictionName, accurate ? 1 : 0}};
return UkmEntry{source_id, std::move(metrics)};
}
private:
PreloadingPredictor predictor_;
};
// Tests the params of WebContentsImpl that contains a prerendered page for a
// new tab navigation.
void ExpectWebContentsIsForNewTabPrerendering(WebContents& web_contents) {
auto& web_contents_impl = static_cast<WebContentsImpl&>(web_contents);
// The primary page shows the initial blank page.
EXPECT_TRUE(web_contents_impl.GetLastCommittedURL().is_empty());
// The prerendering WebContents should not have an opener to avoid cross-page
// scripting during prerendering.
EXPECT_FALSE(web_contents_impl.HasOpener());
// The prerendering WebContents should be hidden until prerender activation.
EXPECT_TRUE(web_contents_impl.IsHidden());
}
// This is a fake implementation of WebContentsDelegate that allows
// prerendering.
class FakeWebContentsDelegate : public WebContentsDelegate {
public:
// WebContentsDelegate overrides.
PreloadingEligibility IsPrerender2Supported(
WebContents& web_contents,
PreloadingTriggerType trigger_type) override {
return PreloadingEligibility::kEligible;
}
};
class PrerenderBrowserTest : public ContentBrowserTest,
public WebContentsObserver {
public:
using LifecycleStateImpl = RenderFrameHostImpl::LifecycleStateImpl;
enum class OriginType {
kSameOrigin,
kSameSiteCrossOrigin,
kCrossSite,
};
PrerenderBrowserTest() {
prerender_helper_ = std::make_unique<test::PrerenderTestHelper>(
base::BindRepeating(&PrerenderBrowserTest::web_contents,
base::Unretained(this)),
/*force_disable_prerender2_fallback*/ true,
/*force_enable_prerender2innewtab*/ false);
// Input suppression during paintholding interferes with the input event
// dispatches to top frames. Disabling kDropInputEventsWhilePaintHolding
// because the tests here are not about top frame paintholding.
feature_list_.InitWithFeatures(
{::features::kSuppressesPrerenderingOnSlowNetwork,
blink::features::kFetchLaterAPI},
{blink::features::kDropInputEventsWhilePaintHolding});
}
~PrerenderBrowserTest() override = default;
void SetUp() override {
ssl_server_.RegisterRequestHandler(
base::BindRepeating(&net::test_server::HandlePrefixedRequest,
"/server-redirect-credentialed-prerender",
base::BindRepeating(HandleCredentialedRequest)));
prerender_helper_->RegisterServerRequestMonitor(&ssl_server_);
ContentBrowserTest::SetUp();
}
void SetUpOnMainThread() override {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
host_resolver()->AddRule("*", "127.0.0.1");
attempt_ukm_entry_builder_ =
std::make_unique<test::PreloadingAttemptUkmEntryBuilder>(
PredictorToExpectInUkm());
attempt_previous_ukm_entry_builder_ =
std::make_unique<PreloadingAttemptPreviousPrimaryPageUkmEntryBuilder>(
PredictorToExpectInUkm());
prediction_ukm_entry_builder_ =
std::make_unique<test::PreloadingPredictionUkmEntryBuilder>(
PredictorToExpectInUkm());
prediction_previous_ukm_entry_builder_ = std::make_unique<
PreloadingPredictionPreviousPrimaryPageUkmEntryBuilder>(
PredictorToExpectInUkm());
ssl_server_.AddDefaultHandlers(GetTestDataFilePath());
ssl_server_.SetSSLConfig(
net::test_server::EmbeddedTestServer::CERT_TEST_NAMES);
pagehide_event_receiver_ =
std::make_unique<net::test_server::ControllableHttpResponse>(
&ssl_server_, kPagehideEventPath);
ASSERT_TRUE(ssl_server_.Start());
WebContentsObserver::Observe(shell()->web_contents());
ukm_recorder_ = std::make_unique<ukm::TestAutoSetUkmRecorder>();
}
void TearDownOnMainThread() override {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
EXPECT_TRUE(ssl_server_.ShutdownAndWaitUntilComplete());
}
static std::unique_ptr<net::test_server::HttpResponse>
HandleCredentialedRequest(const net::test_server::HttpRequest& request) {
GURL request_url = request.GetURL();
std::string dest =
base::UnescapeBinaryURLComponent(request_url.query_piece());
auto http_response =
std::make_unique<net::test_server::BasicHttpResponse>();
http_response->set_code(net::HTTP_FOUND);
http_response->AddCustomHeader("Location", dest);
http_response->AddCustomHeader("Access-Control-Allow-Origin", "*");
http_response->AddCustomHeader("Supports-Loading-Mode",
"credentialed-prerender");
http_response->set_content_type("text/html");
http_response->set_content(base::StringPrintf(
"<!doctype html><p>Redirecting to %s", dest.c_str()));
return http_response;
}
// Waits until the request count for `url` reaches `count`.
void WaitForRequest(const GURL& url, int count) {
prerender_helper_->WaitForRequest(url, count);
}
FrameTreeNodeId AddPrerender(const GURL& prerendering_url,
int32_t world_id = ISOLATED_WORLD_ID_GLOBAL) {
return prerender_helper_->AddPrerender(prerendering_url, world_id);
}
FrameTreeNodeId AddPrerenderWithTags(const GURL& prerendering_url,
std::optional<std::string> tag) {
return prerender_helper_->AddPrerender(
prerendering_url, /*eagerness=*/std::nullopt,
/*no_vary_search_hint=*/std::string(),
/*target_hint=*/std::string(), tag);
}
FrameTreeNodeId AddPrerender(const GURL& prerendering_url,
std::string no_vary_search_hint,
int32_t world_id = ISOLATED_WORLD_ID_GLOBAL) {
return prerender_helper_->AddPrerender(
prerendering_url, /*eagerness=*/std::nullopt, no_vary_search_hint,
/*target_hint=*/std::string(), /*ruleset_tag=*/std::nullopt, world_id);
}
void AddPrerenderAsync(const GURL& prerendering_url) {
prerender_helper_->AddPrerenderAsync(prerendering_url);
}
void AddPrerenderAsync(const GURL& prerendering_url,
std::string no_vary_search_hint) {
prerender_helper_->AddPrerendersAsync({prerendering_url},
/*eagerness=*/std::nullopt,
no_vary_search_hint,
/*target_hint=*/std::string());
}
void AddPrefetchAsync(const GURL& prefetch_url) {
prerender_helper_->AddPrefetchAsync(prefetch_url);
}
void AddPrerendersAsync(const std::vector<GURL>& prerendering_urls) {
prerender_helper_->AddPrerendersAsync(prerendering_urls,
/*eagerness=*/std::nullopt,
/*target_hint=*/std::string());
}
void AddPrerendersAsync(
const std::vector<GURL>& prerendering_urls,
std::optional<blink::mojom::SpeculationEagerness> eagerness,
const std::string& target_hint) {
prerender_helper_->AddPrerendersAsync(prerendering_urls, eagerness,
target_hint);
}
void AddPrerenderWithEagernessAsync(
const GURL& prerendering_url,
blink::mojom::SpeculationEagerness eagerness) {
prerender_helper_->AddPrerendersAsync({prerendering_url}, eagerness,
/*target_hint=*/std::string());
}
std::unique_ptr<PrerenderHandle> AddEmbedderTriggeredPrerender(
const GURL& prerendering_url,
PreloadingAttempt* preloading_attempt = nullptr,
bool should_warm_up_compositor = false) {
std::unique_ptr<PrerenderHandle> handle =
AddEmbedderTriggeredPrerenderAsync(prerendering_url, preloading_attempt,
should_warm_up_compositor);
EXPECT_TRUE(handle);
test::PrerenderTestHelper::WaitForPrerenderLoadCompletion(*web_contents(),
prerendering_url);
return handle;
}
std::unique_ptr<PrerenderHandle> AddEmbedderTriggeredPrerenderAsync(
const GURL& prerendering_url,
PreloadingAttempt* preloading_attempt = nullptr,
bool should_warm_up_compositor = false) {
return web_contents_impl()->StartPrerendering(
prerendering_url, PreloadingTriggerType::kEmbedder,
"EmbedderSuffixForTest",
/*additional_headers=*/net::HttpRequestHeaders(),
/*no_vary_search_hint=*/std::nullopt,
ui::PageTransitionFromInt(ui::PAGE_TRANSITION_TYPED |
ui::PAGE_TRANSITION_FROM_ADDRESS_BAR),
should_warm_up_compositor, /*should_prepare_paint_tree=*/true,
PreloadingHoldbackStatus::kUnspecified,
PreloadPipelineInfo::Create(
/*planned_max_preloading_type=*/PreloadingType::kPrerender),
preloading_attempt,
/*url_match_predicate=*/{},
/*prerender_navigation_handle_callback=*/{});
}
bool AddTestUtilJS(RenderFrameHost* host) {
std::string js = R"(
const script = document.createElement("script");
new Promise(resolve => {
script.addEventListener('load', () => {
resolve(true);
});
script.addEventListener('error', () => {
resolve(false);
});
script.src = "/prerender/test_utils.js";
document.body.appendChild(script);
});
)";
return EvalJs(host, js).ExtractBool();
}
void NavigatePrimaryPage(const GURL& url) {
prerender_helper_->NavigatePrimaryPage(url);
}
void NavigatePrimaryPageFromAddressBar(const GURL& url) {
prerender_helper_->NavigatePrimaryPageAsync(
url, ui::PageTransitionFromInt(ui::PAGE_TRANSITION_TYPED |
ui::PAGE_TRANSITION_FROM_ADDRESS_BAR));
}
FrameTreeNodeId GetHostForUrl(const GURL& url) {
return prerender_helper_->GetHostForUrl(url);
}
RenderFrameHostImpl* GetPrerenderedMainFrameHost(FrameTreeNodeId host_id) {
return static_cast<RenderFrameHostImpl*>(
prerender_helper_->GetPrerenderedMainFrameHost(host_id));
}
void NavigatePrerenderedPage(FrameTreeNodeId host_id, const GURL& url) {
return prerender_helper_->NavigatePrerenderedPage(host_id, url);
}
void CancelPrerenderedPage(FrameTreeNodeId host_id) {
return prerender_helper_->CancelPrerenderedPage(host_id);
}
bool HasHostForUrl(WebContents& web_contents, const GURL& url) {
FrameTreeNodeId host_id =
content::test::PrerenderTestHelper::GetHostForUrl(web_contents, url);
return !host_id.is_null();
}
bool HasHostForUrl(const GURL& url) {
FrameTreeNodeId host_id = GetHostForUrl(url);
return !host_id.is_null();
}
void WaitForPrerenderLoadCompletion(FrameTreeNodeId host_id) {
prerender_helper_->WaitForPrerenderLoadCompletion(host_id);
}
void WaitForPrerenderLoadCompletion(const GURL& url) {
prerender_helper_->WaitForPrerenderLoadCompletion(url);
}
GURL GetUrl(const std::string& path) const {
return ssl_server_.GetURL("a.test", path);
}
GURL GetSameSiteCrossOriginUrl(const std::string& path) {
return ssl_server().GetURL("b.a.test", path);
}
GURL GetCrossSiteUrl(const std::string& path) {
return ssl_server_.GetURL("b.test", path);
}
void ResetSSLConfig(
net::test_server::EmbeddedTestServer::ServerCertificate cert,
const net::SSLServerConfig& ssl_config) {
ASSERT_TRUE(ssl_server_.ResetSSLConfig(cert, ssl_config));
}
int GetRequestCount(const GURL& url) {
return prerender_helper_->GetRequestCount(url);
}
net::test_server::HttpRequest::HeaderMap GetRequestHeaders(const GURL& url) {
return prerender_helper_->GetRequestHeaders(url);
}
WebContents* web_contents() const { return shell()->web_contents(); }
WebContentsImpl* web_contents_impl() const {
return static_cast<WebContentsImpl*>(web_contents());
}
RenderFrameHostImpl* current_frame_host() {
return web_contents_impl()->GetPrimaryMainFrame();
}
ukm::TestAutoSetUkmRecorder* test_ukm_recorder() {
return ukm_recorder_.get();
}
ukm::SourceId PrimaryPageSourceId() {
return current_frame_host()->GetPageUkmSourceId();
}
const test::PreloadingAttemptUkmEntryBuilder& attempt_ukm_entry_builder() {
return *attempt_ukm_entry_builder_;
}
const PreloadingAttemptPreviousPrimaryPageUkmEntryBuilder&
attempt_previous_ukm_entry_builder() {
return *attempt_previous_ukm_entry_builder_;
}
const test::PreloadingPredictionUkmEntryBuilder&
prediction_ukm_entry_builder() {
return *prediction_ukm_entry_builder_;
}
const PreloadingPredictionPreviousPrimaryPageUkmEntryBuilder&
prediction_previous_ukm_entry_builder() {
return *prediction_previous_ukm_entry_builder_;
}
void ExpectPreloadingAttemptUkm(
const std::vector<UkmEntry>& expected_attempt_entries) {
test::ExpectPreloadingAttemptUkm(*test_ukm_recorder(),
expected_attempt_entries);
}
void ExpectPreloadingAttemptPreviousPrimaryPageUkm(
const UkmEntry& expected_attempt_entry) {
auto attempt_entries = test_ukm_recorder()->GetEntries(
Preloading_Attempt_PreviousPrimaryPage::kEntryName,
test::kPreloadingAttemptUkmMetrics);
ASSERT_EQ(attempt_entries.size(), 1u);
EXPECT_EQ(attempt_entries[0], expected_attempt_entry)
<< test::ActualVsExpectedUkmEntryToString(attempt_entries[0],
expected_attempt_entry);
}
void ExpectPreloadingPredictionUkm(
const std::vector<UkmEntry>& expected_prediction_entries) {
test::ExpectPreloadingPredictionUkm(*test_ukm_recorder(),
expected_prediction_entries);
}
void ExpectPreloadingPredictioPreviousPrimaryPageUkm(
const UkmEntry& expected_prediction_entry) {
auto prediction_entries = test_ukm_recorder()->GetEntries(
Preloading_Prediction_PreviousPrimaryPage::kEntryName,
test::kPreloadingPredictionUkmMetrics);
ASSERT_EQ(prediction_entries.size(), 1u);
EXPECT_EQ(prediction_entries[0], expected_prediction_entry)
<< test::ActualVsExpectedUkmEntryToString(prediction_entries[0],
expected_prediction_entry);
}
void TestHostPrerenderingState(const GURL& prerender_url) {
const GURL kInitialUrl = GetUrl("/empty.html");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// The initial page should not be in prerendered state.
RenderFrameHostImpl* initiator_render_frame_host = current_frame_host();
EXPECT_TRUE(initiator_render_frame_host->frame_tree()->is_primary());
EXPECT_EQ(initiator_render_frame_host->lifecycle_state(),
LifecycleStateImpl::kActive);
// Start a prerender.
AddPrerender(prerender_url);
EXPECT_TRUE(prerender_helper_->VerifyPrerenderingState(prerender_url));
// Activate the prerendered page.
NavigatePrimaryPage(prerender_url);
EXPECT_EQ(web_contents()->GetLastCommittedURL(), prerender_url);
// The activated page should no longer be in the prerendering state.
RenderFrameHostImpl* navigated_render_frame_host = current_frame_host();
// The new page shouldn't be in the prerendering state.
navigated_render_frame_host->ForEachRenderFrameHostImpl(
[](RenderFrameHostImpl* rfhi) {
// All the subframes should be transitioned to
// LifecycleStateImpl::kActive state after activation.
EXPECT_EQ(rfhi->lifecycle_state(),
RenderFrameHostImpl::LifecycleStateImpl::kActive);
EXPECT_FALSE(rfhi->frame_tree()->is_prerendering());
// Check that each document can use a deferred Mojo interface. Choose
// WebLocks API as the feature is enabled by default and does not
// require permission.
const std::string kMojoScript = R"(
navigator.locks.request('hi', {mode:'shared'}, () => {});
)";
EXPECT_TRUE(ExecJs(rfhi, kMojoScript));
});
}
void TestPrerenderAllowedOnIframeWithStatusCode(OriginType origin_type,
std::string status_code);
test::PrerenderTestHelper* prerender_helper() {
return prerender_helper_.get();
}
void SetUpCommandLine(base::CommandLine* command_line) override {
// The viewport meta tag is only enabled on Android.
#if BUILDFLAG(IS_ANDROID)
command_line->AppendSwitchASCII(switches::kEnableBlinkFeatures,
"DisplayCutoutAPI");
#endif
}
void TestNavigationHistory(const GURL& expected_current_url,
int expected_history_index,
int expected_history_length) {
ASSERT_EQ(expected_current_url, web_contents()->GetLastCommittedURL());
EXPECT_EQ(expected_history_index,
web_contents()->GetController().GetCurrentEntryIndex());
EXPECT_EQ(expected_history_length,
web_contents()->GetController().GetEntryCount());
EXPECT_EQ(expected_history_length,
EvalJs(web_contents(), "history.length"));
}
void AssertPrerenderHistoryLength(FrameTreeNodeId host_id,
RenderFrameHost* prerender_frame_host) {
EXPECT_EQ(1, FrameTreeNode::GloballyFindByID(host_id)
->frame_tree()
.controller()
.GetEntryCount());
ASSERT_EQ(1, EvalJs(prerender_frame_host, "history.length"));
}
void GoBack() {
web_contents()->GetController().GoBack();
EXPECT_TRUE(WaitForLoadStop(web_contents()));
}
void GoForward() {
web_contents()->GetController().GoForward();
EXPECT_TRUE(WaitForLoadStop(web_contents()));
}
void ExpectFinalStatus(const std::string& final_status_name,
PrerenderFinalStatus status) {
// Check FinalStatus in UMA.
histogram_tester().ExpectUniqueSample(final_status_name, status, 1);
// Check all entries in UKM to make sure that the recorded FinalStatus is
// equal to `status`. At least one entry should exist.
bool final_status_entry_found = false;
const auto entries = ukm_recorder_->GetEntriesByName(
ukm::builders::PrerenderPageLoad::kEntryName);
for (const ukm::mojom::UkmEntry* entry : entries) {
if (ukm_recorder_->EntryHasMetric(
entry, ukm::builders::PrerenderPageLoad::kFinalStatusName)) {
final_status_entry_found = true;
ukm_recorder_->ExpectEntryMetric(
entry, ukm::builders::PrerenderPageLoad::kFinalStatusName,
static_cast<int>(status));
}
}
EXPECT_TRUE(final_status_entry_found);
}
void ExpectFinalStatusForSpeculationRule(PrerenderFinalStatus status) {
ExpectFinalStatus(
"Prerender.Experimental.PrerenderHostFinalStatus.SpeculationRule",
status);
}
void ExpectFinalStatusForSpeculationRuleFromIsolatedWorld(
PrerenderFinalStatus status) {
ExpectFinalStatus(
"Prerender.Experimental.PrerenderHostFinalStatus."
"SpeculationRuleFromIsolatedWorld",
status);
}
void ExpectFinalStatusForSpeculationRuleFromAutoSpeculationRules(
PrerenderFinalStatus status) {
ExpectFinalStatus(
"Prerender.Experimental.PrerenderHostFinalStatus."
"SpeculationRuleFromAutoSpeculationRules",
status);
}
void ExpectFinalStatusForEmbedder(PrerenderFinalStatus status) {
// UKM can be recorded in an initiator page and an activated page. Embedder
// triggers don't have an initiator page, so UKM is not recorded anywhere
// when prerendering is canceled.
if (status != PrerenderFinalStatus::kActivated) {
return;
}
ExpectFinalStatus(
"Prerender.Experimental.PrerenderHostFinalStatus.Embedder_"
"EmbedderSuffixForTest",
status);
}
const base::HistogramTester& histogram_tester() { return histogram_tester_; }
std::string GetBodyTextContent() {
base::RunLoop loop;
base::Value result;
web_contents()->GetPrimaryMainFrame()->ExecuteJavaScriptForTests(
base::UTF8ToUTF16(std::string("document.body.textContent.trim()")),
base::BindOnce(
[](base::RunLoop* loop, base::Value* result, base::Value value) {
*result = std::move(value);
loop->QuitClosure().Run();
},
&loop, &result),
ISOLATED_WORLD_ID_GLOBAL);
loop.Run();
CHECK(result.is_string());
return result.GetString();
}
void WaitForPageHide() { pagehide_event_receiver_->WaitForRequest(); }
bool PageHideReceived() {
return pagehide_event_receiver_->has_received_request();
}
// Stores all the navigation_ids for all navigations. This is used to check
// that we record UKMs for correct SourceIds.
std::vector<int64_t> navigation_ids_;
protected:
void TestCancelPrerendersWhenTimeout(
std::vector<Visibility> visibility_transitions);
void TestCancelOnlyEmbedderTriggeredPrerenderWhenTimeout(
std::vector<Visibility> visibility_transitions);
void TestTimerResetWhenPageGoBackToForeground(Visibility visibility);
void TestCancelPrerenderWithTargetBlankWhenTimeout(Visibility visibility);
void TestEmbedderTriggerWithUnsupportedScheme(const GURL& prerendering_url);
net::test_server::EmbeddedTestServer& ssl_server() { return ssl_server_; }
// Override this in subclasses if you want the test_ukm_recorder() and friends
// to expect a different predictor.
virtual PreloadingPredictor PredictorToExpectInUkm() {
return content_preloading_predictor::kSpeculationRules;
}
void ResetPointerPosition() {
#if !BUILDFLAG(IS_ANDROID)
InputEventAckWaiter waiter(
web_contents()->GetPrimaryMainFrame()->GetRenderWidgetHost(),
blink::WebInputEvent::Type::kMouseMove);
SimulateMouseEvent(web_contents(), blink::WebMouseEvent::Type::kMouseMove,
blink::WebMouseEvent::Button::kNoButton,
gfx::Point(0, 0));
waiter.Wait();
#else
// TODO(crbug.com/40269669): Simulate |WebGestureEvent| to make this
// function work for Android.
#endif // !BUILDFLAG(IS_ANDROID)
}
void PointerHoverToAnchor(const GURL& url) {
ResetPointerPosition();
#if !BUILDFLAG(IS_ANDROID)
const auto point = CalculateCenterPointOfAnchorElement(url);
InputEventAckWaiter waiter(
web_contents()->GetPrimaryMainFrame()->GetRenderWidgetHost(),
blink::WebInputEvent::Type::kMouseMove);
SimulateMouseEvent(web_contents(), blink::WebMouseEvent::Type::kMouseMove,
blink::WebMouseEvent::Button::kNoButton, point);
waiter.Wait();
#else
// TODO(crbug.com/40269669): Simulate |WebGestureEvent| to make this
// function work for Android.
#endif // !BUILDFLAG(IS_ANDROID)
}
void PointerDownToAnchor(const GURL& url) {
ResetPointerPosition();
#if !BUILDFLAG(IS_ANDROID)
const auto point = CalculateCenterPointOfAnchorElement(url);
InputEventAckWaiter waiter(
web_contents()->GetPrimaryMainFrame()->GetRenderWidgetHost(),
blink::WebInputEvent::Type::kMouseDown);
SimulateMouseEventForClick(blink::WebMouseEvent::Type::kMouseDown,
blink::WebMouseEvent::Button::kLeft, point);
waiter.Wait();
#else
// TODO(crbug.com/40269669): Simulate |WebGestureEvent| to make this
// function work for Android.
#endif // !BUILDFLAG(IS_ANDROID)
}
void PointerUpToAnchor(const GURL& url) {
#if !BUILDFLAG(IS_ANDROID)
const auto point = CalculateCenterPointOfAnchorElement(url);
InputEventAckWaiter waiter(
web_contents()->GetPrimaryMainFrame()->GetRenderWidgetHost(),
blink::WebInputEvent::Type::kMouseUp);
SimulateMouseEventForClick(blink::WebMouseEvent::Type::kMouseUp,
blink::WebMouseEvent::Button::kLeft, point);
waiter.Wait();
#else
// TODO(crbug.com/40269669): Simulate |WebGestureEvent| to make this
// function work for Android.
#endif // !BUILDFLAG(IS_ANDROID)
}
void InsertAnchor(const GURL url) {
const std::string script = R"(
const anchor = document.createElement('a');
anchor.href = $1;
anchor.text = $1;
document.body.appendChild(anchor);
)";
ASSERT_TRUE(ExecJs(web_contents(), JsReplace(script, url.spec())));
}
void ClickAnchor(const GURL url) {
PointerDownToAnchor(url);
PointerUpToAnchor(url);
}
private:
void DidStartNavigation(NavigationHandle* handle) override {
navigation_ids_.push_back(handle->GetNavigationId());
}
void SimulateMouseEventForClick(blink::WebInputEvent::Type type,
blink::WebMouseEvent::Button button,
const gfx::Point& point) {
auto* web_contents_impl = static_cast<WebContentsImpl*>(web_contents());
auto* rwhvb = static_cast<RenderWidgetHostViewBase*>(
web_contents()->GetRenderWidgetHostView());
blink::WebMouseEvent mouse_event(type, 0, ui::EventTimeForNow());
mouse_event.button = button;
mouse_event.SetPositionInWidget(point.x(), point.y());
// Mac needs positionInScreen for events to plugins.
gfx::Rect offset = web_contents()->GetContainerBounds();
mouse_event.SetPositionInScreen(point.x() + offset.x(),
point.y() + offset.y());
mouse_event.click_count = 1;
web_contents_impl->GetInputEventRouter()->RouteMouseEvent(
rwhvb, &mouse_event, ui::LatencyInfo());
}
gfx::Point CalculateCenterPointOfAnchorElement(const GURL& url) {
const std::string script_get_x = R"(
const anchor = document.querySelector('a[href=$1]');
const bounds = anchor.getBoundingClientRect();
Math.floor(bounds.left + bounds.width / 2);
)";
const std::string script_get_y = R"(
const anchor = document.querySelector('a[href=$1]');
const bounds = anchor.getBoundingClientRect();
Math.floor(bounds.top + bounds.height / 2);
)";
const float x = EvalJs(web_contents(), JsReplace(script_get_x, url.spec()))
.ExtractDouble();
const float y = EvalJs(web_contents(), JsReplace(script_get_y, url.spec()))
.ExtractDouble();
return gfx::ToFlooredPoint(gfx::PointF(x, y));
}
base::ScopedMockElapsedTimersForTest scoped_test_timer_;
net::test_server::EmbeddedTestServer ssl_server_{
net::test_server::EmbeddedTestServer::TYPE_HTTPS};
std::unique_ptr<test::PrerenderTestHelper> prerender_helper_;
base::HistogramTester histogram_tester_;
std::unique_ptr<ukm::TestAutoSetUkmRecorder> ukm_recorder_;
std::unique_ptr<test::PreloadingAttemptUkmEntryBuilder>
attempt_ukm_entry_builder_;
std::unique_ptr<PreloadingAttemptPreviousPrimaryPageUkmEntryBuilder>
attempt_previous_ukm_entry_builder_;
std::unique_ptr<test::PreloadingPredictionUkmEntryBuilder>
prediction_ukm_entry_builder_;
std::unique_ptr<PreloadingPredictionPreviousPrimaryPageUkmEntryBuilder>
prediction_previous_ukm_entry_builder_;
std::unique_ptr<net::test_server::ControllableHttpResponse>
pagehide_event_receiver_;
base::test::ScopedFeatureList feature_list_;
};
class NoVarySearchPrerenderBrowserTest : public PrerenderBrowserTest {
public:
using StartedReason = PrerenderHost::WaitingForHeadersStartedReason;
using FinishedReason = PrerenderHost::WaitingForHeadersFinishedReason;
NoVarySearchPrerenderBrowserTest() {
feature_list_.InitAndEnableFeatureWithParameters(
features::kPrerender2NoVarySearch,
{{"wait_for_headers_timeout_eager_prerender", "500"}});
}
~NoVarySearchPrerenderBrowserTest() override = default;
protected:
void TestNoVarySearchHeaderFailure(const std::string& no_vary_search_header,
FinishedReason expected_finished_reason);
private:
base::test::ScopedFeatureList feature_list_;
};
class NoVarySearchHintPrerenderHostObserver : public PrerenderHost::Observer {
public:
explicit NoVarySearchHintPrerenderHostObserver(
PrerenderHost& prerender_host) {
observation_.Observe(&prerender_host);
}
void OnWaitingForHeadersStarted(
NavigationHandle& navigation_handle,
PrerenderHost::WaitingForHeadersStartedReason reason) override {
DCHECK(static_cast<NavigationRequest*>(&navigation_handle));
ASSERT_FALSE(static_cast<NavigationRequest*>(&navigation_handle)
->IsCommitDeferringConditionDeferredForTesting());
ASSERT_FALSE(wait_for_headers_start_reason_.has_value());
ASSERT_FALSE(wait_for_headers_finish_reason_.has_value());
wait_for_headers_start_reason_ = reason;
}
void OnWaitingForHeadersFinished(
PrerenderHost::WaitingForHeadersFinishedReason reason) override {
ASSERT_FALSE(wait_for_headers_finish_reason_.has_value());
wait_for_headers_finish_reason_ = reason;
// Reset the observation here, not in Observer::OnHostDestroyed(), as
// OnWaitingForHeadersFinished() is supposed to be called after that.
observation_.Reset();
}
std::optional<PrerenderHost::WaitingForHeadersStartedReason>
wait_for_headers_start_reason() const {
return wait_for_headers_start_reason_;
}
std::optional<PrerenderHost::WaitingForHeadersFinishedReason>
wait_for_headers_finish_reason() const {
return wait_for_headers_finish_reason_;
}
private:
std::optional<PrerenderHost::WaitingForHeadersStartedReason>
wait_for_headers_start_reason_;
std::optional<PrerenderHost::WaitingForHeadersFinishedReason>
wait_for_headers_finish_reason_;
base::ScopedObservation<PrerenderHost, PrerenderHost::Observer> observation_{
this};
};
} // namespace
// Test that the timer is enabled and cleared appropriately when navigating to
// a No-Vary-Search hint matched prerender successfully.
IN_PROC_BROWSER_TEST_F(
NoVarySearchPrerenderBrowserTest,
EagerTimerWorksCorrectlyForHeadersThatArriveBeforeTimeout) {
const std::string kTestingRelativeUrl =
"/delayed_with_no_vary_search?prerender";
const std::string kPrerenderingRelativeUrl = kTestingRelativeUrl + "&a=5";
// Create a HTTP response to control prerendering main-frame navigation.
net::test_server::ControllableHttpResponse main_prerender_response(
embedded_test_server(), kPrerenderingRelativeUrl);
ASSERT_TRUE(embedded_test_server()->Start());
const GURL kInitialUrl = embedded_test_server()->GetURL("/empty.html");
const GURL kPrerenderingUrl =
embedded_test_server()->GetURL(kPrerenderingRelativeUrl);
const GURL kNavigationUrl =
embedded_test_server()->GetURL(kTestingRelativeUrl + "&a=3");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
ASSERT_EQ(web_contents()->GetLastCommittedURL(), kInitialUrl);
// Inject mock time task runner.
auto task_runner = base::MakeRefCounted<base::TestMockTimeTaskRunner>();
PrerenderNoVarySearchHintCommitDeferringCondition::
SetTimerTaskRunnerForTesting(task_runner);
// Start prerendering `kPrerenderingUrl`.
content::test::PrerenderHostCreationWaiter host_creation_waiter;
AddPrerenderAsync(kPrerenderingUrl, R"(params=(\\\"a\\\"))");
FrameTreeNodeId host_id = host_creation_waiter.Wait();
auto* host =
web_contents_impl()->GetPrerenderHostRegistry()->FindNonReservedHostById(
host_id);
ASSERT_TRUE(host);
ASSERT_TRUE(host->no_vary_search_hint().has_value());
// Add a testing PrerenderHost::Observer to the prerender host that we'd like
// to activate.
NoVarySearchHintPrerenderHostObserver observer(*host);
// Start navigation in primary page to kNavigationUrl.
TestActivationManager primary_page_manager(web_contents(), kNavigationUrl);
// Start to navigate to kNavigationUrl
std::unique_ptr<content::TestNavigationObserver> nav_observer =
test::PrerenderTestHelper::NavigatePrimaryPageAsync(*web_contents_impl(),
kNavigationUrl);
// Wait until the navigation is deferred by CommitDeferringCondition.
ASSERT_TRUE(primary_page_manager.WaitForBeforeChecks());
primary_page_manager.ResumeActivation();
ASSERT_FALSE(host->were_headers_received());
ASSERT_TRUE(host->WaitUntilHeadTimeout().is_positive());
auto* prerender_web_contents =
content::WebContents::FromFrameTreeNodeId(host_id);
content::test::PrerenderHostObserver host_observer(*prerender_web_contents,
host_id);
// Advance the prerender http response by sending headers.
main_prerender_response.WaitForRequest();
// Advance timer for half the wait until head timeout.
task_runner->FastForwardBy(host->WaitUntilHeadTimeout() / 2);
main_prerender_response.Send(
net::HTTP_OK, /*content_type=*/"text/html", /*content=*/"",
/*cookies=*/{}, /*extra_headers=*/{"No-Vary-Search: params=(\"a\")"});
main_prerender_response.Send("Some Content");
main_prerender_response.Done();
ASSERT_TRUE(primary_page_manager.WaitForAfterChecks());
primary_page_manager.ResumeActivation();
// Wait for the navigation to finish.
nav_observer->Wait();
primary_page_manager.WaitForNavigationFinished();
// Check that the prerender host was activated.
ASSERT_TRUE(host_observer.was_activated());
// Ensure the state has been propagated to renderer processes.
ASSERT_EQ(false, EvalJs(web_contents(), "document.prerendering"));
// The prerender host should be consumed.
EXPECT_FALSE(HasHostForUrl(kPrerenderingUrl));
ASSERT_TRUE(observer.wait_for_headers_start_reason().has_value());
ASSERT_TRUE(observer.wait_for_headers_finish_reason().has_value());
EXPECT_EQ(observer.wait_for_headers_start_reason().value(),
StartedReason::kWithTimeout);
EXPECT_EQ(observer.wait_for_headers_finish_reason().value(),
FinishedReason::kNoVarySearchHeaderReceivedAndMatched);
histogram_tester().ExpectUniqueSample(
"Prerender.Experimental.WaitingForHeadersFinishedReason.SpeculationRule",
FinishedReason::kNoVarySearchHeaderReceivedAndMatched, 1);
histogram_tester().ExpectUniqueSample(
"Prerender.Experimental.MatchableHostCountOnActivation", 1, 1);
}
// Tests the case where prerendering navigation fails while a potential
// activation navigation is waiting for the No-Vary-Search header.
// This is a regression test for crbug.com/420906968.
IN_PROC_BROWSER_TEST_F(NoVarySearchPrerenderBrowserTest,
FailureOnPrerenderNavigation) {
const std::string kTestingRelativeUrl =
"/delayed_with_no_vary_search?prerender";
const std::string kPrerenderingRelativeUrl = kTestingRelativeUrl + "&a=5";
// Create a HTTP response to control prerendering main-frame navigation.
net::test_server::ControllableHttpResponse main_prerender_response(
embedded_test_server(), kPrerenderingRelativeUrl);
ASSERT_TRUE(embedded_test_server()->Start());
const GURL initial_url = embedded_test_server()->GetURL("/empty.html");
const GURL prerendering_url =
embedded_test_server()->GetURL(kPrerenderingRelativeUrl);
const GURL navigation_url =
embedded_test_server()->GetURL(kTestingRelativeUrl + "&a=3");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
ASSERT_EQ(web_contents()->GetLastCommittedURL(), initial_url);
// Start prerendering with the No-Vary-Search hint.
content::test::PrerenderHostCreationWaiter host_creation_waiter;
AddPrerenderAsync(prerendering_url, R"(params=(\\\"a\\\"))");
FrameTreeNodeId host_id = host_creation_waiter.Wait();
auto* host =
web_contents_impl()->GetPrerenderHostRegistry()->FindNonReservedHostById(
host_id);
ASSERT_TRUE(host);
ASSERT_TRUE(host->no_vary_search_hint().has_value());
// Add a testing PrerenderHost::Observer to the prerender host that we'd like
// to monitor.
NoVarySearchHintPrerenderHostObserver observer(*host);
// Start navigation in primary page.
TestActivationManager primary_page_manager(web_contents(), navigation_url);
std::unique_ptr<content::TestNavigationObserver> nav_observer =
test::PrerenderTestHelper::NavigatePrimaryPageAsync(*web_contents_impl(),
navigation_url);
// Wait until the navigation is deferred by CommitDeferringCondition.
ASSERT_TRUE(primary_page_manager.WaitForBeforeChecks());
primary_page_manager.ResumeActivation();
ASSERT_FALSE(host->were_headers_received());
auto* prerender_web_contents =
content::WebContents::FromFrameTreeNodeId(host_id);
content::test::PrerenderHostObserver host_observer(*prerender_web_contents,
host_id);
// Abort the request. This fails the prerender navigation.
main_prerender_response.WaitForRequest();
main_prerender_response.Done();
ASSERT_TRUE(primary_page_manager.WaitForAfterChecks());
primary_page_manager.ResumeActivation();
// Wait for the navigation to finish.
nav_observer->Wait();
primary_page_manager.WaitForNavigationFinished();
// Check that the prerender host was not activated.
ASSERT_FALSE(host_observer.was_activated());
host_observer.WaitForDestroyed();
ASSERT_TRUE(observer.wait_for_headers_start_reason().has_value());
ASSERT_TRUE(observer.wait_for_headers_finish_reason().has_value());
EXPECT_EQ(observer.wait_for_headers_start_reason().value(),
StartedReason::kWithTimeout);
EXPECT_EQ(observer.wait_for_headers_finish_reason().value(),
FinishedReason::kPrerenderNavigationFailed);
histogram_tester().ExpectUniqueSample(
"Prerender.Experimental.WaitingForHeadersFinishedReason.SpeculationRule",
FinishedReason::kPrerenderNavigationFailed, 1);
}
// Test that the timer is enabled and cleared appropriately when navigating to
// a No-Vary-Search hint matched prerender with timeout waiting for headers.
// Flaky on android: crbug.com/395337644
#if BUILDFLAG(IS_ANDROID)
#define MAYBE_EagerTimerWorksCorrectlyForHeadersThatArriveAfterTimeout \
DISABLED_EagerTimerWorksCorrectlyForHeadersThatArriveAfterTimeout
#else
#define MAYBE_EagerTimerWorksCorrectlyForHeadersThatArriveAfterTimeout \
EagerTimerWorksCorrectlyForHeadersThatArriveAfterTimeout
#endif
IN_PROC_BROWSER_TEST_F(
NoVarySearchPrerenderBrowserTest,
MAYBE_EagerTimerWorksCorrectlyForHeadersThatArriveAfterTimeout) {
const std::string kTestingRelativeUrl =
"/delayed_with_no_vary_search?prerender";
const std::string kPrerenderingRelativeUrl = kTestingRelativeUrl + "&a=5";
// Create a HTTP response to control prerendering main-frame navigation.
net::test_server::ControllableHttpResponse main_prerender_response(
embedded_test_server(), kPrerenderingRelativeUrl);
const std::string kNavigationRelativeUrl = kTestingRelativeUrl + "&a=3";
// Create a HTTP response to control the navigation in main-frame.
net::test_server::ControllableHttpResponse main_navigation_response(
embedded_test_server(), kNavigationRelativeUrl);
ASSERT_TRUE(embedded_test_server()->Start());
const GURL kInitialUrl = embedded_test_server()->GetURL("/empty.html");
const GURL kPrerenderingUrl =
embedded_test_server()->GetURL(kPrerenderingRelativeUrl);
const GURL kNavigationUrl =
embedded_test_server()->GetURL(kNavigationRelativeUrl);
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
ASSERT_EQ(web_contents()->GetLastCommittedURL(), kInitialUrl);
// Inject mock time task runner.
auto task_runner = base::MakeRefCounted<base::TestMockTimeTaskRunner>();
PrerenderNoVarySearchHintCommitDeferringCondition::
SetTimerTaskRunnerForTesting(task_runner);
// Start prerendering `kPrerenderingUrl`.
content::test::PrerenderHostCreationWaiter host_creation_waiter;
AddPrerenderAsync(kPrerenderingUrl, R"(params=(\\\"a\\\"))");
FrameTreeNodeId host_id = host_creation_waiter.Wait();
auto* host =
web_contents_impl()->GetPrerenderHostRegistry()->FindNonReservedHostById(
host_id);
ASSERT_TRUE(host);
ASSERT_TRUE(host->no_vary_search_hint().has_value());
// Add a testing PrerenderHost::Observer to the prerender host that we'd like
// to activate.
NoVarySearchHintPrerenderHostObserver observer(*host);
// Start navigation in primary page to kNavigationUrl.
TestActivationManager primary_page_manager(web_contents(), kNavigationUrl);
// Start to navigate to kNavigationUrl
std::unique_ptr<content::TestNavigationObserver> nav_observer =
test::PrerenderTestHelper::NavigatePrimaryPageAsync(*web_contents_impl(),
kNavigationUrl);
// Wait until the navigation is deferred by CommitDeferringCondition.
ASSERT_TRUE(primary_page_manager.WaitForBeforeChecks());
primary_page_manager.ResumeActivation();
ASSERT_FALSE(host->were_headers_received());
ASSERT_TRUE(host->WaitUntilHeadTimeout().is_positive());
auto* prerender_web_contents =
content::WebContents::FromFrameTreeNodeId(host_id);
content::test::PrerenderHostObserver host_observer(*prerender_web_contents,
host_id);
// Advance the prerender http response by sending headers.
main_prerender_response.WaitForRequest();
// Advance timer for twice the wait until head timeout.
task_runner->FastForwardBy(2 * host->WaitUntilHeadTimeout());
main_prerender_response.Send(
net::HTTP_OK, /*content_type=*/"text/html", /*content=*/"",
/*cookies=*/{}, /*extra_headers=*/{"No-Vary-Search: params=(\"a\")"});
main_prerender_response.Send("Some Content");
main_prerender_response.Done();
ASSERT_TRUE(primary_page_manager.WaitForAfterChecks());
main_navigation_response.WaitForRequest();
main_navigation_response.Send("Some Content");
main_navigation_response.Done();
// Wait for the navigation to finish.
nav_observer->Wait();
primary_page_manager.WaitForNavigationFinished();
// Check that the prerender host was activated.
ASSERT_FALSE(host_observer.was_activated());
// Ensure the state has been propagated to renderer processes.
ASSERT_EQ(false, EvalJs(web_contents(), "document.prerendering"));
// The prerender host should be destroyed.
EXPECT_FALSE(HasHostForUrl(kPrerenderingUrl));
ASSERT_TRUE(observer.wait_for_headers_start_reason().has_value());
ASSERT_TRUE(observer.wait_for_headers_finish_reason().has_value());
EXPECT_EQ(observer.wait_for_headers_start_reason().value(),
StartedReason::kWithTimeout);
EXPECT_EQ(observer.wait_for_headers_finish_reason().value(),
FinishedReason::kTimeoutElapsed);
histogram_tester().ExpectUniqueSample(
"Prerender.Experimental.WaitingForHeadersFinishedReason.SpeculationRule",
FinishedReason::kTimeoutElapsed, 1);
histogram_tester().ExpectUniqueSample(
"Prerender.Experimental.MatchableHostCountOnActivation", 1, 1);
}
// Helper function to test cases where `no_vary_search_header` that does not
// match the No-Vary-Search hint is served and results in activation mismatch.
void NoVarySearchPrerenderBrowserTest::TestNoVarySearchHeaderFailure(
const std::string& no_vary_search_header,
FinishedReason expected_finished_reason) {
const std::string kTestingRelativeUrl =
"/delayed_with_no_vary_search?prerender";
const std::string kPrerenderingRelativeUrl = kTestingRelativeUrl + "&a=5";
// Create a HTTP response to control prerendering main-frame navigation.
net::test_server::ControllableHttpResponse main_prerender_response(
embedded_test_server(), kPrerenderingRelativeUrl);
ASSERT_TRUE(embedded_test_server()->Start());
const GURL kInitialUrl = embedded_test_server()->GetURL("/empty.html");
const GURL kPrerenderingUrl =
embedded_test_server()->GetURL(kPrerenderingRelativeUrl);
const GURL kNavigationUrl =
embedded_test_server()->GetURL(kTestingRelativeUrl + "&a=3");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
ASSERT_EQ(web_contents()->GetLastCommittedURL(), kInitialUrl);
// Inject mock time task runner to avoid timeout.
auto task_runner = base::MakeRefCounted<base::TestMockTimeTaskRunner>();
PrerenderNoVarySearchHintCommitDeferringCondition::
SetTimerTaskRunnerForTesting(task_runner);
// Start prerendering `kPrerenderingUrl`.
content::test::PrerenderHostCreationWaiter host_creation_waiter;
AddPrerenderAsync(kPrerenderingUrl, R"(params=(\\\"a\\\"))");
FrameTreeNodeId host_id = host_creation_waiter.Wait();
auto* host =
web_contents_impl()->GetPrerenderHostRegistry()->FindNonReservedHostById(
host_id);
ASSERT_TRUE(host);
ASSERT_TRUE(host->no_vary_search_hint().has_value());
// Add a testing PrerenderHost::Observer to the prerender host that we'd like
// to activate.
NoVarySearchHintPrerenderHostObserver observer(*host);
// Start navigation in primary page to kNavigationUrl.
TestActivationManager primary_page_manager(web_contents(), kNavigationUrl);
// Start to navigate to kNavigationUrl
std::unique_ptr<content::TestNavigationObserver> nav_observer =
test::PrerenderTestHelper::NavigatePrimaryPageAsync(*web_contents_impl(),
kNavigationUrl);
// Wait until the navigation is deferred by CommitDeferringCondition.
ASSERT_TRUE(primary_page_manager.WaitForBeforeChecks());
primary_page_manager.ResumeActivation();
ASSERT_FALSE(host->were_headers_received());
ASSERT_TRUE(host->WaitUntilHeadTimeout().is_positive());
auto* prerender_web_contents =
content::WebContents::FromFrameTreeNodeId(host_id);
content::test::PrerenderHostObserver host_observer(*prerender_web_contents,
host_id);
// Advance the prerender http response by sending headers.
main_prerender_response.WaitForRequest();
main_prerender_response.Send(net::HTTP_OK, /*content_type=*/"text/html",
/*content=*/"",
/*cookies=*/{}, {no_vary_search_header});
main_prerender_response.Send("Some Content");
main_prerender_response.Done();
// Wait for the navigation to finish.
nav_observer->Wait();
primary_page_manager.WaitForNavigationFinished();
// Check that the prerender host was not activated as the header was not
// valid.
ASSERT_FALSE(host_observer.was_activated());
ASSERT_TRUE(observer.wait_for_headers_start_reason().has_value());
ASSERT_TRUE(observer.wait_for_headers_finish_reason().has_value());
EXPECT_EQ(observer.wait_for_headers_start_reason().value(),
StartedReason::kWithTimeout);
EXPECT_EQ(observer.wait_for_headers_finish_reason().value(),
expected_finished_reason);
histogram_tester().ExpectUniqueSample(
"Prerender.Experimental.WaitingForHeadersFinishedReason.SpeculationRule",
expected_finished_reason, 1);
histogram_tester().ExpectTotalCount(
"Prerender.Experimental.MatchableHostCountOnActivation", 1);
}
// Test that a No-Vary-Search header is malformed.
IN_PROC_BROWSER_TEST_F(NoVarySearchPrerenderBrowserTest,
MalformedNoVarySearchHeader) {
TestNoVarySearchHeaderFailure("No-Vary-Search: malformed(\"a\")",
FinishedReason::kNoVarySearchHeaderParseFailed);
}
// Test that a No-Vary-Search header is default value.
IN_PROC_BROWSER_TEST_F(NoVarySearchPrerenderBrowserTest,
NoVarySearchHeaderWithDefaultValue) {
TestNoVarySearchHeaderFailure(
"No-Vary-Search: params=()",
FinishedReason::kNoVarySearchHeaderReceivedButDefaultValue);
}
// Test that a No-Vary-Search header is not served.
IN_PROC_BROWSER_TEST_F(NoVarySearchPrerenderBrowserTest, NoNoVarySearchHeader) {
TestNoVarySearchHeaderFailure("",
FinishedReason::kNoVarySearchHeaderNotReceived);
}
// Test that a No-Vary-Search header is received but does not match.
IN_PROC_BROWSER_TEST_F(NoVarySearchPrerenderBrowserTest,
UnmatchedNoVarySearchHeader) {
TestNoVarySearchHeaderFailure(
"No-Vary-Search: params=(\"different\")",
FinishedReason::kNoVarySearchHeaderReceivedButNotMatched);
}
// Test that activation is successful when navigating to an inexact URL
// before No-Vary-Search header is back from the server, if the No-Vary-Search
// header is matching when it is received.
IN_PROC_BROWSER_TEST_F(NoVarySearchPrerenderBrowserTest,
HintActivationSuccessful) {
const std::string kTestingRelativeUrl =
"/delayed_with_no_vary_search?prerender";
const std::string kPrerenderingRelativeUrl = kTestingRelativeUrl + "&a=5";
// Create a HTTP response to control prerendering main-frame navigation.
net::test_server::ControllableHttpResponse main_prerender_response(
embedded_test_server(), kPrerenderingRelativeUrl);
ASSERT_TRUE(embedded_test_server()->Start());
const GURL kInitialUrl = embedded_test_server()->GetURL("/empty.html");
const GURL kPrerenderingUrl =
embedded_test_server()->GetURL(kPrerenderingRelativeUrl);
const GURL kNavigationUrl =
embedded_test_server()->GetURL(kTestingRelativeUrl + "&a=3");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
ASSERT_EQ(web_contents()->GetLastCommittedURL(), kInitialUrl);
// Start prerendering `kPrerenderingUrl`.
content::test::PrerenderHostCreationWaiter host_creation_waiter;
AddPrerenderAsync(kPrerenderingUrl, R"(params=(\\\"a\\\"))");
FrameTreeNodeId host_id = host_creation_waiter.Wait();
auto* host =
web_contents_impl()->GetPrerenderHostRegistry()->FindNonReservedHostById(
host_id);
ASSERT_TRUE(host);
ASSERT_TRUE(host->no_vary_search_hint().has_value());
// Add a PrerenderHost::Observer with default behaviour to increase
// code coverage.
PrerenderHost::Observer empty_observer;
host->AddObserver(&empty_observer);
NavigationHandleObserver activation_observer(web_contents(), kNavigationUrl);
// Start navigation in primary page to kNavigationUrl.
TestActivationManager primary_page_manager(shell()->web_contents(),
kNavigationUrl);
// Start to navigate to kNavigationUrl
std::unique_ptr<content::TestNavigationObserver> nav_observer =
test::PrerenderTestHelper::NavigatePrimaryPageAsync(*web_contents_impl(),
kNavigationUrl);
// Wait until the navigation is deferred by CommitDeferringCondition.
ASSERT_TRUE(primary_page_manager.WaitForBeforeChecks());
primary_page_manager.ResumeActivation();
ASSERT_FALSE(host->were_headers_received());
// Make sure that the prerender host is not a match by IsUrlMatch.
ASSERT_FALSE(host->IsUrlMatch(kNavigationUrl));
auto* prerender_web_contents =
content::WebContents::FromFrameTreeNodeId(host_id);
content::test::PrerenderHostObserver host_observer(*prerender_web_contents,
host_id);
// Check that PrerenderNoVarySearchHintCommitDeferringCondition is deferring
// the commit.
NavigationRequest* nav_request =
web_contents_impl()->GetPrimaryFrameTree().root()->navigation_request();
EXPECT_TRUE(nav_request->IsCommitDeferringConditionDeferredForTesting());
// The navigation should not have proceeded past NOT_STARTED because the
// PrerenderCommitDeferringCondition is deferring it.
EXPECT_EQ(nav_request->state(), NavigationRequest::NOT_STARTED);
// Advance the prerender http response by sending headers.
main_prerender_response.WaitForRequest();
main_prerender_response.Send(
net::HTTP_OK, /*content_type=*/"text/html", /*content=*/"",
/*cookies=*/{}, /*extra_headers=*/{"No-Vary-Search: params=(\"a\")"});
host_observer.WaitForHeaders();
ASSERT_TRUE(host->were_headers_received());
// Make sure that, after receiving headers the prerender host is a match by
// IsUrlMatch.
ASSERT_TRUE(host->IsUrlMatch(kNavigationUrl));
EXPECT_TRUE(nav_request->IsCommitDeferringConditionDeferredForTesting());
main_prerender_response.Send("Some Content");
main_prerender_response.Done();
ASSERT_TRUE(primary_page_manager.WaitForAfterChecks());
primary_page_manager.ResumeActivation();
// Wait for the navigation to finish.
nav_observer->Wait();
primary_page_manager.WaitForNavigationFinished();
// Check that the prerender host was activated.
ASSERT_TRUE(host_observer.was_activated());
// Ensure the state has been propagated to renderer processes.
ASSERT_EQ(false, EvalJs(web_contents(), "document.prerendering"));
// The prerender host should be consumed.
EXPECT_FALSE(HasHostForUrl(kPrerenderingUrl));
// Activating the prerendered page should not issue a request.
ExpectFinalStatusForSpeculationRule(PrerenderFinalStatus::kActivated);
ASSERT_EQ(web_contents()->GetLastCommittedURL(), kNavigationUrl);
ukm::SourceId ukm_source_id = activation_observer.next_page_ukm_source_id();
ExpectPreloadingAttemptUkm({attempt_ukm_entry_builder().BuildEntry(
ukm_source_id, PreloadingType::kPrerender,
PreloadingEligibility::kEligible, PreloadingHoldbackStatus::kAllowed,
PreloadingTriggeringOutcome::kSuccess,
PreloadingFailureReason::kUnspecified,
/*accurate=*/true,
/*ready_time=*/kMockElapsedTime,
blink::mojom::SpeculationEagerness::kEager)});
histogram_tester().ExpectUniqueSample(
"Prerender.Experimental.MatchableHostCountOnActivation", 1, 1);
}
// Test that activation is not successful when navigating to an inexact URL
// before No-Vary-Search header is back from the server if the No-Vary-Search
// header is not matching when it is received.
IN_PROC_BROWSER_TEST_F(NoVarySearchPrerenderBrowserTest,
HintActivationUnsuccessful) {
const std::string kTestingRelativeUrl =
"/delayed_without_no_vary_search?prerender";
const std::string kPrerenderingRelativeUrl = kTestingRelativeUrl + "&a=5";
// Create a HTTP response to control prerendering main-frame navigation.
net::test_server::ControllableHttpResponse main_prerender_response(
embedded_test_server(), kPrerenderingRelativeUrl);
const std::string kNavigationRelativeUrl = kTestingRelativeUrl + "&a=3";
// Create a HTTP response to control main-frame navigation.
net::test_server::ControllableHttpResponse main_navigation_response(
embedded_test_server(), kNavigationRelativeUrl);
ASSERT_TRUE(embedded_test_server()->Start());
const GURL kInitialUrl = embedded_test_server()->GetURL("/empty.html");
const GURL kPrerenderingUrl =
embedded_test_server()->GetURL(kPrerenderingRelativeUrl);
const GURL kNavigationUrl =
embedded_test_server()->GetURL(kNavigationRelativeUrl);
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
ASSERT_EQ(web_contents()->GetLastCommittedURL(), kInitialUrl);
// Start prerendering `kPrerenderingUrl`.
content::test::PrerenderHostCreationWaiter host_creation_waiter;
AddPrerenderAsync(kPrerenderingUrl, R"(params=(\\\"a\\\"))");
FrameTreeNodeId host_id = host_creation_waiter.Wait();
auto* host =
web_contents_impl()->GetPrerenderHostRegistry()->FindNonReservedHostById(
host_id);
ASSERT_TRUE(host);
ASSERT_TRUE(host->no_vary_search_hint().has_value());
TestActivationManager primary_page_manager(shell()->web_contents(),
kNavigationUrl);
// Start navigation to kNavigationUrl.
std::unique_ptr<content::TestNavigationObserver> nav_observer =
test::PrerenderTestHelper::NavigatePrimaryPageAsync(*web_contents_impl(),
kNavigationUrl);
// Wait until the navigation is deferred by CommitDeferringCondition.
ASSERT_TRUE(primary_page_manager.WaitForBeforeChecks());
primary_page_manager.ResumeActivation();
ASSERT_FALSE(host->were_headers_received());
NavigationRequest* nav_request =
web_contents_impl()->GetPrimaryFrameTree().root()->navigation_request();
// Make sure PrerenderHostRegistry selects this prerender as a potential
// prerender host to activate.
ASSERT_TRUE(host->IsNoVarySearchHintUrlMatch(kNavigationUrl));
// Make sure that the prerender host is not a match by IsUrlMatch.
ASSERT_FALSE(host->IsUrlMatch(kNavigationUrl));
// Check that PrerenderNoVarySearchHintCommitDeferringCondition is deferring
// the commit.
EXPECT_TRUE(nav_request->IsCommitDeferringConditionDeferredForTesting());
// The navigation should not have proceeded past NOT_STARTED because the
// PrerenderCommitDeferringCondition is deferring it.
EXPECT_EQ(nav_request->state(), NavigationRequest::NOT_STARTED);
auto* prerender_web_contents =
content::WebContents::FromFrameTreeNodeId(host_id);
content::test::PrerenderHostObserver host_observer(*prerender_web_contents,
host_id);
// Advance the prerender http response by sending headers.
main_prerender_response.WaitForRequest();
main_prerender_response.Send(net::HTTP_OK, /*content_type=*/"text/html",
/*content=*/"Some Content");
host_observer.WaitForHeaders();
ASSERT_TRUE(host->were_headers_received());
// Make sure that, after receiving headers the prerender host is not a match
// by IsUrlMatch.
ASSERT_FALSE(host->IsUrlMatch(kNavigationUrl));
main_prerender_response.Done();
main_navigation_response.WaitForRequest();
main_navigation_response.Send(net::HTTP_OK, /*content_type=*/"text/html",
/*content=*/"Other Content");
main_navigation_response.Done();
primary_page_manager.WaitForNavigationFinished();
// Check that the prerender host was not activated.
ASSERT_FALSE(host_observer.was_activated());
// Wait for the navigation to finish.
nav_observer->Wait();
// The navigation should issue a request.
ASSERT_EQ(web_contents()->GetLastCommittedURL(), kNavigationUrl);
histogram_tester().ExpectUniqueSample(
"Prerender.Experimental.MatchableHostCountOnActivation", 1, 1);
}
// Test that activation is successful when navigating to an exact URL before
// No-Vary-Search header is back from the server.
IN_PROC_BROWSER_TEST_F(NoVarySearchPrerenderBrowserTest,
HintActivationSuccessful_ExactUrl) {
const std::string testing_relative_url =
"/delayed_with_no_vary_search?prerender";
const std::string prerendering_relative_url = testing_relative_url + "&a=5";
// Create a HTTP response to control prerendering main-frame navigation.
net::test_server::ControllableHttpResponse main_prerender_response(
embedded_test_server(), prerendering_relative_url);
ASSERT_TRUE(embedded_test_server()->Start());
const GURL initial_url = embedded_test_server()->GetURL("/empty.html");
const GURL prerendering_url =
embedded_test_server()->GetURL(prerendering_relative_url);
const GURL navigation_url =
embedded_test_server()->GetURL(prerendering_relative_url);
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
ASSERT_EQ(web_contents()->GetLastCommittedURL(), initial_url);
// Start prerendering `kPrerenderingUrl`.
content::test::PrerenderHostCreationWaiter host_creation_waiter;
AddPrerenderAsync(prerendering_url, R"(params=(\\\"a\\\"))");
FrameTreeNodeId host_id = host_creation_waiter.Wait();
auto* host =
web_contents_impl()->GetPrerenderHostRegistry()->FindNonReservedHostById(
host_id);
ASSERT_TRUE(host);
ASSERT_TRUE(host->no_vary_search_hint().has_value());
NavigationHandleObserver activation_observer(web_contents(), navigation_url);
// Start navigation in primary page to kNavigationUrl.
TestActivationManager primary_page_manager(shell()->web_contents(),
navigation_url);
// Start to navigate to kNavigationUrl
std::unique_ptr<content::TestNavigationObserver> nav_observer =
test::PrerenderTestHelper::NavigatePrimaryPageAsync(*web_contents_impl(),
navigation_url);
// Wait until the navigation is deferred by CommitDeferringCondition.
ASSERT_TRUE(primary_page_manager.WaitForBeforeChecks());
primary_page_manager.ResumeActivation();
ASSERT_FALSE(host->were_headers_received());
// Make sure that the prerender host is a match by IsUrlMatch regardless of
// the No-Vary-Search header.
std::optional<UrlMatchType> match_type = host->IsUrlMatch(navigation_url);
ASSERT_TRUE(match_type.has_value());
ASSERT_EQ(match_type.value(), UrlMatchType::kExact);
auto* prerender_web_contents =
content::WebContents::FromFrameTreeNodeId(host_id);
content::test::PrerenderHostObserver host_observer(*prerender_web_contents,
host_id);
// Check that PrerenderCommitDeferringCondition is deferring the commit.
NavigationRequest* nav_request =
web_contents_impl()->GetPrimaryFrameTree().root()->navigation_request();
EXPECT_TRUE(nav_request->IsCommitDeferringConditionDeferredForTesting());
// The navigation should not have proceeded past NOT_STARTED because the
// PrerenderCommitDeferringCondition is deferring it.
EXPECT_EQ(nav_request->state(), NavigationRequest::NOT_STARTED);
// Advance the prerender http response by sending headers.
main_prerender_response.WaitForRequest();
main_prerender_response.Send(
net::HTTP_OK, /*content_type=*/"text/html", /*content=*/"",
/*cookies=*/{}, /*extra_headers=*/{"No-Vary-Search: params=(\"a\")"});
host_observer.WaitForHeaders();
ASSERT_TRUE(host->were_headers_received());
// Make sure that, after receiving headers the prerender host is still a match
// by IsUrlMatch.
ASSERT_TRUE(host->IsUrlMatch(navigation_url));
EXPECT_TRUE(nav_request->IsCommitDeferringConditionDeferredForTesting());
main_prerender_response.Send("Some Content");
main_prerender_response.Done();
ASSERT_TRUE(primary_page_manager.WaitForAfterChecks());
primary_page_manager.ResumeActivation();
// Wait for the navigation to finish.
nav_observer->Wait();
primary_page_manager.WaitForNavigationFinished();
// Check that the prerender host was activated.
ASSERT_TRUE(host_observer.was_activated());
ExpectFinalStatusForSpeculationRule(PrerenderFinalStatus::kActivated);
// PrerenderNoVarySearchHintCommitDeferringCondition was not be involved in
// prerender activation, so the metric should not be recorded.
histogram_tester().ExpectTotalCount(
"Prerender.Experimental.WaitingForHeadersFinishedReason.SpeculationRule",
0);
histogram_tester().ExpectUniqueSample(
"Prerender.Experimental.MatchableHostCountOnActivation", 1, 1);
}
// Test that activation is successful when 2 matchable PrerenderHosts exist.
IN_PROC_BROWSER_TEST_F(NoVarySearchPrerenderBrowserTest,
MultipleMatchableHosts) {
const std::string testing_relative_url =
"/delayed_with_no_vary_search?prerender";
const std::string prerendering_relative_url1 = testing_relative_url + "&a=5";
const std::string prerendering_relative_url2 = testing_relative_url + "&a=7";
// Create a HTTP response to control prerendering main-frame navigation.
net::test_server::ControllableHttpResponse main_prerender_response1(
embedded_test_server(), prerendering_relative_url1);
const std::string navigation_relative_url = testing_relative_url + "&a=3";
ASSERT_TRUE(embedded_test_server()->Start());
const GURL initial_url = embedded_test_server()->GetURL("/empty.html");
const GURL prerendering_url1 =
embedded_test_server()->GetURL(prerendering_relative_url1);
const GURL prerendering_url2 =
embedded_test_server()->GetURL(prerendering_relative_url2);
const GURL navigation_url =
embedded_test_server()->GetURL(navigation_relative_url);
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
ASSERT_EQ(web_contents()->GetLastCommittedURL(), initial_url);
// Start prerendering `prerendering_url1`.
test::PrerenderHostCreationWaiter host_creation_waiter1;
AddPrerenderAsync(prerendering_url1, R"(params=(\\\"a\\\"))");
FrameTreeNodeId host_id1 = host_creation_waiter1.Wait();
auto* host1 =
web_contents_impl()->GetPrerenderHostRegistry()->FindNonReservedHostById(
host_id1);
ASSERT_TRUE(host1);
ASSERT_TRUE(host1->no_vary_search_hint().has_value());
test::PrerenderHostObserver host_observer1(*web_contents(), host_id1);
// Start prerendering `prerendering_url2`.
test::PrerenderHostCreationWaiter host_creation_waiter2;
AddPrerenderAsync(prerendering_url2, R"(params=(\\\"a\\\"))");
FrameTreeNodeId host_id2 = host_creation_waiter2.Wait();
auto* host2 =
web_contents_impl()->GetPrerenderHostRegistry()->FindNonReservedHostById(
host_id2);
ASSERT_TRUE(host2);
ASSERT_TRUE(host2->no_vary_search_hint().has_value());
test::PrerenderHostObserver host_observer2(*web_contents(), host_id2);
NavigationHandleObserver activation_observer(web_contents(), navigation_url);
// Start navigation in primary page to navigation_url.
TestActivationManager primary_page_manager(shell()->web_contents(),
navigation_url);
// Start to navigate to navigation_url.
std::unique_ptr<TestNavigationObserver> nav_observer =
test::PrerenderTestHelper::NavigatePrimaryPageAsync(*web_contents(),
navigation_url);
// Wait until the navigation is deferred by CommitDeferringCondition.
ASSERT_TRUE(primary_page_manager.WaitForBeforeChecks());
primary_page_manager.ResumeActivation();
ASSERT_FALSE(host1->were_headers_received());
// The prererender 2 should be destroyed as the prerender 1 is chosen for
// activation.
host_observer2.WaitForDestroyed();
ExpectFinalStatusForSpeculationRule(
PrerenderFinalStatus::kOtherPrerenderedPageActivated);
// Check that PrerenderCommitDeferringCondition is deferring the commit.
NavigationRequest* nav_request =
web_contents_impl()->GetPrimaryFrameTree().root()->navigation_request();
EXPECT_TRUE(nav_request->IsCommitDeferringConditionDeferredForTesting());
// The navigation should not have proceeded past NOT_STARTED because the
// PrerenderCommitDeferringCondition is deferring it.
EXPECT_EQ(nav_request->state(), NavigationRequest::NOT_STARTED);
// Advance the prerender http response 1 by sending headers.
main_prerender_response1.WaitForRequest();
main_prerender_response1.Send(
net::HTTP_OK, /*content_type=*/"text/html", /*content=*/"",
/*cookies=*/{}, /*extra_headers=*/{"No-Vary-Search: params=(\"a\")"});
host_observer1.WaitForHeaders();
ASSERT_TRUE(host1->were_headers_received());
// Make sure that, after receiving headers the prerender host is still a match
// by IsUrlMatch.
ASSERT_TRUE(host1->IsUrlMatch(navigation_url));
main_prerender_response1.Send("Some Content");
main_prerender_response1.Done();
ASSERT_TRUE(primary_page_manager.WaitForAfterChecks());
primary_page_manager.ResumeActivation();
// Wait for the navigation to finish.
nav_observer->Wait();
primary_page_manager.WaitForNavigationFinished();
// Check that the prerender host was activated.
ASSERT_TRUE(host_observer1.was_activated());
histogram_tester().ExpectBucketCount(
"Prerender.Experimental.PrerenderHostFinalStatus.SpeculationRule",
PrerenderFinalStatus::kActivated, 1);
histogram_tester().ExpectTotalCount(
"Prerender.Experimental.WaitingForHeadersFinishedReason.SpeculationRule",
1);
histogram_tester().ExpectUniqueSample(
"Prerender.Experimental.MatchableHostCountOnActivation", 2, 1);
}
// Tests that the speculationrules No-Vary-Search hint is populated for the
// PrerenderHost.
IN_PROC_BROWSER_TEST_F(NoVarySearchPrerenderBrowserTest, HintIsPopulated) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/no_vary_search_a.html?prerender");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
ASSERT_EQ(web_contents()->GetLastCommittedURL(), kInitialUrl);
// Start prerendering `kPrerenderingUrl`.
ASSERT_EQ(GetRequestCount(kPrerenderingUrl), 0);
FrameTreeNodeId host_id =
AddPrerender(kPrerenderingUrl, R"(params=(\\\"a\\\"))");
auto* host =
web_contents_impl()->GetPrerenderHostRegistry()->FindNonReservedHostById(
host_id);
ASSERT_TRUE(host);
ASSERT_TRUE(host->no_vary_search_hint().has_value());
}
// Tests that the speculationrules trigger works in the presence of
// No-Vary-Search for same URL.
IN_PROC_BROWSER_TEST_F(NoVarySearchPrerenderBrowserTest, ExactUrlMatch) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/no_vary_search_a.html?prerender");
const GURL kNavigationUrl = kPrerenderingUrl;
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
ASSERT_EQ(web_contents()->GetLastCommittedURL(), kInitialUrl);
// Start prerendering `kPrerenderingUrl`.
ASSERT_EQ(GetRequestCount(kPrerenderingUrl), 0);
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
ASSERT_TRUE(host_id);
ASSERT_EQ(GetRequestCount(kPrerenderingUrl), 1);
NavigationHandleObserver activation_observer(web_contents(), kNavigationUrl);
NavigatePrimaryPage(kNavigationUrl);
// Ensure the state has been propagated to renderer processes.
ASSERT_EQ(false, EvalJs(web_contents(), "document.prerendering"));
// The prerender host should be consumed.
EXPECT_FALSE(HasHostForUrl(kPrerenderingUrl));
// Activating the prerendered page should not issue a request.
EXPECT_EQ(GetRequestCount(kNavigationUrl), 1);
ExpectFinalStatusForSpeculationRule(PrerenderFinalStatus::kActivated);
ASSERT_EQ(web_contents()->GetLastCommittedURL(), kNavigationUrl);
histogram_tester().ExpectTotalCount(
"Navigation.Prerender.NoVarySearchCommitDeferTime.SpeculationRule", 0);
ukm::SourceId ukm_source_id = activation_observer.next_page_ukm_source_id();
ExpectPreloadingAttemptUkm({attempt_ukm_entry_builder().BuildEntry(
ukm_source_id, PreloadingType::kPrerender,
PreloadingEligibility::kEligible, PreloadingHoldbackStatus::kAllowed,
PreloadingTriggeringOutcome::kSuccess,
PreloadingFailureReason::kUnspecified,
/*accurate=*/true,
/*ready_time=*/kMockElapsedTime,
blink::mojom::SpeculationEagerness::kEager)});
}
// Tests that the speculationrules trigger works in the presence of
// No-Vary-Search.
IN_PROC_BROWSER_TEST_F(NoVarySearchPrerenderBrowserTest, InexactUrlMatch) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/no_vary_search_a.html?prerender");
const GURL kNavigationUrl = GetUrl("/no_vary_search_a.html?prerender&a=3");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
ASSERT_EQ(web_contents()->GetLastCommittedURL(), kInitialUrl);
// Start prerendering `kPrerenderingUrl`.
ASSERT_EQ(GetRequestCount(kPrerenderingUrl), 0);
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
ASSERT_TRUE(host_id);
ASSERT_EQ(GetRequestCount(kPrerenderingUrl), 1);
NavigationHandleObserver activation_observer(web_contents(), kNavigationUrl);
NavigatePrimaryPage(kNavigationUrl);
// Ensure the state has been propagated to renderer processes.
ASSERT_EQ(false, EvalJs(web_contents(), "document.prerendering"));
// The prerender host should be consumed.
EXPECT_FALSE(HasHostForUrl(kPrerenderingUrl));
EXPECT_FALSE(HasHostForUrl(kNavigationUrl));
EXPECT_EQ(GetRequestCount(kPrerenderingUrl), 1);
// Activating the prerendered page should not issue a request.
EXPECT_EQ(GetRequestCount(kNavigationUrl), 0);
ExpectFinalStatusForSpeculationRule(PrerenderFinalStatus::kActivated);
ASSERT_EQ(web_contents()->GetLastCommittedURL(), kNavigationUrl);
ASSERT_EQ(kNavigationUrl, EvalJs(web_contents(), "window.location.href"));
histogram_tester().ExpectTotalCount(
"Navigation.Prerender.NoVarySearchCommitDeferTime.SpeculationRule", 1);
// URL match was inexact but should be recorded as accurate.
ukm::SourceId ukm_source_id = activation_observer.next_page_ukm_source_id();
ExpectPreloadingAttemptUkm({attempt_ukm_entry_builder().BuildEntry(
ukm_source_id, PreloadingType::kPrerender,
PreloadingEligibility::kEligible, PreloadingHoldbackStatus::kAllowed,
PreloadingTriggeringOutcome::kSuccess,
PreloadingFailureReason::kUnspecified,
/*accurate=*/true,
/*ready_time=*/kMockElapsedTime,
blink::mojom::SpeculationEagerness::kEager)});
}
// Tests that the speculationrules trigger works in the presence of
// No-Vary-Search for same URL in the presence of redirection.
IN_PROC_BROWSER_TEST_F(NoVarySearchPrerenderBrowserTest,
ExactMatchWithUrlRedirection) {
// Navigate to an initial page.
const GURL kInitialUrl = GetUrl("/empty.html");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start prerendering a URL that causes same-origin redirection.
const GURL kRedirectedUrl = GetUrl("/no_vary_search_a.html?prerender");
const GURL kPrerenderingUrl =
GetUrl("/server-redirect?" + kRedirectedUrl.spec());
AddPrerender(kPrerenderingUrl);
EXPECT_EQ(GetRequestCount(kPrerenderingUrl), 1);
EXPECT_EQ(GetRequestCount(kRedirectedUrl), 1);
// The prerender host should be registered for the initial request URL, not
// the redirected URL.
EXPECT_TRUE(HasHostForUrl(kPrerenderingUrl));
EXPECT_FALSE(HasHostForUrl(kRedirectedUrl));
NavigationHandleObserver activation_observer(web_contents(),
kPrerenderingUrl);
NavigatePrimaryPage(kPrerenderingUrl);
// Ensure the state has been propagated to renderer processes.
ASSERT_EQ(false, EvalJs(web_contents(), "document.prerendering"));
// The prerender host should be consumed.
EXPECT_FALSE(HasHostForUrl(kPrerenderingUrl));
// Activating the prerendered page should not issue a request.
EXPECT_EQ(GetRequestCount(kPrerenderingUrl), 1);
EXPECT_EQ(GetRequestCount(kRedirectedUrl), 1);
ExpectFinalStatusForSpeculationRule(PrerenderFinalStatus::kActivated);
ASSERT_EQ(web_contents()->GetLastCommittedURL(), kRedirectedUrl);
histogram_tester().ExpectTotalCount(
"Navigation.Prerender.NoVarySearchCommitDeferTime.SpeculationRule", 0);
ukm::SourceId ukm_source_id = activation_observer.next_page_ukm_source_id();
ExpectPreloadingAttemptUkm({attempt_ukm_entry_builder().BuildEntry(
ukm_source_id, PreloadingType::kPrerender,
PreloadingEligibility::kEligible, PreloadingHoldbackStatus::kAllowed,
PreloadingTriggeringOutcome::kSuccess,
PreloadingFailureReason::kUnspecified,
/*accurate=*/true,
/*ready_time=*/kMockElapsedTime,
blink::mojom::SpeculationEagerness::kEager)});
}
// Tests that the speculationrules trigger works in the presence of
// No-Vary-Search for inexact URL in the presence of redirection.
IN_PROC_BROWSER_TEST_F(NoVarySearchPrerenderBrowserTest,
InexactMatchWithUrlRedirection) {
// Navigate to an initial page.
const GURL kInitialUrl = GetUrl("/empty.html");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start prerendering a URL that causes same-origin redirection.
const GURL kRedirectedUrl = GetUrl("/no_vary_search_a.html?prerender&a=2");
const GURL kRedirectedUrlWithIgnoredQueryParam =
GetUrl("/no_vary_search_a.html?prerender&a=3");
const GURL kPrerenderingUrl =
GetUrl("/server-redirect?" + kRedirectedUrl.spec());
const GURL kNavigationUrl =
GetUrl("/server-redirect?" + kRedirectedUrlWithIgnoredQueryParam.spec());
AddPrerender(kPrerenderingUrl);
EXPECT_EQ(GetRequestCount(kPrerenderingUrl), 1);
EXPECT_EQ(GetRequestCount(kRedirectedUrl), 1);
// The prerender host should be registered for the initial request URL, not
// the redirected URL.
EXPECT_TRUE(HasHostForUrl(kPrerenderingUrl));
EXPECT_FALSE(HasHostForUrl(kRedirectedUrl));
NavigationHandleObserver activation_observer(web_contents(), kNavigationUrl);
NavigatePrimaryPage(kNavigationUrl);
// Ensure the state has been propagated to renderer processes.
ASSERT_EQ(false, EvalJs(web_contents(), "document.prerendering"));
// The prerender host should be consumed.
EXPECT_FALSE(HasHostForUrl(kPrerenderingUrl));
// Activating the prerendered page should not issue a request.
EXPECT_EQ(GetRequestCount(kPrerenderingUrl), 1);
EXPECT_EQ(GetRequestCount(kRedirectedUrl), 1);
EXPECT_EQ(GetRequestCount(kNavigationUrl), 0);
EXPECT_EQ(GetRequestCount(kRedirectedUrlWithIgnoredQueryParam), 0);
ExpectFinalStatusForSpeculationRule(PrerenderFinalStatus::kActivated);
// Make sure the omnibox URL hasn't been updated to
// kRedirectedUrlWithIgnoredQueryParam because we've used at navigation
// the already redirected prerender renderer.
ASSERT_EQ(web_contents()->GetLastCommittedURL(), kRedirectedUrl);
ASSERT_EQ(kRedirectedUrl, EvalJs(web_contents(), "window.location.href"));
histogram_tester().ExpectTotalCount(
"Navigation.Prerender.NoVarySearchCommitDeferTime.SpeculationRule", 0);
// URL match was inexact but should be recorded as accurate.
ukm::SourceId ukm_source_id = activation_observer.next_page_ukm_source_id();
ExpectPreloadingAttemptUkm({attempt_ukm_entry_builder().BuildEntry(
ukm_source_id, PreloadingType::kPrerender,
PreloadingEligibility::kEligible, PreloadingHoldbackStatus::kAllowed,
PreloadingTriggeringOutcome::kSuccess,
PreloadingFailureReason::kUnspecified,
/*accurate=*/true,
/*ready_time=*/kMockElapsedTime,
blink::mojom::SpeculationEagerness::kEager)});
}
// Tests that the speculationrules trigger works in the presence of
// No-Vary-Search for inexact URL in the presence of main frame navigation.
IN_PROC_BROWSER_TEST_F(NoVarySearchPrerenderBrowserTest,
InexactUrlMatchWithMainFrameNavigation) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/no_vary_search_a.html?prerender");
const GURL kPrerenderingNextUrl = GetUrl("/empty.html?next");
const GURL kNavigationUrl = GetUrl("/no_vary_search_a.html?prerender&a=3");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
ASSERT_EQ(web_contents()->GetLastCommittedURL(), kInitialUrl);
// Start prerendering `kPrerenderingUrl`.
ASSERT_EQ(GetRequestCount(kPrerenderingUrl), 0);
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
ASSERT_TRUE(host_id);
ASSERT_EQ(GetRequestCount(kPrerenderingUrl), 1);
// Navigate the prerendered page to `kPrerenderingNextUrl`.
NavigatePrerenderedPage(host_id, kPrerenderingNextUrl);
WaitForPrerenderLoadCompletion(host_id);
NavigationHandleObserver activation_observer(web_contents(), kNavigationUrl);
NavigatePrimaryPage(kNavigationUrl);
// Ensure the state has been propagated to renderer processes.
ASSERT_EQ(false, EvalJs(web_contents(), "document.prerendering"));
// The prerender host should be consumed.
EXPECT_FALSE(HasHostForUrl(kPrerenderingUrl));
EXPECT_FALSE(HasHostForUrl(kNavigationUrl));
EXPECT_EQ(GetRequestCount(kPrerenderingUrl), 1);
EXPECT_EQ(GetRequestCount(kPrerenderingNextUrl), 1);
// Activating the prerendered page should not issue a request.
EXPECT_EQ(GetRequestCount(kNavigationUrl), 0);
ExpectFinalStatusForSpeculationRule(PrerenderFinalStatus::kActivated);
ASSERT_EQ(web_contents()->GetLastCommittedURL(), kPrerenderingNextUrl);
ASSERT_EQ(kPrerenderingNextUrl,
EvalJs(web_contents(), "window.location.href"));
// URL match was inexact but should be recorded as accurate.
ukm::SourceId ukm_source_id = activation_observer.next_page_ukm_source_id();
ExpectPreloadingAttemptUkm({attempt_ukm_entry_builder().BuildEntry(
ukm_source_id, PreloadingType::kPrerender,
PreloadingEligibility::kEligible, PreloadingHoldbackStatus::kAllowed,
PreloadingTriggeringOutcome::kSuccess,
PreloadingFailureReason::kUnspecified,
/*accurate=*/true,
/*ready_time=*/kMockElapsedTime,
blink::mojom::SpeculationEagerness::kEager)});
}
// Tests that the speculationrules trigger works.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, SpeculationRulesPrerender) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/empty.html?prerender");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
ASSERT_EQ(web_contents()->GetLastCommittedURL(), kInitialUrl);
// Start prerendering `kPrerenderingUrl`.
ASSERT_EQ(GetRequestCount(kPrerenderingUrl), 0);
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
ASSERT_TRUE(host_id);
ASSERT_EQ(GetRequestCount(kPrerenderingUrl), 1);
NavigationHandleObserver activation_observer(web_contents(),
kPrerenderingUrl);
NavigatePrimaryPage(kPrerenderingUrl);
// Ensure the state has been propagated to renderer processes.
ASSERT_EQ(false, EvalJs(web_contents(), "document.prerendering"));
// The prerender host should be consumed.
EXPECT_FALSE(HasHostForUrl(kPrerenderingUrl));
// Activating the prerendered page should not issue a request.
EXPECT_EQ(GetRequestCount(kPrerenderingUrl), 1);
ExpectFinalStatusForSpeculationRule(PrerenderFinalStatus::kActivated);
{
// Cross-check that both Preloading_Prediction and Preloading_Attempt UKMs
// are logged on successful activation for speculation rules prerender.
ukm::SourceId ukm_source_id = activation_observer.next_page_ukm_source_id();
auto attempt_ukm_entries = test_ukm_recorder()->GetEntries(
Preloading_Attempt::kEntryName, test::kPreloadingAttemptUkmMetrics);
auto prediction_ukm_entries =
test_ukm_recorder()->GetEntries(Preloading_Prediction::kEntryName,
test::kPreloadingPredictionUkmMetrics);
EXPECT_EQ(prediction_ukm_entries.size(), 1u);
EXPECT_EQ(attempt_ukm_entries.size(), 1u);
auto prerender_page_load_ukm_entries =
test_ukm_recorder()->GetEntriesByName(
ukm::builders::PrerenderPageLoad::kEntryName);
// Check that Preloading_Attempt, Preloading_Prediction and
// PrerenderPageLoad are all associated with the same SourceId.
// There are three navigations
// 1) Navigation to initial Url
// 2) Navigation inside prerender frame tree
// 3) Prerender activation navigation => navigation_ids_[2].
// activation_id represents the SourceId for activation navigation. Check
// that all the UKM events are logged for this SourceId.
ukm::SourceId activation_id = ToSourceId(navigation_ids_[2]);
EXPECT_EQ(activation_id, prerender_page_load_ukm_entries.back()->source_id);
EXPECT_EQ(activation_id, prediction_ukm_entries.back().source_id);
EXPECT_EQ(activation_id, attempt_ukm_entries.back().source_id);
ExpectPreloadingAttemptUkm({attempt_ukm_entry_builder().BuildEntry(
activation_id, PreloadingType::kPrerender,
PreloadingEligibility::kEligible, PreloadingHoldbackStatus::kAllowed,
PreloadingTriggeringOutcome::kSuccess,
PreloadingFailureReason::kUnspecified,
/*accurate=*/true,
/*ready_time=*/kMockElapsedTime,
blink::mojom::SpeculationEagerness::kEager)});
ExpectPreloadingPredictionUkm({prediction_ukm_entry_builder().BuildEntry(
ukm_source_id,
/*confidence=*/100,
/*accurate_prediction=*/true)});
}
// Collect metrics we recorded the renderer processes.
FetchHistogramsFromChildProcesses();
histogram_tester().ExpectTotalCount(
"Prerender.Experimental.ActivationIPCDelay.SpeculationRule", 1u);
}
// Used for running tests that should commonly pass regardless of target hints.
class PrerenderTargetAgnosticBrowserTest
: public PrerenderBrowserTest,
public testing::WithParamInterface<std::string> {
public:
PrerenderTargetAgnosticBrowserTest() {
// Explicitly enables blink::features::kPrerender2InNewTab to override
// SpeculationRulesTargetHint.
feature_list_.InitAndEnableFeature(blink::features::kPrerender2InNewTab);
}
// Activates a prerendered page for `url` hosted on `prerender_web_contents`.
void ActivatePrerenderedPage(WebContents& prerender_web_contents,
const GURL& url) {
test::PrerenderHostObserver prerender_observer(prerender_web_contents, url);
if (GetTargetHint() == "_blank") {
TestNavigationObserver observer(&prerender_web_contents);
test::PrerenderTestHelper::OpenNewWindowWithoutOpener(*web_contents(),
url);
observer.WaitForNavigationFinished();
} else {
test::PrerenderTestHelper::NavigatePrimaryPage(*web_contents(), url);
}
ASSERT_TRUE(prerender_observer.was_activated());
}
protected:
std::string GetTargetHint() { return GetParam(); }
private:
base::test::ScopedFeatureList feature_list_;
};
INSTANTIATE_TEST_SUITE_P(All,
PrerenderTargetAgnosticBrowserTest,
testing::Values("_self", "_blank"),
[](const testing::TestParamInfo<std::string>& info) {
return info.param;
});
class AutoSpeculationRulesPrerenderBrowserTest : public PrerenderBrowserTest {
public:
AutoSpeculationRulesPrerenderBrowserTest() {
sub_feature_list_.InitAndEnableFeatureWithParameters(
blink::features::kAutoSpeculationRules, {{"config", GetConfig()}});
}
protected:
void SetUp() override {
ssl_server().RegisterRequestHandler(base::BindLambdaForTesting(
[&](const net::test_server::HttpRequest& request)
-> std::unique_ptr<net::test_server::HttpResponse> {
if (request.relative_url == kInitialUrlPath) {
auto response =
std::make_unique<net::test_server::BasicHttpResponse>();
response->set_code(net::HTTP_OK);
response->set_content_type("text/html");
// This will trigger the auto speculation rules configured in
// SetUp().
response->set_content(
"<!DOCTYPE html><main data-reactroot></main>");
return response;
}
return nullptr;
}));
PrerenderBrowserTest::SetUp();
}
PreloadingPredictor PredictorToExpectInUkm() override {
return content_preloading_predictor::
kSpeculationRulesFromAutoSpeculationRules;
}
GURL GetInitialUrl() const { return GetUrl(kInitialUrlPath); }
GURL GetPrerenderedUrl() const { return GetUrl(kPrerenderedUrlPath); }
std::string GetConfig() const {
// JavaScriptFramework::kReact is 9, and it is detected by the presence of
// data-reactroot attributes.
return base::StringPrintf(R"(
{
"framework_to_speculation_rules": {
"9": "{\"prerender\":[{\"source\":\"list\", \"urls\":[\"%s\"]}]}"
}
}
)",
kPrerenderedUrlPath);
}
private:
base::test::ScopedFeatureList sub_feature_list_;
static constexpr char kInitialUrlPath[] = "/start.html";
static constexpr char kPrerenderedUrlPath[] = "/empty.html?prerender";
};
class AutoSpeculationRulesPrerenderBrowserTestWithHoldback
: public AutoSpeculationRulesPrerenderBrowserTest {
public:
AutoSpeculationRulesPrerenderBrowserTestWithHoldback() {
sub_feature_list_.InitAndEnableFeatureWithParameters(
blink::features::kAutoSpeculationRules,
{{"config", GetConfig()}, {"holdback", "true"}});
}
private:
base::test::ScopedFeatureList sub_feature_list_;
};
IN_PROC_BROWSER_TEST_F(AutoSpeculationRulesPrerenderBrowserTest, Metrics) {
const GURL kInitialUrl = GetInitialUrl();
const GURL kPrerenderingUrl = GetPrerenderedUrl();
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
WaitForPrerenderLoadCompletion(kPrerenderingUrl);
ASSERT_EQ(GetRequestCount(kPrerenderingUrl), 1);
NavigationHandleObserver activation_observer(web_contents(),
kPrerenderingUrl);
NavigatePrimaryPage(kPrerenderingUrl);
// Ensure the state has been propagated to renderer processes.
ASSERT_EQ(false, EvalJs(web_contents(), "document.prerendering"));
// The prerender host should be consumed.
EXPECT_FALSE(HasHostForUrl(kPrerenderingUrl));
// Activating the prerendered page should not issue a request.
EXPECT_EQ(GetRequestCount(kPrerenderingUrl), 1);
// Check UMA final status
ExpectFinalStatusForSpeculationRuleFromAutoSpeculationRules(
PrerenderFinalStatus::kActivated);
// Check UKM metrics, the same as in the
// PrerenderBrowserTest.SpeculationRulesPrerender test except the predictor is
// overridden by the AutoSpeculationRulesPrerenderBrowserTest class.
{
// Cross-check that both Preloading_Prediction and Preloading_Attempt UKMs
// are logged on successful activation for speculation rules prerender.
ukm::SourceId ukm_source_id = activation_observer.next_page_ukm_source_id();
auto attempt_ukm_entries = test_ukm_recorder()->GetEntries(
Preloading_Attempt::kEntryName, test::kPreloadingAttemptUkmMetrics);
auto prediction_ukm_entries =
test_ukm_recorder()->GetEntries(Preloading_Prediction::kEntryName,
test::kPreloadingPredictionUkmMetrics);
EXPECT_EQ(prediction_ukm_entries.size(), 1u);
EXPECT_EQ(attempt_ukm_entries.size(), 1u);
auto prerender_page_load_ukm_entries =
test_ukm_recorder()->GetEntriesByName(
ukm::builders::PrerenderPageLoad::kEntryName);
ukm::SourceId activation_id = ToSourceId(navigation_ids_[2]);
EXPECT_EQ(activation_id, prerender_page_load_ukm_entries.back()->source_id);
EXPECT_EQ(activation_id, prediction_ukm_entries.back().source_id);
EXPECT_EQ(activation_id, attempt_ukm_entries.back().source_id);
ExpectPreloadingAttemptUkm({attempt_ukm_entry_builder().BuildEntry(
activation_id, PreloadingType::kPrerender,
PreloadingEligibility::kEligible, PreloadingHoldbackStatus::kAllowed,
PreloadingTriggeringOutcome::kSuccess,
PreloadingFailureReason::kUnspecified,
/*accurate=*/true,
/*ready_time=*/kMockElapsedTime,
blink::mojom::SpeculationEagerness::kEager)});
ExpectPreloadingPredictionUkm({prediction_ukm_entry_builder().BuildEntry(
ukm_source_id,
/*confidence=*/100,
/*accurate_prediction=*/true)});
}
}
IN_PROC_BROWSER_TEST_F(AutoSpeculationRulesPrerenderBrowserTestWithHoldback,
Metrics) {
const GURL kInitialUrl = GetInitialUrl();
const GURL kPrerenderingUrl = GetPrerenderedUrl();
test::PrerenderHostRegistryObserver registry_observer(*web_contents_impl());
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Wait for PrerenderHostRegistry to receive the holdback prerender
// request, and it should be ignored.
registry_observer.WaitForTrigger(kPrerenderingUrl);
EXPECT_FALSE(HasHostForUrl(kPrerenderingUrl));
EXPECT_EQ(GetRequestCount(kPrerenderingUrl), 0);
NavigationHandleObserver next_page_observer(web_contents(), kPrerenderingUrl);
NavigatePrimaryPage(kPrerenderingUrl);
// No final status for holdbacks.
// Check UKM metrics: similar to the non-holdback case, except for the
// holdback status and no prerender page load entries.
{
// Cross-check that both Preloading_Prediction and Preloading_Attempt UKMs
// are logged on successful activation for speculation rules prerender.
ukm::SourceId ukm_source_id = next_page_observer.next_page_ukm_source_id();
auto attempt_ukm_entries = test_ukm_recorder()->GetEntries(
Preloading_Attempt::kEntryName, test::kPreloadingAttemptUkmMetrics);
auto prediction_ukm_entries =
test_ukm_recorder()->GetEntries(Preloading_Prediction::kEntryName,
test::kPreloadingPredictionUkmMetrics);
EXPECT_EQ(prediction_ukm_entries.size(), 1u);
EXPECT_EQ(attempt_ukm_entries.size(), 1u);
auto prerender_page_load_ukm_entries =
test_ukm_recorder()->GetEntriesByName(
ukm::builders::PrerenderPageLoad::kEntryName);
ukm::SourceId next_page_id = ToSourceId(navigation_ids_[1]);
EXPECT_TRUE(prerender_page_load_ukm_entries.empty());
EXPECT_EQ(prediction_ukm_entries.back().source_id, next_page_id);
EXPECT_EQ(attempt_ukm_entries.back().source_id, next_page_id);
ExpectPreloadingAttemptUkm({attempt_ukm_entry_builder().BuildEntry(
next_page_id, PreloadingType::kPrerender,
PreloadingEligibility::kEligible, PreloadingHoldbackStatus::kHoldback,
PreloadingTriggeringOutcome::kUnspecified,
PreloadingFailureReason::kUnspecified,
/*accurate=*/true,
/*ready_time=*/std::nullopt,
blink::mojom::SpeculationEagerness::kEager)});
ExpectPreloadingPredictionUkm({prediction_ukm_entry_builder().BuildEntry(
ukm_source_id,
/*confidence=*/100,
/*accurate_prediction=*/true)});
}
}
enum class PrerenderingResult { kSuccess, kFailed };
enum class BodySize { kSmall, kLarge };
class PrerenderAndPrefetchBrowserTest
: public PrerenderBrowserTest,
public testing::WithParamInterface<
std::tuple<PrerenderingResult, BodySize, PrefetchReusableForTests>> {
public:
// Provides meaningful param names instead of /0, /1, ...
static std::string DescribeParams(
const testing::TestParamInfo<ParamType>& info) {
auto [prerendering_result, body_size, prefetch_reusable] = info.param;
std::stringstream params_description;
switch (prerendering_result) {
case PrerenderingResult::kSuccess:
params_description << "PrerenderSucceeded";
break;
case PrerenderingResult::kFailed:
params_description << "PrerenderFailed";
break;
}
switch (body_size) {
case BodySize::kSmall:
params_description << "_SmallBody";
break;
case BodySize::kLarge:
params_description << "_LargeBody";
break;
}
switch (prefetch_reusable) {
case PrefetchReusableForTests::kEnabled:
params_description << "_PrefetchReusableEnabled";
break;
case PrefetchReusableForTests::kDisabled:
params_description << "_PrefetchReusableDisabled";
break;
}
return params_description.str();
}
private:
void SetUp() override {
std::vector<base::test::FeatureRefAndParams> enabled_features;
std::vector<base::test::FeatureRef> disabled_features;
switch (std::get<PrefetchReusableForTests>(GetParam())) {
case PrefetchReusableForTests::kDisabled:
disabled_features.push_back(features::kPrefetchReusable);
break;
case PrefetchReusableForTests::kEnabled:
// Set the limit to the size of `/cacheable_long.html` - 1, to check
// that exceeding the limit by 1 byte disallows reuse.
enabled_features.push_back(
{features::kPrefetchReusable,
{{features::kPrefetchReusableBodySizeLimit.name, "102118"}}});
break;
}
sub_feature_list_.InitWithFeaturesAndParameters(enabled_features,
disabled_features);
PrerenderBrowserTest::SetUp();
}
void TearDown() override {
PrerenderBrowserTest::TearDown();
sub_feature_list_.Reset();
}
base::test::ScopedFeatureList sub_feature_list_;
};
IN_PROC_BROWSER_TEST_P(PrerenderAndPrefetchBrowserTest,
SpeculationRulesPrefetchThenPrerender) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = std::get<1>(GetParam()) == BodySize::kSmall
? GetUrl("/cacheable.html?prerender")
: GetUrl("/cacheable_long.html?prerender");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
ASSERT_EQ(web_contents()->GetLastCommittedURL(), kInitialUrl);
// Start prefetching `kPrerenderingUrl` and wait for its completion.
PrefetchService* prefetch_service = PrefetchService::GetFromFrameTreeNodeId(
current_frame_host()->GetFrameTreeNodeId());
ASSERT_TRUE(prefetch_service);
base::RunLoop run_loop;
PrefetchContainer::SetPrefetchResponseCompletedCallbackForTesting(
base::BindRepeating(
[](base::RunLoop* run_loop, const GURL& url,
base::WeakPtr<PrefetchContainer> prefetch_container) {
CHECK(prefetch_container);
CHECK_EQ(prefetch_container->GetURL(), url);
run_loop->Quit();
},
&run_loop, kPrerenderingUrl));
ASSERT_EQ(GetRequestCount(kPrerenderingUrl), 0);
AddPrefetchAsync(kPrerenderingUrl);
run_loop.Run();
ASSERT_EQ(GetRequestCount(kPrerenderingUrl), 1);
// Start prerendering `kPrerenderingUrl`.
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
ASSERT_TRUE(host_id);
ASSERT_EQ(GetRequestCount(kPrerenderingUrl), 1);
switch (std::get<0>(GetParam())) {
case PrerenderingResult::kSuccess:
EXPECT_TRUE(HasHostForUrl(kPrerenderingUrl));
break;
case PrerenderingResult::kFailed:
// Cancel prerendered page.
ASSERT_TRUE(web_contents_impl()->CancelPrerendering(
FrameTreeNode::GloballyFindByID(host_id),
PrerenderFinalStatus::kCancelAllHostsForTesting));
EXPECT_FALSE(HasHostForUrl(kPrerenderingUrl));
break;
}
// Start main navigation.
NavigationHandleObserver activation_observer(web_contents(),
kPrerenderingUrl);
NavigatePrimaryPage(kPrerenderingUrl);
auto delivery_type =
EvalJs(web_contents()->GetPrimaryMainFrame(),
"performance.getEntriesByType('navigation')[0].deliveryType");
switch (std::get<0>(GetParam())) {
case PrerenderingResult::kSuccess:
// Main navigation activates the prerendered page even for the large page.
ExpectFinalStatusForSpeculationRule(PrerenderFinalStatus::kActivated);
EXPECT_EQ(GetRequestCount(kPrerenderingUrl), 1);
EXPECT_EQ(delivery_type, "navigational-prefetch");
break;
case PrerenderingResult::kFailed:
// Main navigation shouldn't activate prerendered page (because it's
// canceled).
ExpectFinalStatusForSpeculationRule(
PrerenderFinalStatus::kCancelAllHostsForTesting);
if (std::get<1>(GetParam()) == BodySize::kSmall &&
std::get<2>(GetParam()) == PrefetchReusableForTests::kEnabled) {
// The prefetched result should be still used for navigation for small
// body, because it fits within PrefetchDataPipeTee buffer limit.
EXPECT_EQ(GetRequestCount(kPrerenderingUrl), 1);
EXPECT_EQ(delivery_type, "navigational-prefetch");
} else {
// The prefetched result can't be used for navigation for large body
// due to PrefetchDataPipeTee buffer limit. A cached response from the
// HTTP cache is used instead, we still should not see another request.
EXPECT_EQ(GetRequestCount(kPrerenderingUrl), 1);
EXPECT_EQ(delivery_type, "cache");
}
break;
}
switch (std::get<1>(GetParam())) {
case BodySize::kSmall:
EXPECT_EQ(GetBodyTextContent(), "This page is cacheable");
break;
case BodySize::kLarge:
// `document.body.textContent.trim().length` for
// `/find_in_long_page.html`
EXPECT_EQ(GetBodyTextContent().size(), 102119u);
break;
}
}
INSTANTIATE_TEST_SUITE_P(
/* no prefix */,
PrerenderAndPrefetchBrowserTest,
testing::Combine(testing::Values(PrerenderingResult::kSuccess,
PrerenderingResult::kFailed),
testing::Values(BodySize::kSmall, BodySize::kLarge),
testing::ValuesIn(PrefetchReusableValuesForTests())),
PrerenderAndPrefetchBrowserTest::DescribeParams);
// Tests that the speculationrules-triggered prerender would be destroyed after
// its initiator navigates away.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, SpeculationInitiatorNavigateAway) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/empty.html?prerender");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
// Navigate the initiator page to a non-prerendered page. This destroys the
// prerendered page.
test::PrerenderHostObserver host_observer(*web_contents_impl(), host_id);
NavigatePrimaryPage(GetUrl("/empty.html?elsewhere"));
host_observer.WaitForDestroyed();
// The prerender host should be destroyed.
EXPECT_FALSE(HasHostForUrl(kPrerenderingUrl));
// Cross-check that in case where the navigation happens to a different page,
// we log the correct metrics.
ukm::SourceId ukm_source_id = PrimaryPageSourceId();
ExpectPreloadingAttemptUkm({attempt_ukm_entry_builder().BuildEntry(
ukm_source_id, PreloadingType::kPrerender,
PreloadingEligibility::kEligible, PreloadingHoldbackStatus::kAllowed,
PreloadingTriggeringOutcome::kReady,
PreloadingFailureReason::kUnspecified,
/*accurate=*/false,
/*ready_time=*/kMockElapsedTime,
blink::mojom::SpeculationEagerness::kEager)});
ExpectPreloadingPredictionUkm({prediction_ukm_entry_builder().BuildEntry(
ukm_source_id, /*confidence=*/100,
/*accurate_prediction=*/false)});
}
// Tests that clicking a link can activate a prerender.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, ActivateOnLinkClick) {
const GURL kInitialUrl = GetUrl("/simple_links.html");
const GURL kPrerenderingUrl = GetUrl("/title2.html");
// Navigate to an initial page which has a link to `kPrerenderingUrl`.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start prerendering `kPrerenderingUrl`.
FrameTreeNodeId prerender_host_id = AddPrerender(kPrerenderingUrl);
test::PrerenderHostObserver prerender_observer(*web_contents(),
prerender_host_id);
// Click the link. It should activate the prerendered page.
TestNavigationObserver nav_observer(web_contents());
const std::string kLinkClickScript = R"(
const link = document.querySelector('#same_site_link');
link.click();
)";
EXPECT_TRUE(ExecJs(web_contents(), kLinkClickScript));
nav_observer.WaitForNavigationFinished();
EXPECT_EQ(web_contents()->GetLastCommittedURL(), kPrerenderingUrl);
EXPECT_TRUE(prerender_observer.was_activated());
}
// Tests that clicking a link annotated with "target=_blank" cannot activate a
// prerender.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, ActivateOnLinkClick_TargetBlank) {
const GURL kInitialUrl = GetUrl("/simple_links.html");
const GURL kPrerenderingUrl = GetUrl("/title2.html");
// Navigate to an initial page which has a link to `kPrerenderingUrl`.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start prerendering `kPrerenderingUrl`.
FrameTreeNodeId prerender_host_id = AddPrerender(kPrerenderingUrl);
test::PrerenderHostObserver prerender_observer(*web_contents(),
prerender_host_id);
// Click the link annotated with "target=_blank". This should not activate the
// prerendered page.
TestNavigationObserver nav_observer(kPrerenderingUrl);
nav_observer.StartWatchingNewWebContents();
const std::string kLinkClickScript = R"(
clickSameSiteNewWindowLink();
)";
EXPECT_TRUE(ExecJs(web_contents(), kLinkClickScript));
nav_observer.WaitForNavigationFinished();
EXPECT_EQ(nav_observer.last_navigation_url(), kPrerenderingUrl);
EXPECT_FALSE(prerender_observer.was_activated());
// The navigation occurred in a new WebContents, so the original WebContents
// should still be showing the initial trigger page.
EXPECT_EQ(web_contents()->GetLastCommittedURL(), kInitialUrl);
// Also, the prerendered page should still be alive.
EXPECT_TRUE(HasHostForUrl(kPrerenderingUrl));
// Navigate to `kPrerenderingUrl` on the original WebContents. This should
// activate the prerendered page.
NavigatePrimaryPage(kPrerenderingUrl);
EXPECT_EQ(web_contents()->GetLastCommittedURL(), kPrerenderingUrl);
EXPECT_TRUE(prerender_observer.was_activated());
ExpectFinalStatusForSpeculationRule(PrerenderFinalStatus::kActivated);
}
class PrerenderTargetHintEnabledBrowserTest : public PrerenderBrowserTest {
public:
PrerenderTargetHintEnabledBrowserTest() {
// Explicitly enables blink::features::kPrerender2InNewTab to override
// SpeculationRulesTargetHint.
feature_list_.InitAndEnableFeature(blink::features::kPrerender2InNewTab);
}
void TestActivateOnWindowOpen(std::string_view window_features);
private:
base::test::ScopedFeatureList feature_list_;
};
// Tests that clicking a link annotated with "target=_blank" can activate a
// prerender whose target_hint is "_blank".
IN_PROC_BROWSER_TEST_F(PrerenderTargetHintEnabledBrowserTest,
ActivateOnLinkClick_TargetBlank_WithTargetHintBlank) {
const GURL kInitialUrl = GetUrl("/simple_links.html");
const GURL kPrerenderingUrl = GetUrl("/title2.html");
// Navigate to an initial page which has a link to `kPrerenderingUrl`.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start prerendering `kPrerenderingUrl`.
FrameTreeNodeId host_id = prerender_helper()->AddPrerender(
kPrerenderingUrl, /*eagerness=*/std::nullopt, "_blank");
auto* prerender_web_contents = WebContents::FromFrameTreeNodeId(host_id);
ASSERT_NE(prerender_web_contents, web_contents_impl());
ExpectWebContentsIsForNewTabPrerendering(*prerender_web_contents);
// Click the link annotated with "target=_blank". This should activate the
// prerendered page.
TestNavigationObserver activation_observer(kPrerenderingUrl);
activation_observer.WatchExistingWebContents();
test::PrerenderHostObserver prerender_observer(*prerender_web_contents,
host_id);
const std::string kLinkClickScript = R"(
clickSameSiteNewWindowLink();
)";
EXPECT_TRUE(ExecJs(web_contents(), kLinkClickScript));
activation_observer.WaitForNavigationFinished();
EXPECT_EQ(prerender_web_contents->GetLastCommittedURL(), kPrerenderingUrl);
EXPECT_EQ(activation_observer.last_navigation_url(), kPrerenderingUrl);
EXPECT_TRUE(prerender_observer.was_activated());
EXPECT_FALSE(HasHostForUrl(kPrerenderingUrl));
ExpectFinalStatusForSpeculationRule(PrerenderFinalStatus::kActivated);
ukm::SourceId ukm_source_id = activation_observer.next_page_ukm_source_id();
ExpectPreloadingAttemptUkm({attempt_ukm_entry_builder().BuildEntry(
ukm_source_id, PreloadingType::kPrerender,
PreloadingEligibility::kEligible, PreloadingHoldbackStatus::kAllowed,
PreloadingTriggeringOutcome::kSuccess,
PreloadingFailureReason::kUnspecified,
/*accurate=*/true,
/*ready_time=*/kMockElapsedTime,
blink::mojom::SpeculationEagerness::kEager)});
ExpectPreloadingPredictionUkm({prediction_ukm_entry_builder().BuildEntry(
ukm_source_id,
/*confidence=*/100,
/*accurate_prediction=*/true)});
// The navigation occurred in a new WebContents, so the original WebContents
// should still be showing the initial trigger page.
EXPECT_EQ(web_contents()->GetLastCommittedURL(), kInitialUrl);
}
// Tests that clicking a link annotated with "target=_blank" does not activate a
// mismatched prerender url whose target_hint is "_blank" and the navigation
// does not cancel the prerender.
IN_PROC_BROWSER_TEST_F(
PrerenderTargetHintEnabledBrowserTest,
DoesNotActivateOnMismatchedLinkClick_TargetBlank_WithTargetHintBlank) {
const GURL initial_url = GetUrl("/simple_links.html");
const GURL prerendering_url = GetUrl("/title2.html?different");
// Navigate to an initial page which has a link other than `prerendering_url`.
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
// Start prerendering `prerendering_url`.
FrameTreeNodeId host_id = prerender_helper()->AddPrerender(
prerendering_url, /*eagerness=*/std::nullopt, "_blank");
auto* prerender_web_contents = WebContents::FromFrameTreeNodeId(host_id);
ASSERT_NE(prerender_web_contents, web_contents_impl());
ExpectWebContentsIsForNewTabPrerendering(*prerender_web_contents);
// Click the link annotated with "target=_blank" but different from the
// prerendered url. This should not activate the prerendered page.
TestNavigationObserver nav_observer(GetUrl("/title2.html"));
nav_observer.StartWatchingNewWebContents();
test::PrerenderHostObserver prerender_observer(*prerender_web_contents,
host_id);
const std::string kLinkClickScript = R"(
clickSameSiteNewWindowLink();
)";
EXPECT_TRUE(ExecJs(web_contents(), kLinkClickScript));
nav_observer.WaitForNavigationFinished();
EXPECT_FALSE(prerender_observer.was_activated());
EXPECT_FALSE(HasHostForUrl(prerendering_url));
// Navigating a different url than the prerendered url into a new tab should
// not cancel the prerender.
EXPECT_TRUE(prerender_helper()->HasNewTabHandle(host_id));
// The navigation occurred in a new WebContents, so the original WebContents
// should still be showing the initial trigger page.
EXPECT_EQ(web_contents()->GetLastCommittedURL(), initial_url);
}
// Tests that using window.open the prerendered url with a customized window
// name cannot activate a prerender whose target_hint is "_blank".
IN_PROC_BROWSER_TEST_F(
PrerenderTargetHintEnabledBrowserTest,
DoesNotActivateOnWindowOpen_WithCustomizedWindowName_WithTargetHintBlank) {
const GURL initial_url = GetUrl("/simple_links.html");
const GURL prerendering_url = GetUrl("/title2.html");
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
// Start prerendering `prerendering_url`.
FrameTreeNodeId host_id = prerender_helper()->AddPrerender(
prerendering_url, /*eagerness=*/std::nullopt, "_blank");
auto* prerender_web_contents = WebContents::FromFrameTreeNodeId(host_id);
ASSERT_NE(prerender_web_contents, web_contents_impl());
ExpectWebContentsIsForNewTabPrerendering(*prerender_web_contents);
// Use window.open a customized window name should not activate
// `prerendering_url`.
TestNavigationObserver nav_observer(prerendering_url);
nav_observer.StartWatchingNewWebContents();
test::PrerenderHostObserver prerender_observer(*prerender_web_contents,
host_id);
std::string window_open_script =
R"(window.open($1, 'WindowName', 'noopener');)";
EXPECT_TRUE(ExecJs(web_contents(),
JsReplace(window_open_script, prerendering_url.spec())));
nav_observer.WaitForNavigationFinished();
EXPECT_FALSE(prerender_observer.was_activated());
// Navigating prerendered url with a customized window name should not cancel
// the prerender.
EXPECT_TRUE(prerender_helper()->HasNewTabHandle(host_id));
// The navigation occurred in a new WebContents, so the original WebContents
// should still be showing the initial trigger page.
EXPECT_EQ(web_contents()->GetLastCommittedURL(), initial_url);
}
// Tests that clicking a link annotated with "target=_blank" can activate a
// prerender whose target_hint is "_blank" where the initiator page is in the
// background when the speculation rules were added.
IN_PROC_BROWSER_TEST_F(
PrerenderTargetHintEnabledBrowserTest,
BackgroundedPage_ActivateOnLinkClick_TargetBlank_WithTargetHintBlank) {
const GURL initial_url = GetUrl("/simple_links.html");
const GURL prerender_url = GetUrl("/title2.html");
// Inject mock time task runner.
auto task_runner = base::MakeRefCounted<base::TestMockTimeTaskRunner>();
PrerenderHostRegistry* registry =
web_contents_impl()->GetPrerenderHostRegistry();
registry->SetTaskRunnerForTesting(task_runner);
// Navigate to an initial page which has a link to `prerender_url`.
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
web_contents()->WasHidden();
// The timers should be still running.
ASSERT_TRUE(registry->GetEmbedderTimerForTesting()->IsRunning());
ASSERT_TRUE(registry->GetSpeculationRulesTimerForTesting()->IsRunning());
// Start prerendering `prerender_url`.
FrameTreeNodeId host_id = prerender_helper()->AddPrerender(
prerender_url, /*eagerness=*/std::nullopt, "_blank");
auto* prerender_web_contents = WebContents::FromFrameTreeNodeId(host_id);
ASSERT_NE(prerender_web_contents, web_contents_impl());
ExpectWebContentsIsForNewTabPrerendering(*prerender_web_contents);
web_contents()->WasShown();
// The timers should be stopped after WasShown().
ASSERT_FALSE(registry->GetEmbedderTimerForTesting()->IsRunning());
ASSERT_FALSE(registry->GetSpeculationRulesTimerForTesting()->IsRunning());
// Forward the time by
// PrerenderHostRegistry::kTimeToLiveInBackgroundForSpeculationRules shouldn't
// affect the prerender.
task_runner->FastForwardBy(
PrerenderHostRegistry::kTimeToLiveInBackgroundForSpeculationRules);
// Click the link annotated with "target=_blank". This should activate the
// prerendered page.
TestNavigationObserver activation_observer(prerender_url);
activation_observer.WatchExistingWebContents();
test::PrerenderHostObserver prerender_observer(*prerender_web_contents,
host_id);
const std::string kLinkClickScript = R"(
clickSameSiteNewWindowLink();
)";
EXPECT_TRUE(ExecJs(web_contents(), kLinkClickScript));
activation_observer.WaitForNavigationFinished();
EXPECT_EQ(prerender_web_contents->GetLastCommittedURL(), prerender_url);
EXPECT_EQ(activation_observer.last_navigation_url(), prerender_url);
EXPECT_TRUE(prerender_observer.was_activated());
EXPECT_FALSE(HasHostForUrl(prerender_url));
ExpectFinalStatusForSpeculationRule(PrerenderFinalStatus::kActivated);
ukm::SourceId ukm_source_id = activation_observer.next_page_ukm_source_id();
ExpectPreloadingAttemptUkm({attempt_ukm_entry_builder().BuildEntry(
ukm_source_id, PreloadingType::kPrerender,
PreloadingEligibility::kEligible, PreloadingHoldbackStatus::kAllowed,
PreloadingTriggeringOutcome::kSuccess,
PreloadingFailureReason::kUnspecified,
/*accurate=*/true,
/*ready_time=*/kMockElapsedTime,
blink::mojom::SpeculationEagerness::kEager)});
ExpectPreloadingPredictionUkm({prediction_ukm_entry_builder().BuildEntry(
ukm_source_id,
/*confidence=*/100,
/*accurate_prediction=*/true)});
// The navigation occurred in a new WebContents, so the original WebContents
// should still be showing the initial trigger page.
EXPECT_EQ(web_contents()->GetLastCommittedURL(), initial_url);
}
// Tests that the prerendering started by a hidden initiator page will be
// canceled after timeout.
// TODO(b/40234240): Flaky on win.
#if BUILDFLAG(IS_WIN)
#define MAYBE_BackgroundedPageTimeout_TargetBlank_WithTargetHintBlank \
DISABLED_BackgroundedPageTimeout_TargetBlank_WithTargetHintBlank
#else
#define MAYBE_BackgroundedPageTimeout_TargetBlank_WithTargetHintBlank \
BackgroundedPageTimeout_TargetBlank_WithTargetHintBlank
#endif
IN_PROC_BROWSER_TEST_F(
PrerenderTargetHintEnabledBrowserTest,
MAYBE_BackgroundedPageTimeout_TargetBlank_WithTargetHintBlank) {
const GURL initial_url = GetUrl("/simple_links.html");
const GURL prerender_url = GetUrl("/title2.html");
// Inject mock time task runner.
auto task_runner = base::MakeRefCounted<base::TestMockTimeTaskRunner>();
PrerenderHostRegistry* registry =
web_contents_impl()->GetPrerenderHostRegistry();
registry->SetTaskRunnerForTesting(task_runner);
// Navigate to an initial page which has a link to `prerender_url`.
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
web_contents()->WasHidden();
// The timers should be still running.
ASSERT_TRUE(registry->GetSpeculationRulesTimerForTesting()->IsRunning());
// Start prerendering `prerender_url`.
FrameTreeNodeId host_id = prerender_helper()->AddPrerender(
prerender_url, /*eagerness=*/std::nullopt, "_blank");
auto* prerender_web_contents = WebContents::FromFrameTreeNodeId(host_id);
ASSERT_NE(prerender_web_contents, web_contents_impl());
ExpectWebContentsIsForNewTabPrerendering(*prerender_web_contents);
test::PrerenderHostObserver prerender_observer(*prerender_web_contents,
host_id);
// Expire the timers.
task_runner->FastForwardBy(
PrerenderHostRegistry::kTimeToLiveInBackgroundForSpeculationRules);
// The timers should cancel prerendering.
prerender_observer.WaitForDestroyed();
histogram_tester().ExpectUniqueSample(
"Prerender.Experimental.PrerenderHostFinalStatus.SpeculationRule",
PrerenderFinalStatus::kTimeoutBackgrounded, 1);
}
IN_PROC_BROWSER_TEST_F(
PrerenderTargetHintEnabledBrowserTest,
PrerenderWhenInitiatorInBackground_Queue_Processing_WithTargetHint) {
ASSERT_TRUE(embedded_test_server()->Start());
const GURL initial_url = embedded_test_server()->GetURL("/empty.html");
const GURL prerender_url1 =
embedded_test_server()->GetURL("/empty.html?prerender1");
const GURL prerender_url2 =
embedded_test_server()->GetURL("/empty.html?prerender2");
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
web_contents()->WasHidden();
// Insert 2 URLs into the speculation rules at the same time.
WebContents* prerender_web_contents = nullptr;
WebContents* prerender2_web_contents = nullptr;
base::RunLoop run_loop;
auto creation_subscription = RegisterWebContentsCreationCallback(
base::BindLambdaForTesting([&](WebContents* web_contents) {
if (prerender_web_contents == nullptr) {
prerender_web_contents = web_contents;
} else {
prerender2_web_contents = web_contents;
}
run_loop.QuitClosure().Run();
}));
AddPrerendersAsync({prerender_url1, prerender_url2},
/*eagerness=*/std::nullopt,
/*target_hint=*/"_blank");
run_loop.Run();
ExpectWebContentsIsForNewTabPrerendering(*prerender_web_contents);
// Check the prerender host is already ready.
prerender_helper()->WaitForPrerenderLoadCompletion(*prerender_web_contents,
prerender_url1);
PrerenderHost* prerender_host =
static_cast<WebContentsImpl*>(prerender_web_contents)
->GetPrerenderHostRegistry()
->FindHostByUrlForTesting(prerender_url1);
auto* preloading_attempt_impl = static_cast<PreloadingAttemptImpl*>(
prerender_host->preloading_attempt().get());
EXPECT_EQ(test::PreloadingAttemptAccessor(preloading_attempt_impl)
.GetTriggeringOutcome(),
PreloadingTriggeringOutcome::kReady);
// Currently, prerender_url2 will be cancelled since there is no queue
// mechanism for prerender-into-new-tab yet.
// TODO(crbug.com/350785853): Add queue mechanism and
// update test expectation.
ExpectFinalStatusForSpeculationRule(
PrerenderFinalStatus::kTabClosedWithoutUserGesture);
}
// Tests that clicking a link annotated with "target=_blank rel=noopener" cannot
// activate a prerender.
IN_PROC_BROWSER_TEST_F(PrerenderTargetHintEnabledBrowserTest,
ActivateOnLinkClick_TargetBlankWithNoopener) {
const GURL kInitialUrl = GetUrl("/simple_links.html");
const GURL kPrerenderingUrl = GetUrl("/title2.html");
// Navigate to an initial page which has a link to `kPrerenderingUrl`.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start prerendering `kPrerenderingUrl`.
FrameTreeNodeId prerender_host_id = AddPrerender(kPrerenderingUrl);
test::PrerenderHostObserver prerender_observer(*web_contents(),
prerender_host_id);
// Click the link annotated with "target=_blank rel=noopener". This should not
// activate the prerendered page.
TestNavigationObserver nav_observer(kPrerenderingUrl);
nav_observer.StartWatchingNewWebContents();
const std::string kLinkClickScript = R"(
clickSameSiteNewWindowWithNoopenerLink();
)";
EXPECT_TRUE(ExecJs(web_contents(), kLinkClickScript));
nav_observer.WaitForNavigationFinished();
EXPECT_EQ(nav_observer.last_navigation_url(), kPrerenderingUrl);
EXPECT_FALSE(prerender_observer.was_activated());
// The navigation occurred in a new WebContents, so the original WebContents
// should still be showing the initial trigger page.
EXPECT_EQ(web_contents()->GetLastCommittedURL(), kInitialUrl);
// Also, the prerendered page should still be alive.
EXPECT_TRUE(HasHostForUrl(kPrerenderingUrl));
// Navigate to `kPrerenderingUrl` on the original WebContents. This should
// activate the prerendered page.
NavigatePrimaryPage(kPrerenderingUrl);
EXPECT_EQ(web_contents()->GetLastCommittedURL(), kPrerenderingUrl);
EXPECT_TRUE(prerender_observer.was_activated());
ExpectFinalStatusForSpeculationRule(PrerenderFinalStatus::kActivated);
}
// Tests that clicking a link annotated with "target=_blank rel=noopener" can
// activate a prerender whose target_hint is "_blank".
IN_PROC_BROWSER_TEST_F(
PrerenderTargetHintEnabledBrowserTest,
ActivateOnLinkClick_TargetBlankWithNoopener_WithTargetHintBlank) {
const GURL kInitialUrl = GetUrl("/simple_links.html");
const GURL kPrerenderingUrl = GetUrl("/title2.html");
// Navigate to an initial page which has a link to `kPrerenderingUrl`.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start prerendering `kPrerenderingUrl`.
FrameTreeNodeId host_id = prerender_helper()->AddPrerender(
kPrerenderingUrl, /*eagerness=*/std::nullopt, "_blank");
auto* prerender_web_contents = WebContents::FromFrameTreeNodeId(host_id);
ASSERT_NE(prerender_web_contents, web_contents_impl());
ExpectWebContentsIsForNewTabPrerendering(*prerender_web_contents);
// Click the link annotated with "target=_blank rel=noopener". This should
// activate the prerendered page.
TestNavigationObserver activation_observer(kPrerenderingUrl);
activation_observer.WatchExistingWebContents();
test::PrerenderHostObserver prerender_observer(*prerender_web_contents,
host_id);
const std::string kLinkClickScript = R"(
clickSameSiteNewWindowWithNoopenerLink();
)";
EXPECT_TRUE(ExecJs(web_contents(), kLinkClickScript));
activation_observer.WaitForNavigationFinished();
EXPECT_EQ(prerender_web_contents->GetLastCommittedURL(), kPrerenderingUrl);
EXPECT_EQ(activation_observer.last_navigation_url(), kPrerenderingUrl);
EXPECT_EQ(prerender_web_contents->GetLastCommittedURL(), kPrerenderingUrl);
EXPECT_TRUE(prerender_observer.was_activated());
EXPECT_FALSE(HasHostForUrl(kPrerenderingUrl));
ExpectFinalStatusForSpeculationRule(PrerenderFinalStatus::kActivated);
ukm::SourceId ukm_source_id = activation_observer.next_page_ukm_source_id();
ExpectPreloadingAttemptUkm({attempt_ukm_entry_builder().BuildEntry(
ukm_source_id, PreloadingType::kPrerender,
PreloadingEligibility::kEligible, PreloadingHoldbackStatus::kAllowed,
PreloadingTriggeringOutcome::kSuccess,
PreloadingFailureReason::kUnspecified,
/*accurate=*/true,
/*ready_time=*/kMockElapsedTime,
blink::mojom::SpeculationEagerness::kEager)});
ExpectPreloadingPredictionUkm({prediction_ukm_entry_builder().BuildEntry(
ukm_source_id,
/*confidence=*/100,
/*accurate_prediction=*/true)});
// The navigation occurred in a new WebContents, so the original WebContents
// should still be showing the initial trigger page.
EXPECT_EQ(web_contents()->GetLastCommittedURL(), kInitialUrl);
}
// Tests that clicking a link annotated with "target=_blank rel=opener" cannot
// activate a prerender.
IN_PROC_BROWSER_TEST_F(PrerenderTargetHintEnabledBrowserTest,
ActivateOnLinkClick_TargetBlankWithOpener) {
const GURL kInitialUrl = GetUrl("/simple_links.html");
const GURL kPrerenderingUrl = GetUrl("/title2.html");
// Navigate to an initial page which has a link to `kPrerenderingUrl`.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start prerendering `kPrerenderingUrl`.
FrameTreeNodeId prerender_host_id = AddPrerender(kPrerenderingUrl);
test::PrerenderHostObserver prerender_observer(*web_contents(),
prerender_host_id);
// Click the link annotated with "target=_blank rel=opener". This should not
// activate the prerendered page.
TestNavigationObserver nav_observer(kPrerenderingUrl);
nav_observer.StartWatchingNewWebContents();
const std::string kLinkClickScript = R"(
clickSameSiteNewWindowWithOpenerLink();
)";
EXPECT_TRUE(ExecJs(web_contents(), kLinkClickScript));
nav_observer.WaitForNavigationFinished();
EXPECT_EQ(nav_observer.last_navigation_url(), kPrerenderingUrl);
EXPECT_FALSE(prerender_observer.was_activated());
// The navigation occurred in a new WebContents, so the original WebContents
// should still be showing the initial trigger page.
EXPECT_EQ(web_contents()->GetLastCommittedURL(), kInitialUrl);
// Also, the prerendered page should still be alive.
EXPECT_TRUE(HasHostForUrl(kPrerenderingUrl));
// Navigate to `kPrerenderingUrl` on the original WebContents. The page opened
// with "rel=opener" should prevent it from activating the prerendered page.
NavigatePrimaryPage(kPrerenderingUrl);
EXPECT_EQ(web_contents()->GetLastCommittedURL(), kPrerenderingUrl);
EXPECT_FALSE(prerender_observer.was_activated());
// The prerendered page should be destroyed on activation attempt.
prerender_observer.WaitForDestroyed();
EXPECT_TRUE(GetHostForUrl(kPrerenderingUrl).is_null());
ExpectFinalStatusForSpeculationRule(
PrerenderFinalStatus::kActivatedWithAuxiliaryBrowsingContexts);
}
// Tests that clicking a link annotated with "target=_blank rel=opener" cannot
// activate a prerender whose target_hint is "_blank".
IN_PROC_BROWSER_TEST_F(
PrerenderTargetHintEnabledBrowserTest,
ActivateOnLinkClick_TargetBlankWithOpener_WithTargetHintBlank) {
const GURL kInitialUrl = GetUrl("/simple_links.html");
const GURL kPrerenderingUrl = GetUrl("/title2.html");
// Navigate to an initial page which has a link to `kPrerenderingUrl`.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start prerendering `kPrerenderingUrl`.
FrameTreeNodeId host_id = prerender_helper()->AddPrerender(
kPrerenderingUrl, /*eagerness=*/std::nullopt, "_blank");
auto* prerender_web_contents = WebContents::FromFrameTreeNodeId(host_id);
ASSERT_NE(prerender_web_contents, web_contents_impl());
ExpectWebContentsIsForNewTabPrerendering(*prerender_web_contents);
ukm::SourceId triggering_primary_page_source_id =
web_contents_impl()->GetPrimaryMainFrame()->GetPageUkmSourceId();
// Click the link annotated with "target=_blank rel=opener". This should not
// activate the prerendered page.
test::PrerenderHostObserver prerender_observer(*prerender_web_contents,
host_id);
const std::string kLinkClickScript = R"(
clickSameSiteNewWindowWithOpenerLink();
)";
EXPECT_TRUE(ExecJs(web_contents(), kLinkClickScript));
// The WebContents pre-created for prerendering should not be used.
EXPECT_NE(prerender_web_contents->GetLastCommittedURL(), kPrerenderingUrl);
EXPECT_FALSE(prerender_observer.was_activated());
// The host should still be available.
EXPECT_TRUE(HasHostForUrl(*prerender_web_contents, kPrerenderingUrl));
// The navigation occurred in a new WebContents, so the original WebContents
// should still be showing the initial trigger page.
EXPECT_EQ(web_contents()->GetLastCommittedURL(), kInitialUrl);
// Navigate to `kPrerenderingUrl` on the original WebContents. This should
// destroy the prerendered page and its WebContents.
NavigatePrimaryPage(kPrerenderingUrl);
EXPECT_EQ(web_contents()->GetLastCommittedURL(), kPrerenderingUrl);
EXPECT_FALSE(prerender_observer.was_activated());
prerender_observer.WaitForDestroyed();
EXPECT_TRUE(GetHostForUrl(kPrerenderingUrl).is_null());
ExpectFinalStatusForSpeculationRule(PrerenderFinalStatus::kTriggerDestroyed);
// Wait for UKM recording in PreloadingDataImpl::WebContentsDestroyed() on
// the destruction of the prerender WebContents.
// TODO(nhiroki): Wait for that in a more deterministic way instead of
// RunUntilIdle().
base::RunLoop().RunUntilIdle();
// The prerender WebContents doesn't have the primary page that can record UKM
// on destruction. Instead, it asks the primary page hosted on the primary
// WebContents to record UKM.
ExpectPreloadingAttemptPreviousPrimaryPageUkm(
attempt_previous_ukm_entry_builder().BuildEntry(
triggering_primary_page_source_id, PreloadingType::kPrerender,
PreloadingEligibility::kEligible, PreloadingHoldbackStatus::kAllowed,
PreloadingTriggeringOutcome::kReady,
PreloadingFailureReason::kUnspecified,
/*accurate=*/false,
/*ready_time=*/kMockElapsedTime,
blink::mojom::SpeculationEagerness::kEager));
ExpectPreloadingPredictioPreviousPrimaryPageUkm(
{prediction_previous_ukm_entry_builder().BuildEntry(
triggering_primary_page_source_id,
/*confidence=*/100,
/*accurate=*/false)});
}
// `window_features` is passed to the 3rd argument of window.open().
void PrerenderTargetHintEnabledBrowserTest::TestActivateOnWindowOpen(
std::string_view window_features) {
const GURL initial_url = GetUrl("/simple_links.html");
const GURL prerendering_url = GetUrl("/title2.html");
// Navigate to an initial page which has a link to `prerendering_url`.
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
// Start prerendering `prerendering_url`.
FrameTreeNodeId host_id = prerender_helper()->AddPrerender(
prerendering_url, /*eagerness=*/std::nullopt, "_blank");
auto* prerender_web_contents = WebContents::FromFrameTreeNodeId(host_id);
ASSERT_NE(prerender_web_contents, web_contents_impl());
ExpectWebContentsIsForNewTabPrerendering(*prerender_web_contents);
// Open a new window with "_blank" and `window_features`. This should activate
// the prerendered page.
TestNavigationObserver activation_observer(prerendering_url);
activation_observer.WatchExistingWebContents();
test::PrerenderHostObserver prerender_observer(*prerender_web_contents,
host_id);
const std::string script = base::StringPrintf(R"(
window.open("title2.html", "_blank", "%s");
)",
window_features);
EXPECT_TRUE(ExecJs(web_contents(), script));
activation_observer.WaitForNavigationFinished();
EXPECT_EQ(prerender_web_contents->GetLastCommittedURL(), prerendering_url);
EXPECT_EQ(activation_observer.last_navigation_url(), prerendering_url);
EXPECT_TRUE(prerender_observer.was_activated());
EXPECT_FALSE(HasHostForUrl(*prerender_web_contents, prerendering_url));
ExpectFinalStatusForSpeculationRule(PrerenderFinalStatus::kActivated);
ukm::SourceId ukm_source_id = activation_observer.next_page_ukm_source_id();
ExpectPreloadingAttemptUkm({attempt_ukm_entry_builder().BuildEntry(
ukm_source_id, PreloadingType::kPrerender,
PreloadingEligibility::kEligible, PreloadingHoldbackStatus::kAllowed,
PreloadingTriggeringOutcome::kSuccess,
PreloadingFailureReason::kUnspecified,
/*accurate=*/true,
/*ready_time=*/kMockElapsedTime,
blink::mojom::SpeculationEagerness::kEager)});
// The navigation occurred in a new WebContents, so the original WebContents
// should still be showing the initial trigger page.
EXPECT_EQ(web_contents()->GetLastCommittedURL(), initial_url);
}
// Tests that window.open() annotated with "_blank" and "noopener" can activate
// a prerender whose target_hint is "_blank".
IN_PROC_BROWSER_TEST_F(PrerenderTargetHintEnabledBrowserTest,
ActivateOnWindowOpen_NewTab) {
TestActivateOnWindowOpen("noopener");
}
// Tests that window.open() annotated with "_blank" and "noopener,popup" can
// activate a prerender whose target_hint is "_blank".
IN_PROC_BROWSER_TEST_F(PrerenderTargetHintEnabledBrowserTest,
ActivateOnWindowOpen_PopUp) {
TestActivateOnWindowOpen("noopener,popup");
}
// TODO(crbug.com/40234240): Add more test cases for prerender-in-new-tab:
// - Multiple prerendering requests with the same URL but different target hint.
// - Navigation in a new tab to the prerendering URL multiple times. Only the
// first navigation should activate the prerendered page.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, ResponseHeaders) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/set-header?X-Foo: bar");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
ASSERT_EQ(web_contents()->GetLastCommittedURL(), kInitialUrl);
// Start prerendering `kPrerenderingUrl` and check if `X-Foo` header is
// observed.
NavigationHandleObserver observer1(web_contents(), kPrerenderingUrl);
AddPrerender(kPrerenderingUrl);
ASSERT_EQ(GetRequestCount(kPrerenderingUrl), 1);
EXPECT_TRUE(observer1.has_committed());
EXPECT_EQ("bar", observer1.GetNormalizedResponseHeader("x-foo"));
// Activate the page and check if `X-Foo` header is observed again.
NavigationHandleObserver observer2(web_contents(), kPrerenderingUrl);
NavigatePrimaryPage(kPrerenderingUrl);
EXPECT_TRUE(observer2.has_committed());
EXPECT_EQ("bar", observer2.GetNormalizedResponseHeader("x-foo"));
}
// Tests that cancelling a prerender-into-new-tab trigger by invoking
// CancelHosts on initiator WebContents's PrerenderHostRegistry will
// eventually destruct corresponding PrerenderNewTabHandle and its WebContents
// created for the new-tab trigger.
IN_PROC_BROWSER_TEST_F(PrerenderTargetHintEnabledBrowserTest,
NewTabPrerenderCancellationOnInitiatorPHR) {
const GURL initial_url = GetUrl("/empty.html");
const GURL prerendering_url = GetUrl("/empty.html?prerender");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
// Start prerendering.
FrameTreeNodeId host_id = prerender_helper()->AddPrerender(
prerendering_url, /*eagerness=*/std::nullopt, "_blank");
auto* prerender_web_contents = WebContents::FromFrameTreeNodeId(host_id);
WebContentsDestroyedWatcher wc_destroyed_watcher(prerender_web_contents);
test::PrerenderHostObserver host_observer(*prerender_web_contents, host_id);
// Call CancelHost on initiator WebContents's PrerenderHostRegistry.
web_contents_impl()->GetPrerenderHostRegistry()->CancelHost(
host_id, PrerenderFinalStatus::kDestroyed);
host_observer.WaitForDestroyed();
// WebContents created for the new-tab trigger will be destroyed.
wc_destroyed_watcher.Wait();
EXPECT_FALSE(prerender_helper()->HasNewTabHandle(host_id));
ExpectFinalStatusForSpeculationRule(PrerenderFinalStatus::kDestroyed);
}
// Tests that cancelling a prerender-into-new-tab trigger by invoking
// CancelHosts on PrerenderHostRegistry of WebContents created by new-tab
// triggers will eventually destruct corresponding PrerenderNewTabHandle on
// initiator's PHR and that WebContents created for the new-tab trigger.
IN_PROC_BROWSER_TEST_F(PrerenderTargetHintEnabledBrowserTest,
NewTabPrerenderCancellationOnNewTabPHR) {
const GURL initial_url = GetUrl("/empty.html");
const GURL prerendering_url = GetUrl("/empty.html?prerender");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
// Start prerendering.
FrameTreeNodeId host_id = prerender_helper()->AddPrerender(
prerendering_url, /*eagerness=*/std::nullopt, "_blank");
auto* prerender_web_contents = WebContents::FromFrameTreeNodeId(host_id);
WebContentsDestroyedWatcher wc_destroyed_watcher(prerender_web_contents);
test::PrerenderHostObserver host_observer(*prerender_web_contents, host_id);
// Call CancelHost on WebContents's PrerenderHostRegistry that was created for
// the new-tab trigger.
static_cast<WebContentsImpl*>(prerender_web_contents)
->GetPrerenderHostRegistry()
->CancelHost(host_id, PrerenderFinalStatus::kDestroyed);
host_observer.WaitForDestroyed();
// WebContents created for the new-tab trigger will be destroyed.
wc_destroyed_watcher.Wait();
EXPECT_FALSE(prerender_helper()->HasNewTabHandle(host_id));
ExpectFinalStatusForSpeculationRule(PrerenderFinalStatus::kDestroyed);
}
// Tests that closing initiator's WebContents will eventually destruct
// corresponding PrerenderNewTabHandle WebContents created for the new-tab
// trigger without crashing.
IN_PROC_BROWSER_TEST_F(PrerenderTargetHintEnabledBrowserTest,
NewTabPrerenderCancellationByInitiatorWCClosure) {
const GURL initial_url = GetUrl("/empty.html");
const GURL prerendering_url = GetUrl("/empty.html?prerender");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
// Start prerendering.
FrameTreeNodeId host_id = prerender_helper()->AddPrerender(
prerendering_url, /*eagerness=*/std::nullopt, "_blank");
auto* prerender_web_contents = WebContents::FromFrameTreeNodeId(host_id);
WebContentsDestroyedWatcher wc_destroyed_watcher(prerender_web_contents);
test::PrerenderHostObserver host_observer(*prerender_web_contents, host_id);
shell()->Close();
host_observer.WaitForDestroyed();
// WebContents created for the new-tab trigger will be destroyed.
wc_destroyed_watcher.Wait();
ExpectFinalStatusForSpeculationRule(
PrerenderFinalStatus::kTabClosedWithoutUserGesture);
}
// Tests that prerendering is cancelled if a network request for the
// navigation results in an empty response with 404 status.
IN_PROC_BROWSER_TEST_P(PrerenderTargetAgnosticBrowserTest,
PrerenderCancelledOnEmptyBody404) {
const GURL kInitialUrl = GetUrl("/empty.html");
// Specify a URL for which we don't have a corresponding file in the data dir.
const GURL kPrerenderingUrl = GetUrl("/404");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start prerendering `kPrerenderingUrl`.
test::PrerenderHostCreationWaiter host_creation_waiter;
prerender_helper()->AddPrerendersAsync(
{kPrerenderingUrl}, /*eagerness=*/std::nullopt, GetTargetHint());
FrameTreeNodeId host_id = host_creation_waiter.Wait();
auto* prerender_web_contents = WebContents::FromFrameTreeNodeId(host_id);
test::PrerenderHostObserver host_observer(*prerender_web_contents, host_id);
host_observer.WaitForDestroyed();
EXPECT_EQ(GetRequestCount(kPrerenderingUrl), 1);
ExpectFinalStatusForSpeculationRule(
PrerenderFinalStatus::kNavigationBadHttpStatus);
}
// Tests that prerendering is cancelled if a network request for the
// navigation results in an non-empty response with 404 status.
IN_PROC_BROWSER_TEST_P(PrerenderTargetAgnosticBrowserTest,
PrerenderCancelledOnNonEmptyBody404) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/page404.html");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Add prerendering to the 404 error page, then check that it got cancelled.
test::PrerenderHostCreationWaiter host_creation_waiter;
prerender_helper()->AddPrerendersAsync(
{kPrerenderingUrl}, /*eagerness=*/std::nullopt, GetTargetHint());
FrameTreeNodeId host_id = host_creation_waiter.Wait();
auto* prerender_web_contents = WebContents::FromFrameTreeNodeId(host_id);
test::PrerenderHostObserver host_observer(*prerender_web_contents, host_id);
host_observer.WaitForDestroyed();
EXPECT_EQ(GetRequestCount(kPrerenderingUrl), 1);
ExpectFinalStatusForSpeculationRule(
PrerenderFinalStatus::kNavigationBadHttpStatus);
}
// Tests that prerendering is cancelled if a network request for the
// navigation results in an non-empty response with 500 status.
IN_PROC_BROWSER_TEST_P(PrerenderTargetAgnosticBrowserTest,
PrerenderCancelledOn500Page) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/page500.html");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Add prerendering to the 500 error page, then check that it got cancelled.
test::PrerenderHostCreationWaiter host_creation_waiter;
prerender_helper()->AddPrerendersAsync(
{kPrerenderingUrl}, /*eagerness=*/std::nullopt, GetTargetHint());
FrameTreeNodeId host_id = host_creation_waiter.Wait();
auto* prerender_web_contents = WebContents::FromFrameTreeNodeId(host_id);
test::PrerenderHostObserver host_observer(*prerender_web_contents, host_id);
host_observer.WaitForDestroyed();
EXPECT_EQ(GetRequestCount(kPrerenderingUrl), 1);
ExpectFinalStatusForSpeculationRule(
PrerenderFinalStatus::kNavigationBadHttpStatus);
}
IN_PROC_BROWSER_TEST_P(PrerenderTargetAgnosticBrowserTest,
PrerenderCancelledOn204Page) {
// Navigate to an initial page.
const GURL kInitialUrl = GetUrl("/title1.html");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start prerendering `kPrerenderingUrl` that returns 204 response code.
const GURL kPrerenderingUrl = GetUrl("/echo?status=204");
test::PrerenderHostCreationWaiter host_creation_waiter;
prerender_helper()->AddPrerendersAsync(
{kPrerenderingUrl}, /*eagerness=*/std::nullopt, GetTargetHint());
FrameTreeNodeId host_id = host_creation_waiter.Wait();
auto* prerender_web_contents = WebContents::FromFrameTreeNodeId(host_id);
test::PrerenderHostObserver host_observer(*prerender_web_contents, host_id);
// The prerender should be destroyed.
host_observer.WaitForDestroyed();
// Cancellation must have occurred due to bad http status code.
EXPECT_EQ(GetRequestCount(kPrerenderingUrl), 1);
ExpectFinalStatusForSpeculationRule(
PrerenderFinalStatus::kNavigationBadHttpStatus);
}
IN_PROC_BROWSER_TEST_P(PrerenderTargetAgnosticBrowserTest,
PrerenderCancelledOn205Page) {
// Navigate to an initial page.
const GURL kInitialUrl = GetUrl("/title1.html");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start prerendering `kPrerenderingUrl` that returns 205 response code.
const GURL kPrerenderingUrl = GetUrl("/echo?status=205");
test::PrerenderHostCreationWaiter host_creation_waiter;
prerender_helper()->AddPrerendersAsync(
{kPrerenderingUrl}, /*eagerness=*/std::nullopt, GetTargetHint());
FrameTreeNodeId host_id = host_creation_waiter.Wait();
auto* prerender_web_contents = WebContents::FromFrameTreeNodeId(host_id);
test::PrerenderHostObserver host_observer(*prerender_web_contents, host_id);
// The prerender should be destroyed.
host_observer.WaitForDestroyed();
// Cancellation must have occurred due to bad http status code.
EXPECT_EQ(GetRequestCount(kPrerenderingUrl), 1);
ExpectFinalStatusForSpeculationRule(
PrerenderFinalStatus::kNavigationBadHttpStatus);
}
namespace {
// Tests that an iframe navigation whose response has either 204 or 205 doesn't
// cancel prerendering.
// This is also a regression test for https://crbug.com/1362818.
void PrerenderBrowserTest::TestPrerenderAllowedOnIframeWithStatusCode(
OriginType origin_type,
std::string status_code) {
// This test is designed for 204 and 205 status codes.
ASSERT_TRUE(status_code == "204" || status_code == "205");
// Navigate to an initial page.
const GURL kInitialUrl = GetUrl("/title1.html");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start prerendering `kPrerenderingUrl`.
const GURL kPrerenderingUrl = GetUrl("/title1.html");
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
test::PrerenderHostObserver host_observer(*web_contents_impl(), host_id);
// Construct an iframe URL whose response has 204/205.
GURL iframe_url;
std::string file_path = "/echo?status=" + status_code;
switch (origin_type) {
case OriginType::kSameOrigin:
iframe_url = GetUrl(file_path);
break;
case OriginType::kSameSiteCrossOrigin:
iframe_url = GetSameSiteCrossOriginUrl(file_path);
break;
case OriginType::kCrossSite:
iframe_url = GetCrossSiteUrl(file_path);
break;
}
// Fetch the iframe.
TestNavigationManager iframe_navigation_manager(web_contents(), iframe_url);
RenderFrameHost* prerender_rfh = GetPrerenderedMainFrameHost(host_id);
std::ignore = ExecJs(prerender_rfh, JsReplace(R"(
const i = document.createElement('iframe');
i.src = $1;
document.body.appendChild(i);
)",
iframe_url.spec()));
switch (origin_type) {
case OriginType::kSameOrigin:
// Wait for the completion of the iframe navigation.
ASSERT_TRUE(iframe_navigation_manager.WaitForNavigationFinished());
break;
case OriginType::kSameSiteCrossOrigin:
case OriginType::kCrossSite:
// Cross-origin iframe navigation is deferred in WillStartRequest() before
// checking the status code.
ASSERT_TRUE(
iframe_navigation_manager.WaitForFirstYieldAfterDidStartNavigation());
auto* request = static_cast<NavigationRequest*>(
iframe_navigation_manager.GetNavigationHandle());
EXPECT_TRUE(request->IsDeferredForTesting());
NavigationThrottleRunner* throttle_runner =
request->GetNavigationThrottleRunnerForTesting();
EXPECT_STREQ(
"PrerenderSubframeNavigationThrottle",
throttle_runner->GetDeferringThrottle()->GetNameForLogging());
break;
}
// Fetching an iframe whose response has 204/205 status code shouldn't cancel
// prerendering unlike the mainframe whose response has 204/205 status code.
// https://wicg.github.io/nav-speculation/prerendering.html#no-bad-navs
EXPECT_EQ(GetHostForUrl(kPrerenderingUrl), host_id);
}
} // namespace
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
PrerenderAllowedOnIframe_204_SameOrigin) {
TestPrerenderAllowedOnIframeWithStatusCode(OriginType::kSameOrigin, "204");
}
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
PrerenderAllowedOnIframe_204_SameSiteCrossOrigin) {
TestPrerenderAllowedOnIframeWithStatusCode(OriginType::kSameSiteCrossOrigin,
"204");
}
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
PrerenderAllowedOnIframe_204_CrossSite) {
TestPrerenderAllowedOnIframeWithStatusCode(OriginType::kCrossSite, "204");
}
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
PrerenderAllowedOnIframe_205_SameOrigin) {
TestPrerenderAllowedOnIframeWithStatusCode(OriginType::kSameOrigin, "205");
}
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
PrerenderAllowedOnIframe_205_SameSiteCrossOrigin) {
TestPrerenderAllowedOnIframeWithStatusCode(OriginType::kSameSiteCrossOrigin,
"205");
}
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
PrerenderAllowedOnIframe_205_CrossSite) {
TestPrerenderAllowedOnIframeWithStatusCode(OriginType::kCrossSite, "205");
}
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, CancelOnAuthRequested) {
// Navigate to an initial page.
const GURL kInitialUrl = GetUrl("/title1.html");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start prerendering `kPrerenderingUrl`.
const GURL kPrerenderingUrl = GetUrl("/auth-basic");
test::PrerenderHostObserver host_observer(*web_contents_impl(),
kPrerenderingUrl);
AddPrerenderAsync(kPrerenderingUrl);
// The prerender should be destroyed.
host_observer.WaitForDestroyed();
EXPECT_TRUE(GetHostForUrl(kPrerenderingUrl).is_null());
// Navigate primary page to flush the metrics.
const GURL kNavigatedURL = GetUrl("/title2.html");
ASSERT_TRUE(NavigateToURL(shell(), kNavigatedURL));
// Cross-check that Preloading.Attempt logs the correct failure reason.
ExpectPreloadingAttemptUkm({attempt_ukm_entry_builder().BuildEntry(
PrimaryPageSourceId(), PreloadingType::kPrerender,
PreloadingEligibility::kEligible, PreloadingHoldbackStatus::kAllowed,
PreloadingTriggeringOutcome::kFailure,
ToPreloadingFailureReason(PrerenderFinalStatus::kLoginAuthRequested),
/*accurate=*/false,
/*ready_time=*/std::nullopt,
blink::mojom::SpeculationEagerness::kEager)});
// Cancellation must have occurred due to authentication request.
ExpectFinalStatusForSpeculationRule(
PrerenderFinalStatus::kLoginAuthRequested);
}
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, CancelOnAuthRequestedSubframe) {
// Navigate to an initial page.
const GURL kInitialUrl = GetUrl("/title1.html");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start prerendering `kPrerenderingUrl`.
const GURL kPrerenderingUrl = GetUrl("/title1.html");
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
test::PrerenderHostObserver host_observer(*web_contents_impl(), host_id);
// Fetch a subframe that requires authentication.
const GURL kAuthIFrameUrl = GetUrl("/auth-basic");
RenderFrameHost* prerender_rfh = GetPrerenderedMainFrameHost(host_id);
std::ignore =
ExecJs(prerender_rfh,
"const i = document.createElement('iframe'); i.src = '" +
kAuthIFrameUrl.spec() + "'; document.body.appendChild(i);");
// The prerender should be destroyed.
host_observer.WaitForDestroyed();
EXPECT_TRUE(GetHostForUrl(kPrerenderingUrl).is_null());
// Cancellation must have occurred due to authentication request.
ExpectFinalStatusForSpeculationRule(
PrerenderFinalStatus::kLoginAuthRequested);
}
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, CancelOnAuthRequestedSubResource) {
// Navigate to an initial page.
const GURL kInitialUrl = GetUrl("/empty.html");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start prerendering `kPrerenderingUrl`.
const GURL kPrerenderingUrl = GetUrl("/title1.html");
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
test::PrerenderHostObserver host_observer(*web_contents_impl(), host_id);
ASSERT_TRUE(GetHostForUrl(kPrerenderingUrl));
// Fetch a subresrouce.
std::string fetch_subresource_script = R"(
const imgElement = document.createElement('img');
imgElement.src = '/auth-basic/favicon.gif';
document.body.appendChild(imgElement);
)";
std::ignore =
ExecJs(GetPrerenderedMainFrameHost(host_id), fetch_subresource_script);
// The prerender should be destroyed.
host_observer.WaitForDestroyed();
EXPECT_TRUE(GetHostForUrl(kPrerenderingUrl).is_null());
// Cancellation must have occurred due to authentication request.
ExpectFinalStatusForSpeculationRule(
PrerenderFinalStatus::kLoginAuthRequested);
}
IN_PROC_BROWSER_TEST_F(PrerenderTargetHintEnabledBrowserTest,
CancelOnSpeculationCandidateRemoved) {
GURL url_ping(GetUrl(kPagehideEventPath));
// Navigate to an initial page.
const GURL kInitialUrl = GetUrl("/title1.html");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start prerendering.
const GURL kPrerenderingUrl = GetUrl("/title1.html?prerender");
test::PrerenderHostRegistryObserver registry_observer(*web_contents_impl());
AddPrerenderAsync(kPrerenderingUrl);
registry_observer.WaitForTrigger(kPrerenderingUrl);
FrameTreeNodeId host_id = GetHostForUrl(kPrerenderingUrl);
ASSERT_TRUE(host_id);
WaitForPrerenderLoadCompletion(kPrerenderingUrl);
RenderFrameHost* prerender_host = GetPrerenderedMainFrameHost(host_id);
// Call fetchLater() to record that the pagehide event is fired.
std::string js = R"(
addEventListener('pagehide', () => {
fetchLater($1);
});)";
EXPECT_TRUE(ExecJs(prerender_host, JsReplace(js, url_ping)));
EXPECT_FALSE(PageHideReceived());
// Remove the rules and check that the prerender is cancelled with an
// appropriate final status.
test::PrerenderHostObserver host_observer(*web_contents_impl(), host_id);
ASSERT_TRUE(ExecJs(
web_contents_impl()->GetPrimaryMainFrame(),
"document.querySelector('script[type=speculationrules]').remove()"));
host_observer.WaitForDestroyed();
EXPECT_TRUE(GetHostForUrl(kPrerenderingUrl).is_null());
ExpectFinalStatusForSpeculationRule(
PrerenderFinalStatus::kSpeculationRuleRemoved);
// Intended prerender cancellation such as speculation rules removal is
// expected to dispatch the pagehide event unlike other unexpected prerender
// failures.
WaitForPageHide();
EXPECT_TRUE(PageHideReceived());
}
// Tests removing speculation rules whose target_hint is "_blank" (i.e.,
// prerender into new tab).
IN_PROC_BROWSER_TEST_F(
PrerenderTargetHintEnabledBrowserTest,
CancelOnSpeculationCandidateRemoved_WithTargetHintBlank) {
GURL url_ping(GetUrl(kPagehideEventPath));
// Navigate to an initial page.
const GURL kInitialUrl = GetUrl("/title1.html");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start prerendering.
const GURL kPrerenderingUrl = GetUrl("/title1.html?prerender");
FrameTreeNodeId host_id = prerender_helper()->AddPrerender(
kPrerenderingUrl, /*eagerness=*/std::nullopt, "_blank");
auto* prerender_web_contents = WebContents::FromFrameTreeNodeId(host_id);
ASSERT_NE(prerender_web_contents, web_contents_impl());
ExpectWebContentsIsForNewTabPrerendering(*prerender_web_contents);
// Call fetchLater() to record that the pagehide event is fired.
std::string js = R"(
addEventListener('pagehide', () => {
fetchLater($1);
});)";
RenderFrameHost* prerender_host =
prerender_helper()->GetPrerenderedMainFrameHost(*prerender_web_contents,
host_id);
EXPECT_TRUE(ExecJs(prerender_host, JsReplace(js, url_ping)));
EXPECT_FALSE(PageHideReceived());
base::WeakPtr<WebContents> prerender_web_contents_weak =
prerender_web_contents->GetWeakPtr();
// Remove the rules and check that the prerender is cancelled with an
// appropriate final status.
test::PrerenderHostObserver host_observer(*prerender_web_contents, host_id);
ASSERT_TRUE(ExecJs(
web_contents_impl()->GetPrimaryMainFrame(),
"document.querySelector('script[type=speculationrules]').remove()"));
host_observer.WaitForDestroyed();
ExpectFinalStatusForSpeculationRule(
PrerenderFinalStatus::kSpeculationRuleRemoved);
// Intended prerender cancellation such as speculation rules removal is
// expected to dispatch the pagehide event unlike other unexpected prerender
// failures.
WaitForPageHide();
EXPECT_TRUE(PageHideReceived());
// During the cancellation, the prerender WebContents should be destroyed.
EXPECT_FALSE(prerender_web_contents_weak);
ukm::SourceId triggering_primary_page_source_id =
web_contents_impl()->GetPrimaryMainFrame()->GetPageUkmSourceId();
// The prerender WebContents doesn't have the primary page that can record UKM
// on destruction. Instead, it asks the primary page hosted on the primary
// WebContents to record UKM.
ExpectPreloadingAttemptPreviousPrimaryPageUkm(
attempt_previous_ukm_entry_builder().BuildEntry(
triggering_primary_page_source_id, PreloadingType::kPrerender,
PreloadingEligibility::kEligible, PreloadingHoldbackStatus::kAllowed,
PreloadingTriggeringOutcome::kReady,
PreloadingFailureReason::kUnspecified,
/*accurate=*/false,
/*ready_time=*/kMockElapsedTime,
blink::mojom::SpeculationEagerness::kEager));
}
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
DontCancelOnSpeculationUpdateIfStillEligible) {
// Navigate to an initial page.
const GURL kInitialUrl = GetUrl("/title1.html");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start prerendering.
const GURL kPrerenderingUrl = GetUrl("/title2.html");
test::PrerenderHostRegistryObserver registry_observer(*web_contents_impl());
ASSERT_TRUE(ExecJs(web_contents_impl()->GetPrimaryMainFrame(),
JsReplace(
R"(
let sc = document.createElement('script');
sc.type = 'speculationrules';
sc.textContent = JSON.stringify({
prerender: [
{source: "list", urls: [$1]}
]
});
document.head.appendChild(sc);
)",
kPrerenderingUrl)));
registry_observer.WaitForTrigger(kPrerenderingUrl);
FrameTreeNodeId host_id = GetHostForUrl(kPrerenderingUrl);
ASSERT_TRUE(host_id);
ASSERT_TRUE(ExecJs(web_contents_impl()->GetPrimaryMainFrame(),
JsReplace(
R"(
document.querySelector('script[type=speculationrules]')
.remove();
let sc = document.createElement('script');
sc.type = 'speculationrules';
sc.textContent = JSON.stringify({
prerender: [
{source: "list", urls: ["/empty.html", $1]}
]
});
document.head.appendChild(sc);
)",
kPrerenderingUrl)));
// Replace the rules. Even though the original rules are gone, the new ones
// still permit the prerender so it continues.
{
base::RunLoop run_loop;
base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
FROM_HERE, run_loop.QuitClosure(), TestTimeouts::action_timeout());
run_loop.Run();
ASSERT_TRUE(GetHostForUrl(kPrerenderingUrl));
}
// Remove the rules and check that the prerender is cancelled.
test::PrerenderHostObserver host_observer(*web_contents_impl(), host_id);
ASSERT_TRUE(ExecJs(
web_contents_impl()->GetPrimaryMainFrame(),
"document.querySelector('script[type=speculationrules]').remove()"));
host_observer.WaitForDestroyed();
EXPECT_TRUE(GetHostForUrl(kPrerenderingUrl).is_null());
}
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
CanStartSecondPrerenderWhenCancellingFirst) {
// Navigate to an initial page.
const GURL kInitialUrl = GetUrl("/title1.html");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start prerendering.
const GURL kPrerenderingUrl = GetUrl("/title2.html");
test::PrerenderHostRegistryObserver registry_observer(*web_contents_impl());
ASSERT_TRUE(ExecJs(web_contents_impl()->GetPrimaryMainFrame(),
JsReplace(
R"(
let sc = document.createElement('script');
sc.type = 'speculationrules';
sc.textContent = JSON.stringify({
prerender: [
{source: "list", urls: [$1]}
]
});
document.head.appendChild(sc);
)",
kPrerenderingUrl)));
registry_observer.WaitForTrigger(kPrerenderingUrl);
FrameTreeNodeId host_id = GetHostForUrl(kPrerenderingUrl);
ASSERT_TRUE(host_id);
// Starting a different prerender still works.
// (For now, this works unconditionally. In the future this might depend on
// some other conditions.)
const GURL kPrerenderingUrl2 = GetUrl("/title3.html");
test::PrerenderHostObserver host_observer(*web_contents_impl(), host_id);
ASSERT_TRUE(ExecJs(web_contents_impl()->GetPrimaryMainFrame(),
JsReplace(
R"(
document.querySelector('script[type=speculationrules]')
.remove();
let sc = document.createElement('script');
sc.type = 'speculationrules';
sc.textContent = JSON.stringify({
prerender: [
{source: "list", urls: [$1]}
]
});
document.head.appendChild(sc);
)",
kPrerenderingUrl2)));
// The original prerender should be cancelled.
host_observer.WaitForDestroyed();
EXPECT_TRUE(GetHostForUrl(kPrerenderingUrl).is_null());
// And the new one should be discovered.
registry_observer.WaitForTrigger(kPrerenderingUrl2);
FrameTreeNodeId second_host_id = GetHostForUrl(kPrerenderingUrl2);
EXPECT_TRUE(second_host_id);
}
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, RetriggerPrerenderAfterRemoval) {
// Navigate to an initial page.
const GURL kInitialUrl = GetUrl("/title1.html");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start prerendering.
const GURL kPrerenderingUrl = GetUrl("/title2.html");
{
test::PrerenderHostRegistryObserver registry_observer(*web_contents_impl());
ASSERT_TRUE(ExecJs(web_contents_impl()->GetPrimaryMainFrame(),
JsReplace(
R"(
let sc = document.createElement('script');
sc.type = 'speculationrules';
sc.textContent = JSON.stringify({
prerender: [
{source: "list", urls: [$1]}
]
});
document.head.appendChild(sc);
)",
kPrerenderingUrl)));
registry_observer.WaitForTrigger(kPrerenderingUrl);
FrameTreeNodeId host_id = GetHostForUrl(kPrerenderingUrl);
ASSERT_TRUE(host_id);
test::PrerenderHostObserver host_observer(*web_contents_impl(), host_id);
// Remove the rules and check that the prerender is cancelled with an
// appropriate final status.
ASSERT_TRUE(ExecJs(
web_contents_impl()->GetPrimaryMainFrame(),
"document.querySelector('script[type=speculationrules]').remove()"));
host_observer.WaitForDestroyed();
EXPECT_TRUE(GetHostForUrl(kPrerenderingUrl).is_null());
}
{
AddPrerender(kPrerenderingUrl);
FrameTreeNodeId host_id = GetHostForUrl(kPrerenderingUrl);
EXPECT_TRUE(host_id);
}
}
// Tests that prerendering triggered by prerendered pages is deferred until
// activation.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderChain) {
// kInitialUrl prerenders kPrerenderChain1, then kPrerenderChain1 prerenders
// kPrerenderChain2.
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderChain1 =
GetUrl("/prerender/page_with_trigger_function.html?1");
const GURL kPrerenderChain2 =
GetUrl("/prerender/page_with_trigger_function.html?2");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
FrameTreeNodeId host_id = AddPrerender(kPrerenderChain1);
EXPECT_EQ(GetRequestCount(kPrerenderChain1), 1);
EXPECT_TRUE(host_id);
RenderFrameHost* prerender_host = GetPrerenderedMainFrameHost(host_id);
EXPECT_TRUE(AddTestUtilJS(prerender_host));
// Add a prerender trigger to the prerendering page.
EXPECT_TRUE(ExecJs(prerender_host,
JsReplace("add_speculation_rules($1)", kPrerenderChain2)));
// Speculation rules is processed by the idle task runner in Blink. To ensure
// the speculation candidates has been sent by renderer processes, we should
// wait until this runner finishes all tasks.
EXPECT_TRUE(ExecJs(prerender_host, R"(
const idlePromise = new Promise(resolve => requestIdleCallback(resolve));
idlePromise;
)"));
// Start a navigation request that should not be deferred, and wait it to
// reach the server. If the prerender request for kPrerenderChain2 is not
// deferred, the navigation request for kPrerenderChain2 will reach the server
// earlier than the non-deferred one, so we can wait until the latest request
// reaches the sever to prove that the prerender request for kPrerenderChain2
// is deferred.
EXPECT_TRUE(ExecJs(prerender_host, "add_iframe_async('/title1.html')",
EvalJsOptions::EXECUTE_SCRIPT_NO_RESOLVE_PROMISES));
WaitForRequest(GetUrl("/title1.html"), 1);
// The prerender requests were deferred by Mojo capability control, so
// prerendering pages should not trigger prerendering.
EXPECT_EQ(GetRequestCount(kPrerenderChain2), 0);
EXPECT_FALSE(HasHostForUrl(kPrerenderChain2));
// Activate the prerendering page to grant the deferred prerender requests.
NavigatePrimaryPage(kPrerenderChain1);
EXPECT_EQ(web_contents()->GetLastCommittedURL(), kPrerenderChain1);
// The prerendered page was activated. The prerender requests should be
// processed.
WaitForPrerenderLoadCompletion(kPrerenderChain2);
EXPECT_EQ(GetRequestCount(kPrerenderChain2), 1);
EXPECT_TRUE(HasHostForUrl(kPrerenderChain2));
}
// Tests that sub-frames cannot trigger prerendering.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, IgnoreSubFrameInitiatedPrerender) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kSubFrameUrl =
GetUrl("/prerender/page_with_trigger_function.html");
const GURL kPrerenderingUrl = GetUrl("/title.html");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
RenderFrameHostImpl* main_frame_host = current_frame_host();
EXPECT_TRUE(AddTestUtilJS(main_frame_host));
EXPECT_EQ("LOADED",
EvalJs(web_contents(), JsReplace("add_iframe($1)", kSubFrameUrl)));
RenderFrameHost* child_frame_host = ChildFrameAt(main_frame_host, 0);
ASSERT_NE(child_frame_host, nullptr);
ASSERT_EQ(child_frame_host->GetLastCommittedURL(), kSubFrameUrl);
// Add a prerender trigger to the subframe.
EXPECT_TRUE(ExecJs(child_frame_host,
JsReplace("add_speculation_rules($1)", kPrerenderingUrl)));
// Speculation rules is processed by the idle task runner in Blink. To ensure
// the speculation candidates has been sent by renderer processes, we should
// wait until this runner finishes all tasks.
EXPECT_TRUE(ExecJs(child_frame_host, R"(
const idlePromise = new Promise(resolve => requestIdleCallback(resolve));
idlePromise;
)"));
// Start a navigation request that should not be ignored, and wait it to
// reach the server. If the prerender request is not ignored, the navigation
// request for kPrerenderingUrl will reach the server earlier than the
// non-ignored one, so we can wait until the latest request reaches the sever
// to prove that the prerender request for kPrerenderingUrl is ignored.
EXPECT_TRUE(ExecJs(main_frame_host, "add_iframe_async('/title1.html')",
EvalJsOptions::EXECUTE_SCRIPT_NO_RESOLVE_PROMISES));
WaitForRequest(GetUrl("/title1.html"), 1);
// The prerender requests were ignored by SpeculationHostImpl.
EXPECT_EQ(GetRequestCount(kPrerenderingUrl), 0);
EXPECT_FALSE(HasHostForUrl(kPrerenderingUrl));
}
// Regression test for https://crbug.com/1194865.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, CloseOnPrerendering) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/empty.html?prerender");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
ASSERT_EQ(web_contents()->GetLastCommittedURL(), kInitialUrl);
// Start prerendering `kPrerenderingUrl`.
ASSERT_EQ(GetRequestCount(kPrerenderingUrl), 0);
AddPrerender(kPrerenderingUrl);
EXPECT_EQ(GetRequestCount(kPrerenderingUrl), 1);
// A prerender host for the URL should be registered.
EXPECT_TRUE(HasHostForUrl(kPrerenderingUrl));
// Should not crash.
shell()->Close();
ExpectFinalStatusForSpeculationRule(
PrerenderFinalStatus::kTabClosedWithoutUserGesture);
}
namespace {
class RedirectChainObserver : public WebContentsObserver {
public:
RedirectChainObserver(WebContents& web_contents, const GURL& url)
: WebContentsObserver(&web_contents), url_(url) {}
std::vector<GURL>& redirect_chain() { return redirect_chain_; }
private:
void DidFinishNavigation(NavigationHandle* handle) override {
if (handle->GetURL() != url_) {
return;
}
redirect_chain_ = handle->GetRedirectChain();
}
const GURL url_;
std::vector<GURL> redirect_chain_;
};
} // namespace
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, SameOriginRedirection) {
// Navigate to an initial page.
const GURL kInitialUrl = GetUrl("/empty.html");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start prerendering a URL that causes same-origin redirection.
const GURL kRedirectedUrl = GetUrl("/empty.html?prerender");
const GURL kPrerenderingUrl =
GetUrl("/server-redirect?" + kRedirectedUrl.spec());
RedirectChainObserver redirect_chain_observer(*shell()->web_contents(),
kRedirectedUrl);
AddPrerender(kPrerenderingUrl);
EXPECT_EQ(GetRequestCount(kPrerenderingUrl), 1);
EXPECT_EQ(GetRequestCount(kRedirectedUrl), 1);
ASSERT_EQ(2u, redirect_chain_observer.redirect_chain().size());
EXPECT_EQ(kPrerenderingUrl, redirect_chain_observer.redirect_chain()[0]);
EXPECT_EQ(kRedirectedUrl, redirect_chain_observer.redirect_chain()[1]);
// The prerender host should be registered for the initial request URL, not
// the redirected URL.
EXPECT_TRUE(HasHostForUrl(kPrerenderingUrl));
EXPECT_FALSE(HasHostForUrl(kRedirectedUrl));
// Regression test for https://crbug.com/1211274. Make sure that we don't
// crash when activating a prerendered page which performed a same-origin
// redirect.
RedirectChainObserver activation_redirect_chain_observer(
*shell()->web_contents(), kRedirectedUrl);
NavigationHandleObserver activation_observer(web_contents(),
kPrerenderingUrl);
NavigatePrimaryPage(kPrerenderingUrl);
ASSERT_EQ(1u, activation_redirect_chain_observer.redirect_chain().size());
EXPECT_EQ(kRedirectedUrl,
activation_redirect_chain_observer.redirect_chain()[0]);
// Cross-check that in case redirection when the prerender navigates and user
// ends up navigating to the redirected URL. accurate_triggering is true.
ukm::SourceId ukm_source_id = activation_observer.next_page_ukm_source_id();
ExpectPreloadingAttemptUkm({attempt_ukm_entry_builder().BuildEntry(
ukm_source_id, PreloadingType::kPrerender,
PreloadingEligibility::kEligible, PreloadingHoldbackStatus::kAllowed,
PreloadingTriggeringOutcome::kSuccess,
PreloadingFailureReason::kUnspecified,
/*accurate=*/true,
/*ready_time=*/kMockElapsedTime,
blink::mojom::SpeculationEagerness::kEager)});
}
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, CrossSiteRedirection) {
// Navigate to an initial page.
const GURL kInitialUrl = GetUrl("/empty.html");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start prerendering a URL that causes cross-origin redirection. The
// cross-origin redirection should fail prerendering.
const GURL kRedirectedUrl = GetCrossSiteUrl("/empty.html?prerender");
const GURL kPrerenderingUrl =
GetUrl("/server-redirect?" + kRedirectedUrl.spec());
test::PrerenderHostObserver host_observer(*web_contents_impl(),
kPrerenderingUrl);
AddPrerenderAsync(kPrerenderingUrl);
host_observer.WaitForDestroyed();
EXPECT_EQ(GetRequestCount(kPrerenderingUrl), 1);
EXPECT_EQ(GetRequestCount(kRedirectedUrl), 0);
EXPECT_FALSE(HasHostForUrl(kPrerenderingUrl));
EXPECT_FALSE(HasHostForUrl(kRedirectedUrl));
ExpectFinalStatusForSpeculationRule(
PrerenderFinalStatus::kCrossSiteRedirectInInitialNavigation);
}
// Makes sure that activation on navigation for an iframes doesn't happen.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, Activation_iFrame) {
// Navigate to an initial page.
const GURL kInitialUrl = GetUrl("/empty.html");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
EXPECT_TRUE(AddTestUtilJS(current_frame_host()));
// Start a prerender.
const GURL kPrerenderingUrl = GetUrl("/empty.html?prerender");
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
// Attempt to activate the prerendered page for an iframe. This should fail
// and fallback to network request.
ASSERT_EQ(GetRequestCount(kPrerenderingUrl), 1);
EXPECT_EQ("LOADED", EvalJs(web_contents(),
JsReplace("add_iframe($1)", kPrerenderingUrl)));
EXPECT_EQ(GetRequestCount(kPrerenderingUrl), 2);
// Activation shouldn't happen, so the prerender host should not be consumed.
EXPECT_EQ(GetHostForUrl(kPrerenderingUrl), host_id);
}
// Make sure that the prerendering browsing context has an isolated trivial
// session history. history.length should be limited to 1 in the prerendering
// browsing context.
//
// Explainer:
// https://github.com/jeremyroman/alternate-loading-modes/blob/main/browsing-context.md#session-history
IN_PROC_BROWSER_TEST_F(
PrerenderBrowserTest,
SessionHistoryShouldHaveSingleNavigationEntryInPrerender) {
// Navigate the primary main frame to an initial page.
const GURL kInitialUrl = GetUrl("/empty.html?initial");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
TestNavigationHistory(kInitialUrl, /*expected_history_index=*/0,
/*expected_history_length=*/1);
// Navigate the primary main frame to another page so that the initiator
// page's `history.length` becomes 2. That helps us to distinguish the initial
// page's session history and the prerendering page's session history. This is
// not a robust way, but probably good enough in this test.
const GURL k2ndUrl = GetUrl("/empty.html?2nd");
ASSERT_TRUE(NavigateToURL(shell(), k2ndUrl));
TestNavigationHistory(k2ndUrl, /*expected_history_index=*/1,
/*expected_history_length=*/2);
// Start a prerender.
const GURL kPrerenderingUrl = GetUrl("/empty.html?prerender");
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
RenderFrameHost* prerender_frame_host = GetPrerenderedMainFrameHost(host_id);
ASSERT_EQ(GetRequestCount(kPrerenderingUrl), 1);
TestNavigationHistory(k2ndUrl, /*expected_history_index=*/1,
/*expected_history_length=*/2);
AssertPrerenderHistoryLength(host_id, prerender_frame_host);
// From here, we perform several operations which usually append a new entry
// to the session history, however, all navigations within the prerendering
// browsing context should be done with replacement in the isolated session
// history.
// TODO: Factor out this test into several tests. This test is getting large.
// Perform history.replaceState() in the prerendered page. Note
// history.replaceState() doesn't append a new entry anyway. The purpose of
// testing history.replaceState() here is just for the comparison; pushState()
// vs replaceState(). Both should have the same behavior in a prerendering
// browsing context.
{
FrameNavigateParamsCapturer capturer(
FrameTreeNode::From(prerender_frame_host));
ASSERT_EQ(nullptr, EvalJs(prerender_frame_host,
"history.replaceState('state1', null, null)"));
TestNavigationHistory(k2ndUrl, /*expected_history_index=*/1,
/*expected_history_length=*/2);
AssertPrerenderHistoryLength(host_id, prerender_frame_host);
EXPECT_EQ("state1", EvalJs(prerender_frame_host, "history.state"));
EXPECT_EQ(NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY,
capturer.navigation_type());
EXPECT_TRUE(capturer.is_same_document());
EXPECT_TRUE(capturer.did_replace_entry());
}
// Perform history.pushState() in the prerendered page.
{
FrameNavigateParamsCapturer capturer(
FrameTreeNode::From(prerender_frame_host));
ASSERT_EQ(nullptr, EvalJs(prerender_frame_host,
"history.pushState('state2', null, null)"));
TestNavigationHistory(k2ndUrl, /*expected_history_index=*/1,
/*expected_history_length=*/2);
AssertPrerenderHistoryLength(host_id, prerender_frame_host);
EXPECT_EQ("state2", EvalJs(prerender_frame_host, "history.state"));
EXPECT_EQ(NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY,
capturer.navigation_type());
EXPECT_TRUE(capturer.is_same_document());
EXPECT_TRUE(capturer.did_replace_entry());
}
// Do a fragment navigation in the prerendered main frame.
{
FrameNavigateParamsCapturer capturer(
FrameTreeNode::From(prerender_frame_host));
const GURL kPrerenderingAnchorUrl = GetUrl("/empty.html?prerender#anchor");
NavigatePrerenderedPage(host_id, kPrerenderingAnchorUrl);
WaitForPrerenderLoadCompletion(host_id);
ASSERT_EQ(GetRequestCount(kPrerenderingAnchorUrl), 1);
TestNavigationHistory(k2ndUrl, /*expected_history_index=*/1,
/*expected_history_length=*/2);
AssertPrerenderHistoryLength(host_id, prerender_frame_host);
// history.state should be replaced with a fragment navigation.
EXPECT_EQ(nullptr, EvalJs(prerender_frame_host, "history.state"));
EXPECT_EQ(NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY,
capturer.navigation_type());
EXPECT_TRUE(capturer.is_same_document());
EXPECT_TRUE(capturer.did_replace_entry());
}
// Add a same-origin iframe to the prerendered page and let it navigate to the
// different same-origin URL.
{
// Add an iframe.
const GURL kSameOriginSubframeUrl1 =
GetUrl("/empty.html?same_origin_iframe1");
EXPECT_TRUE(AddTestUtilJS(prerender_frame_host));
ASSERT_EQ("LOADED",
EvalJs(prerender_frame_host,
JsReplace("add_iframe($1)", kSameOriginSubframeUrl1)));
ASSERT_EQ(GetRequestCount(kSameOriginSubframeUrl1), 1);
auto* child_frame = ChildFrameAt(prerender_frame_host, 0);
ASSERT_NE(nullptr, child_frame);
EXPECT_EQ(kSameOriginSubframeUrl1, child_frame->GetLastCommittedURL());
// Let the added iframe navigate to the different URL.
{
FrameNavigateParamsCapturer capturer(FrameTreeNode::From(child_frame));
const GURL kSameOriginSubframeUrl2 =
GetUrl("/empty.html?same_origin_iframe2");
ASSERT_EQ(kSameOriginSubframeUrl2,
EvalJs(child_frame,
JsReplace("location = $1", kSameOriginSubframeUrl2)));
capturer.Wait();
child_frame = ChildFrameAt(prerender_frame_host, 0);
EXPECT_EQ(kSameOriginSubframeUrl2, child_frame->GetLastCommittedURL());
ASSERT_EQ(GetRequestCount(kSameOriginSubframeUrl2), 1);
TestNavigationHistory(k2ndUrl, /*expected_history_index=*/1,
/*expected_history_length=*/2);
AssertPrerenderHistoryLength(host_id, prerender_frame_host);
EXPECT_EQ(nullptr, EvalJs(prerender_frame_host, "history.state"));
EXPECT_EQ(NAVIGATION_TYPE_AUTO_SUBFRAME, capturer.navigation_type());
EXPECT_FALSE(capturer.is_same_document());
EXPECT_TRUE(capturer.did_replace_entry());
EXPECT_TRUE(capturer.is_renderer_initiated());
}
// Use WebContents::OpenURL() to let the added iframe navigate.
{
FrameNavigateParamsCapturer capturer(FrameTreeNode::From(child_frame));
const GURL kSameOriginSubframeUrl3 =
GetUrl("/empty.html?same_origin_iframe3");
shell()->web_contents()->OpenURL(
OpenURLParams(kSameOriginSubframeUrl3, Referrer(),
child_frame->GetFrameTreeNodeId(),
WindowOpenDisposition::CURRENT_TAB,
ui::PAGE_TRANSITION_AUTO_SUBFRAME,
/*is_renderer_initiated=*/false),
/*navigation_handle_callback=*/{});
capturer.Wait();
child_frame = ChildFrameAt(prerender_frame_host, 0);
EXPECT_EQ(kSameOriginSubframeUrl3, child_frame->GetLastCommittedURL());
ASSERT_EQ(GetRequestCount(kSameOriginSubframeUrl3), 1);
TestNavigationHistory(k2ndUrl, /*expected_history_index=*/1,
/*expected_history_length=*/2);
AssertPrerenderHistoryLength(host_id, prerender_frame_host);
EXPECT_EQ(nullptr, EvalJs(prerender_frame_host, "history.state"));
EXPECT_EQ(NAVIGATION_TYPE_AUTO_SUBFRAME, capturer.navigation_type());
EXPECT_FALSE(capturer.is_same_document());
EXPECT_TRUE(capturer.did_replace_entry());
EXPECT_FALSE(capturer.is_renderer_initiated());
}
}
// Perform history.back() in the prerendered page, which should be no-op.
{
int current_request_count = GetRequestCount(k2ndUrl);
ASSERT_EQ(nullptr, EvalJs(prerender_frame_host, "history.back()"));
// Make sure that loading is not happening.
EXPECT_FALSE(FrameTreeNode::GloballyFindByID(host_id)
->frame_tree()
.IsLoadingIncludingInnerFrameTrees());
TestNavigationHistory(k2ndUrl, /*expected_history_index=*/1,
/*expected_history_length=*/2);
AssertPrerenderHistoryLength(host_id, prerender_frame_host);
EXPECT_EQ(nullptr, EvalJs(prerender_frame_host, "history.state"));
EXPECT_EQ(current_request_count, GetRequestCount(k2ndUrl));
}
// Perform history.forward() in the prerendered page, which should be no-op.
{
int current_request_count = GetRequestCount(k2ndUrl);
ASSERT_EQ(nullptr, EvalJs(prerender_frame_host, "history.forward()"));
// Make sure that loading is not happening.
EXPECT_FALSE(FrameTreeNode::GloballyFindByID(host_id)
->frame_tree()
.IsLoadingIncludingInnerFrameTrees());
TestNavigationHistory(k2ndUrl, /*expected_history_index=*/1,
/*expected_history_length=*/2);
AssertPrerenderHistoryLength(host_id, prerender_frame_host);
EXPECT_EQ(nullptr, EvalJs(prerender_frame_host, "history.state"));
EXPECT_EQ(current_request_count, GetRequestCount(k2ndUrl));
}
}
// Make sure that activation appends the prerendering page's single navigation
// entry to the initiator page's joint session history. We can go back or
// forward after activation.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, SessionHistoryAfterActivation) {
// Navigate to an initial page.
const GURL kInitialUrl = GetUrl("/empty.html?initial");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
TestNavigationHistory(kInitialUrl, 0, 1);
// Navigate to another page.
const GURL k2ndUrl = GetUrl("/empty.html?2nd");
ASSERT_TRUE(NavigateToURL(shell(), k2ndUrl));
ASSERT_EQ(GetRequestCount(k2ndUrl), 1);
TestNavigationHistory(k2ndUrl, 1, 2);
// Start a prerender.
const GURL kPrerenderingUrl = GetUrl("/empty.html?prerender");
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
RenderFrameHost* prerender_frame_host = GetPrerenderedMainFrameHost(host_id);
ASSERT_EQ(GetRequestCount(kPrerenderingUrl), 1);
TestNavigationHistory(k2ndUrl, 1, 2);
// Call history.pushState(...) in prerendering.
ASSERT_EQ(nullptr, EvalJs(prerender_frame_host,
"history.pushState('teststate', null, null)"));
TestNavigationHistory(k2ndUrl, 1, 2);
AssertPrerenderHistoryLength(host_id, prerender_frame_host);
EXPECT_EQ("teststate", EvalJs(prerender_frame_host, "history.state"));
// Activate.
NavigatePrimaryPage(kPrerenderingUrl);
// The joint session history becomes [initial, 2nd, <prerender>].
TestNavigationHistory(kPrerenderingUrl, 2, 3);
EXPECT_EQ("teststate", EvalJs(web_contents(), "history.state"));
FrameTreeNode* root = static_cast<WebContentsImpl*>(web_contents())
->GetPrimaryFrameTree()
.root();
// Go Back.
{
FrameNavigateParamsCapturer capturer(root);
GoBack();
// The joint session history becomes [initial, <2nd>, prerender].
TestNavigationHistory(k2ndUrl, 1, 3);
EXPECT_EQ(nullptr, EvalJs(web_contents(), "history.state"));
EXPECT_EQ(NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY,
capturer.navigation_type());
EXPECT_FALSE(capturer.is_same_document());
}
// Go Forward.
{
FrameNavigateParamsCapturer capturer(root);
GoForward();
// The joint session history becomes [initial, 2nd, <prerender>].
TestNavigationHistory(kPrerenderingUrl, 2, 3);
EXPECT_EQ("teststate", EvalJs(web_contents(), "history.state"));
EXPECT_EQ(NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY,
capturer.navigation_type());
EXPECT_FALSE(capturer.is_same_document());
}
}
class PrerenderOopsifBrowserTest : public PrerenderBrowserTest {
public:
PrerenderOopsifBrowserTest() {
feature_list_.InitWithFeaturesAndParameters(
{{blink::features::kIsolateSandboxedIframes,
{{"grouping", "per-origin"}}}},
{/* disabled_features */});
}
private:
base::test::ScopedFeatureList feature_list_;
};
// Test for crbug.com/1470312.
// Prior to the CL that introduced this test, if IsolatedSandboxedIframes are
// enabled, and an isolated frame sends the parent a postMessage, then the
// proxies were attached to the active page and not the prerendered mainframe.
// These were proxies that were created on demand when processing the
// postMessage. (to ensure the recipient can reply to the sender frame, or to a
// frame that the sender could reach). This led to a CHECK failure in
// ~BrowsingContextInstance(). This test verifies that problem has been
// resolved.
IN_PROC_BROWSER_TEST_F(PrerenderOopsifBrowserTest,
OopsifSrcdocSandboxIframeWithPostmessage) {
// Navigate to an initial page.
const GURL kInitialUrl =
GetUrl("/prerender/cross_origin_prerender.html?initial");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
EXPECT_TRUE(AddTestUtilJS(current_frame_host()));
// Start a prerender.
const GURL kPrerenderingUrl =
GetUrl("/prerender/cross_origin_srcdoc_sandboxed_postmessage.html");
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
RenderFrameHost* prerender_frame_host = GetPrerenderedMainFrameHost(host_id);
EXPECT_TRUE(AddTestUtilJS(prerender_frame_host));
// Create a srcdoc iframe in the prerendered page.
EXPECT_TRUE(ExecJs(prerender_frame_host, "createSrcdoc();"));
base::RunLoop().RunUntilIdle();
// Load another same-origin iframe to ensure loading the srcdoc iframe
// starts and then it's deferred until activation.
const GURL kSameOriginSubframeUrl =
GetUrl("/prerender/cross_origin_prerender.html");
ASSERT_EQ("LOADED",
EvalJs(prerender_frame_host,
JsReplace("add_iframe($1)", kSameOriginSubframeUrl)));
// Activate.
NavigatePrimaryPage(kPrerenderingUrl);
ASSERT_EQ(web_contents()->GetLastCommittedURL(), kPrerenderingUrl);
// Verify postMessage from srcdoc to mainframe completed.
RenderFrameHostImpl* main_frame =
static_cast<RenderFrameHostImpl*>(web_contents()->GetPrimaryMainFrame());
EXPECT_TRUE(ExecJs(
main_frame,
"Promise.all([child_response_promise, prerender_handler_promise]);"));
// OOPSIFs only process-isolate if the parent gets site isolation, which in
// this case doesn't happen on Android.
if (AreAllSitesIsolatedForTesting()) {
RenderFrameHostImpl* sandboxed_render_frame_host =
main_frame->child_at(0)->current_frame_host();
EXPECT_TRUE(sandboxed_render_frame_host->GetSiteInstance()
->GetSiteInfo()
.is_sandboxed());
ASSERT_NE(main_frame->GetProcess(),
sandboxed_render_frame_host->GetProcess());
}
}
// Makes sure that cross-origin subframe navigations are deferred during
// prerendering.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
DeferCrossOriginSubframeNavigation) {
// Navigate to an initial page.
const GURL kInitialUrl =
GetUrl("/prerender/cross_origin_prerender.html?initial");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
EXPECT_TRUE(AddTestUtilJS(current_frame_host()));
// Start a prerender.
const GURL kPrerenderingUrl =
GetUrl("/prerender/cross_origin_prerender.html?prerender");
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
const GURL kSameOriginSubframeUrl =
GetUrl("/prerender/cross_origin_prerender.html?same_origin_iframe");
const GURL kCrossOriginSubframeUrl = GetCrossSiteUrl(
"/prerender/cross_origin_prerender.html?cross_origin_iframe");
ASSERT_EQ(GetRequestCount(kPrerenderingUrl), 1);
ASSERT_EQ(GetRequestCount(kSameOriginSubframeUrl), 0);
ASSERT_EQ(GetRequestCount(kCrossOriginSubframeUrl), 0);
// Add a cross-origin iframe to the prerendering page.
RenderFrameHost* prerender_frame_host = GetPrerenderedMainFrameHost(host_id);
EXPECT_TRUE(AddTestUtilJS(prerender_frame_host));
// Use ExecuteScriptAsync instead of EvalJs as inserted cross-origin iframe
// navigation would be deferred and script execution does not finish until
// the activation.
ExecuteScriptAsync(prerender_frame_host, JsReplace("add_iframe_async($1)",
kCrossOriginSubframeUrl));
base::RunLoop().RunUntilIdle();
// Add a same-origin iframe to the prerendering page.
ASSERT_EQ("LOADED",
EvalJs(prerender_frame_host,
JsReplace("add_iframe($1)", kSameOriginSubframeUrl)));
ASSERT_EQ(GetRequestCount(kPrerenderingUrl), 1);
ASSERT_EQ(GetRequestCount(kSameOriginSubframeUrl), 1);
ASSERT_EQ(GetRequestCount(kCrossOriginSubframeUrl), 0);
// Activate.
NavigatePrimaryPage(kPrerenderingUrl);
ASSERT_EQ(web_contents()->GetLastCommittedURL(), kPrerenderingUrl);
ASSERT_EQ("LOADED",
EvalJs(prerender_frame_host, JsReplace("wait_iframe_async($1)",
kCrossOriginSubframeUrl)));
ASSERT_EQ(GetRequestCount(kPrerenderingUrl), 1);
ASSERT_EQ(GetRequestCount(kSameOriginSubframeUrl), 1);
EXPECT_EQ(GetRequestCount(kCrossOriginSubframeUrl), 1);
const char kInitialDocumentPrerenderingScript[] =
"initial_document_prerendering";
const char kCurrentDocumentPrerenderingScript[] = "document.prerendering";
const char kOnprerenderingchangeObservedScript[] =
"onprerenderingchange_observed";
const char kActivationStartScript[] =
"performance.getEntriesByType('navigation')[0].activationStart";
EXPECT_EQ(true,
EvalJs(prerender_frame_host, kInitialDocumentPrerenderingScript));
EXPECT_EQ(false,
EvalJs(prerender_frame_host, kCurrentDocumentPrerenderingScript));
EXPECT_EQ(true,
EvalJs(prerender_frame_host, kOnprerenderingchangeObservedScript));
EXPECT_NE(0, EvalJs(prerender_frame_host, kActivationStartScript));
RenderFrameHost* same_origin_render_frame_host = FindRenderFrameHost(
prerender_frame_host->GetPage(), kSameOriginSubframeUrl);
CHECK(same_origin_render_frame_host);
EXPECT_EQ(true, EvalJs(same_origin_render_frame_host,
kInitialDocumentPrerenderingScript));
EXPECT_EQ(false, EvalJs(same_origin_render_frame_host,
kCurrentDocumentPrerenderingScript));
EXPECT_EQ(true, EvalJs(same_origin_render_frame_host,
kOnprerenderingchangeObservedScript));
EXPECT_NE(0, EvalJs(same_origin_render_frame_host, kActivationStartScript));
RenderFrameHost* cross_origin_render_frame_host = FindRenderFrameHost(
prerender_frame_host->GetPage(), kCrossOriginSubframeUrl);
CHECK(cross_origin_render_frame_host);
EXPECT_EQ(false, EvalJs(cross_origin_render_frame_host,
kInitialDocumentPrerenderingScript));
EXPECT_EQ(false, EvalJs(cross_origin_render_frame_host,
kCurrentDocumentPrerenderingScript));
EXPECT_EQ(false, EvalJs(cross_origin_render_frame_host,
kOnprerenderingchangeObservedScript));
EXPECT_EQ(0, EvalJs(cross_origin_render_frame_host, kActivationStartScript));
}
// Makes sure that subframe navigations are deferred if cross-origin redirects
// are observed in a prerendering page.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
DeferCrossOriginRedirectsOnSubframeNavigation) {
// Navigate to an initial page.
const GURL kInitialUrl =
GetUrl("/prerender/cross_origin_prerender.html?initial");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start a prerender.
const GURL kPrerenderingUrl =
GetUrl("/prerender/cross_origin_prerender.html?prerender");
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
const GURL kCrossOriginSubframeUrl = GetCrossSiteUrl(
"/prerender/cross_origin_prerender.html?cross_origin_iframe");
const GURL kServerRedirectSubframeUrl =
GetUrl("/server-redirect?" + kCrossOriginSubframeUrl.spec());
ASSERT_EQ(GetRequestCount(kPrerenderingUrl), 1);
ASSERT_EQ(GetRequestCount(kServerRedirectSubframeUrl), 0);
ASSERT_EQ(GetRequestCount(kCrossOriginSubframeUrl), 0);
// Add an iframe pointing to a server redirect page to the prerendering page.
RenderFrameHost* prerender_frame_host = GetPrerenderedMainFrameHost(host_id);
EXPECT_TRUE(AddTestUtilJS(prerender_frame_host));
// Use ExecuteScriptAsync instead of EvalJs as inserted iframe redirect
// navigation would be deferred and script execution does not finish until
// the activation.
ExecuteScriptAsync(
prerender_frame_host,
JsReplace("add_iframe_async($1)", kServerRedirectSubframeUrl));
WaitForRequest(kServerRedirectSubframeUrl, 1);
ASSERT_EQ(GetRequestCount(kServerRedirectSubframeUrl), 1);
ASSERT_EQ(GetRequestCount(kCrossOriginSubframeUrl), 0);
// Activate.
NavigatePrimaryPage(kPrerenderingUrl);
ASSERT_EQ(web_contents()->GetLastCommittedURL(), kPrerenderingUrl);
ASSERT_EQ("LOADED", EvalJs(prerender_frame_host,
JsReplace("wait_iframe_async($1)",
kServerRedirectSubframeUrl)));
EXPECT_EQ(GetRequestCount(kServerRedirectSubframeUrl), 1);
EXPECT_EQ(GetRequestCount(kCrossOriginSubframeUrl), 1);
const char kInitialDocumentPrerenderingScript[] =
"initial_document_prerendering";
const char kCurrentDocumentPrerenderingScript[] = "document.prerendering";
const char kOnprerenderingchangeObservedScript[] =
"onprerenderingchange_observed";
EXPECT_EQ(true,
EvalJs(prerender_frame_host, kInitialDocumentPrerenderingScript));
EXPECT_EQ(false,
EvalJs(prerender_frame_host, kCurrentDocumentPrerenderingScript));
EXPECT_EQ(true,
EvalJs(prerender_frame_host, kOnprerenderingchangeObservedScript));
RenderFrameHost* cross_origin_render_frame_host = FindRenderFrameHost(
prerender_frame_host->GetPage(), kCrossOriginSubframeUrl);
CHECK(cross_origin_render_frame_host);
EXPECT_EQ(false, EvalJs(cross_origin_render_frame_host,
kInitialDocumentPrerenderingScript));
EXPECT_EQ(false, EvalJs(cross_origin_render_frame_host,
kCurrentDocumentPrerenderingScript));
EXPECT_EQ(false, EvalJs(cross_origin_render_frame_host,
kOnprerenderingchangeObservedScript));
}
// Tests for main frame navigation in a prerendered page.
class PrerenderMainFrameNavigationBrowserTest
: public testing::WithParamInterface<PreloadingTriggerType>,
public PrerenderBrowserTest {
protected:
enum class NavigationType {
kSameOrigin,
kSameSiteCrossOrigin,
kSameSiteCrossOriginWithOptIn,
kCrossSite,
};
// Runs navigations in the `navigations_types` order and makes sure it ends
// with `expected_status`.
void TestMainFrameNavigation(
const std::vector<NavigationType>& navigation_types,
PrerenderFinalStatus expected_status) {
ASSERT_FALSE(navigation_types.empty());
PreloadingTriggerType trigger_type = GetParam();
std::vector<GURL> urls;
for (auto type : navigation_types) {
urls.push_back(CreateUrl(type));
}
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/empty.html?prerender");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start a prerender.
FrameTreeNodeId host_id;
std::unique_ptr<PrerenderHandle> prerender_handle;
switch (trigger_type) {
case PreloadingTriggerType::kSpeculationRule:
host_id = AddPrerender(kPrerenderingUrl);
break;
case PreloadingTriggerType::kSpeculationRuleFromIsolatedWorld:
host_id = AddPrerender(kPrerenderingUrl, /*world_id=*/1);
break;
case PreloadingTriggerType::kEmbedder:
prerender_handle = AddEmbedderTriggeredPrerender(kPrerenderingUrl);
host_id = static_cast<PrerenderHandleImpl*>(prerender_handle.get())
->frame_tree_node_id_for_testing();
break;
case PreloadingTriggerType::kSpeculationRuleFromAutoSpeculationRules:
FAIL() << "Auto speculation rules does not work with empty.html";
}
ASSERT_TRUE(host_id);
test::PrerenderHostObserver observer(*web_contents_impl(), host_id);
// Run navigations in the main frame of the prerendered page. Only the last
// URL of the given navigation URLs will separately be handled later as that
// could cancel prerendering and never finish.
for (auto it = urls.begin(); it != urls.end() - 1; ++it) {
TestNavigationManager navigation_observer(web_contents(), *it);
NavigatePrerenderedPage(host_id, *it);
ASSERT_TRUE(navigation_observer.WaitForNavigationFinished());
EXPECT_TRUE(navigation_observer.was_successful());
}
// The last navigation URL. This should cancel prerendering if the
// expectation is not kActivated.
const GURL& last_url = urls.back();
switch (expected_status) {
case PrerenderFinalStatus::kActivated: {
// Navigation to the last URL should succeed.
TestNavigationManager navigation_observer(web_contents(), last_url);
NavigatePrerenderedPage(host_id, last_url);
ASSERT_TRUE(navigation_observer.WaitForNavigationFinished());
EXPECT_TRUE(navigation_observer.was_successful());
// Activation should succeed.
switch (trigger_type) {
case PreloadingTriggerType::kSpeculationRule:
case PreloadingTriggerType::kSpeculationRuleFromIsolatedWorld:
NavigatePrimaryPage(kPrerenderingUrl);
break;
case PreloadingTriggerType::kEmbedder:
NavigatePrimaryPageFromAddressBar(kPrerenderingUrl);
break;
case PreloadingTriggerType::kSpeculationRuleFromAutoSpeculationRules:
FAIL() << "Auto speculation rules does not work with empty.html";
}
observer.WaitForActivation();
EXPECT_TRUE(observer.was_activated());
EXPECT_EQ(web_contents()->GetLastCommittedURL(), last_url);
break;
}
default: {
// Navigation to the last URL should cancel prerendering.
NavigatePrerenderedPage(host_id, last_url);
observer.WaitForDestroyed();
EXPECT_FALSE(HasHostForUrl(kPrerenderingUrl));
break;
}
}
// Verify UMA/UKM records.
switch (trigger_type) {
case PreloadingTriggerType::kSpeculationRule:
ExpectFinalStatusForSpeculationRule(expected_status);
break;
case PreloadingTriggerType::kSpeculationRuleFromIsolatedWorld:
ExpectFinalStatusForSpeculationRuleFromIsolatedWorld(expected_status);
break;
case PreloadingTriggerType::kEmbedder:
ExpectFinalStatusForEmbedder(expected_status);
break;
case PreloadingTriggerType::kSpeculationRuleFromAutoSpeculationRules:
FAIL() << "Auto speculation rules does not work with empty.html";
}
}
// Runs redirections in the `navigations_types` order and makes sure it ends
// with `expected_status`.
void TestMainFrameRedirection(
const std::vector<NavigationType>& redirection_types,
PrerenderFinalStatus expected_status) {
ASSERT_FALSE(redirection_types.empty());
PreloadingTriggerType trigger_type = GetParam();
// Create a URL that rus a redirection sequence in the order of
// `redirection_types`. To make the URL, create a final URL from the last
// element of `redirection_types` and then prefix a rediretion URL by
// iterating the types in reverse order.
const GURL final_url = CreateUrl(redirection_types.back());
GURL url = final_url;
for (auto it = redirection_types.rbegin() + 1;
it != redirection_types.rend(); ++it) {
url = CreateRedirectionUrl(*it, url);
}
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/empty.html?prerender");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start a prerender.
FrameTreeNodeId host_id;
std::unique_ptr<PrerenderHandle> prerender_handle;
switch (trigger_type) {
case PreloadingTriggerType::kSpeculationRule:
host_id = AddPrerender(kPrerenderingUrl);
break;
case PreloadingTriggerType::kSpeculationRuleFromIsolatedWorld:
host_id = AddPrerender(kPrerenderingUrl, /*world_id=*/1);
break;
case PreloadingTriggerType::kEmbedder:
prerender_handle = AddEmbedderTriggeredPrerender(kPrerenderingUrl);
host_id = static_cast<PrerenderHandleImpl*>(prerender_handle.get())
->frame_tree_node_id_for_testing();
break;
case PreloadingTriggerType::kSpeculationRuleFromAutoSpeculationRules:
FAIL() << "Auto speculation rules does not work with empty.html";
}
ASSERT_TRUE(host_id);
test::PrerenderHostObserver observer(*web_contents_impl(), host_id);
// Run redirections in the main frame of the prerendered page.
TestNavigationManager navigation_observer(web_contents(), url);
NavigatePrerenderedPage(host_id, url);
ASSERT_TRUE(navigation_observer.WaitForNavigationFinished());
switch (expected_status) {
case PrerenderFinalStatus::kActivated: {
// Redirections should succeed.
EXPECT_TRUE(navigation_observer.was_successful());
// Activation should succeed.
switch (trigger_type) {
case PreloadingTriggerType::kSpeculationRule:
case PreloadingTriggerType::kSpeculationRuleFromIsolatedWorld:
NavigatePrimaryPage(kPrerenderingUrl);
break;
case PreloadingTriggerType::kEmbedder:
NavigatePrimaryPageFromAddressBar(kPrerenderingUrl);
break;
case PreloadingTriggerType::kSpeculationRuleFromAutoSpeculationRules:
FAIL() << "Auto speculation rules does not work with empty.html";
}
observer.WaitForActivation();
EXPECT_TRUE(observer.was_activated());
EXPECT_EQ(web_contents()->GetLastCommittedURL(), final_url);
break;
}
default: {
// Redirections should cancel prerendering.
EXPECT_FALSE(navigation_observer.was_successful());
observer.WaitForDestroyed();
EXPECT_FALSE(HasHostForUrl(kPrerenderingUrl));
break;
}
}
// Verify UMA/UKM records.
switch (trigger_type) {
case PreloadingTriggerType::kSpeculationRule:
ExpectFinalStatusForSpeculationRule(expected_status);
break;
case PreloadingTriggerType::kSpeculationRuleFromIsolatedWorld:
ExpectFinalStatusForSpeculationRuleFromIsolatedWorld(expected_status);
break;
case PreloadingTriggerType::kEmbedder:
ExpectFinalStatusForEmbedder(expected_status);
break;
case PreloadingTriggerType::kSpeculationRuleFromAutoSpeculationRules:
FAIL() << "Auto speculation rules does not work with empty.html";
}
}
private:
GURL CreateUrl(NavigationType type) {
static int number_for_prefix = 0;
std::string prefix = base::NumberToString(number_for_prefix++);
switch (type) {
case NavigationType::kSameOrigin:
return GetUrl("/empty.html?" + prefix);
case NavigationType::kSameSiteCrossOrigin:
return GetSameSiteCrossOriginUrl("/empty.html?" + prefix);
case NavigationType::kSameSiteCrossOriginWithOptIn:
return GetSameSiteCrossOriginUrl(
"/prerender/prerender_with_opt_in_header.html?" + prefix);
case NavigationType::kCrossSite:
return GetCrossSiteUrl("/empty.html?" + prefix);
}
}
// Creates a URL that redirects to `url_to_redirect`. The origin of the URL is
// determined by `type`.
GURL CreateRedirectionUrl(NavigationType type, const GURL& url_to_redirect) {
switch (type) {
case NavigationType::kSameOrigin:
return GetUrl("/server-redirect?" + url_to_redirect.spec());
case NavigationType::kSameSiteCrossOrigin:
return GetSameSiteCrossOriginUrl("/server-redirect?" +
url_to_redirect.spec());
case NavigationType::kSameSiteCrossOriginWithOptIn:
return GetSameSiteCrossOriginUrl(
"/server-redirect-credentialed-prerender?" +
url_to_redirect.spec());
case NavigationType::kCrossSite:
return GetCrossSiteUrl("/server-redirect?" + url_to_redirect.spec());
}
}
};
INSTANTIATE_TEST_SUITE_P(
All,
PrerenderMainFrameNavigationBrowserTest,
testing::Values(PreloadingTriggerType::kSpeculationRule,
PreloadingTriggerType::kSpeculationRuleFromIsolatedWorld,
PreloadingTriggerType::kEmbedder),
[](const testing::TestParamInfo<PreloadingTriggerType>& info) {
switch (info.param) {
case PreloadingTriggerType::kSpeculationRule:
return "SpeculationRule";
case PreloadingTriggerType::kSpeculationRuleFromIsolatedWorld:
return "SpeculationRuleFromIsolatedWorld";
case PreloadingTriggerType::kEmbedder:
return "Embedder";
case PreloadingTriggerType::kSpeculationRuleFromAutoSpeculationRules:
ADD_FAILURE() << "Auto speculation rules does not work with "
"TestMainFrameNavigation";
return "SpeculationRuleFromAutoSpeculationRules";
}
});
IN_PROC_BROWSER_TEST_P(PrerenderMainFrameNavigationBrowserTest, SameOrigin) {
std::vector<NavigationType> navigations = {NavigationType::kSameOrigin};
TestMainFrameNavigation(navigations, PrerenderFinalStatus::kActivated);
}
IN_PROC_BROWSER_TEST_P(PrerenderMainFrameNavigationBrowserTest,
SameSiteCrossOriginWithOptIn) {
std::vector<NavigationType> navigations = {
NavigationType::kSameSiteCrossOriginWithOptIn};
TestMainFrameNavigation(navigations, PrerenderFinalStatus::kActivated);
}
IN_PROC_BROWSER_TEST_P(PrerenderMainFrameNavigationBrowserTest,
SameSiteCrossOrigin) {
std::vector<NavigationType> navigations = {
NavigationType::kSameSiteCrossOrigin};
TestMainFrameNavigation(
navigations,
PrerenderFinalStatus::
kSameSiteCrossOriginNavigationNotOptInInMainFrameNavigation);
}
IN_PROC_BROWSER_TEST_P(PrerenderMainFrameNavigationBrowserTest, CrossSite) {
std::vector<NavigationType> navigations = {NavigationType::kCrossSite};
TestMainFrameNavigation(
navigations,
PrerenderFinalStatus::kCrossSiteNavigationInMainFrameNavigation);
}
IN_PROC_BROWSER_TEST_P(PrerenderMainFrameNavigationBrowserTest,
SameSiteCrossOriginWithOptIn_SameOrigin) {
std::vector<NavigationType> navigations = {
NavigationType::kSameSiteCrossOriginWithOptIn,
NavigationType::kSameOrigin};
TestMainFrameNavigation(navigations, PrerenderFinalStatus::kActivated);
}
IN_PROC_BROWSER_TEST_P(
PrerenderMainFrameNavigationBrowserTest,
SameSiteCrossOriginWithOptIn_SameSiteCrossOriginWithOptIn) {
std::vector<NavigationType> navigations = {
NavigationType::kSameSiteCrossOriginWithOptIn,
NavigationType::kSameSiteCrossOriginWithOptIn};
TestMainFrameNavigation(navigations, PrerenderFinalStatus::kActivated);
}
IN_PROC_BROWSER_TEST_P(PrerenderMainFrameNavigationBrowserTest,
SameSiteCrossOriginWithOptIn_SameSiteCrossOrigin) {
std::vector<NavigationType> navigations = {
NavigationType::kSameSiteCrossOriginWithOptIn,
NavigationType::kSameSiteCrossOrigin};
TestMainFrameNavigation(
navigations,
PrerenderFinalStatus::
kSameSiteCrossOriginNavigationNotOptInInMainFrameNavigation);
}
IN_PROC_BROWSER_TEST_P(PrerenderMainFrameNavigationBrowserTest,
SameSiteCrossOrigin_CrossSite) {
std::vector<NavigationType> navigations = {
NavigationType::kSameSiteCrossOriginWithOptIn,
NavigationType::kCrossSite};
TestMainFrameNavigation(
navigations,
PrerenderFinalStatus::kCrossSiteNavigationInMainFrameNavigation);
}
IN_PROC_BROWSER_TEST_P(PrerenderMainFrameNavigationBrowserTest,
Redirection_SameOrigin_SameOrigin) {
std::vector<NavigationType> redirections = {NavigationType::kSameOrigin,
NavigationType::kSameOrigin};
TestMainFrameRedirection(redirections, PrerenderFinalStatus::kActivated);
}
IN_PROC_BROWSER_TEST_P(PrerenderMainFrameNavigationBrowserTest,
Redirection_SameOrigin_SameSiteCrossOriginWithOptIn) {
std::vector<NavigationType> redirections = {
NavigationType::kSameOrigin,
NavigationType::kSameSiteCrossOriginWithOptIn};
TestMainFrameRedirection(redirections, PrerenderFinalStatus::kActivated);
}
IN_PROC_BROWSER_TEST_P(PrerenderMainFrameNavigationBrowserTest,
Redirection_SameOrigin_SameSiteCrossOrigin) {
std::vector<NavigationType> redirections = {
NavigationType::kSameOrigin, NavigationType::kSameSiteCrossOrigin};
TestMainFrameRedirection(
redirections,
PrerenderFinalStatus::
kSameSiteCrossOriginRedirectNotOptInInMainFrameNavigation);
}
IN_PROC_BROWSER_TEST_P(PrerenderMainFrameNavigationBrowserTest,
Redirection_SameOrigin_CrossSite) {
std::vector<NavigationType> redirections = {NavigationType::kSameOrigin,
NavigationType::kCrossSite};
TestMainFrameRedirection(
redirections,
PrerenderFinalStatus::kCrossSiteRedirectInMainFrameNavigation);
}
IN_PROC_BROWSER_TEST_P(PrerenderMainFrameNavigationBrowserTest,
Redirection_SameSiteCrossOriginWithOptIn_SameOrigin) {
std::vector<NavigationType> redirections = {
NavigationType::kSameSiteCrossOriginWithOptIn,
NavigationType::kSameOrigin};
TestMainFrameRedirection(redirections, PrerenderFinalStatus::kActivated);
}
IN_PROC_BROWSER_TEST_P(
PrerenderMainFrameNavigationBrowserTest,
Redirection_SameSiteCrossOriginWithOptIn_SameSiteCrossOriginWithOptIn) {
std::vector<NavigationType> redirections = {
NavigationType::kSameSiteCrossOriginWithOptIn,
NavigationType::kSameSiteCrossOriginWithOptIn};
TestMainFrameRedirection(redirections, PrerenderFinalStatus::kActivated);
}
IN_PROC_BROWSER_TEST_P(
PrerenderMainFrameNavigationBrowserTest,
Redirection_SameSiteCrossOriginWithOptIn_SameSiteCrossOrigin) {
std::vector<NavigationType> redirections = {
NavigationType::kSameSiteCrossOriginWithOptIn,
NavigationType::kSameSiteCrossOrigin};
TestMainFrameRedirection(
redirections,
PrerenderFinalStatus::
kSameSiteCrossOriginRedirectNotOptInInMainFrameNavigation);
}
IN_PROC_BROWSER_TEST_P(PrerenderMainFrameNavigationBrowserTest,
Redirection_SameSiteCrossOriginWithOptIn_CrossSite) {
std::vector<NavigationType> redirections = {
NavigationType::kSameSiteCrossOriginWithOptIn,
NavigationType::kCrossSite};
TestMainFrameRedirection(
redirections,
PrerenderFinalStatus::kCrossSiteRedirectInMainFrameNavigation);
}
IN_PROC_BROWSER_TEST_P(
PrerenderMainFrameNavigationBrowserTest,
Redirection_SameOrigin_SameSiteCrossOriginWithOptIn_SameOrigin) {
std::vector<NavigationType> redirections = {
NavigationType::kSameOrigin,
NavigationType::kSameSiteCrossOriginWithOptIn,
NavigationType::kSameOrigin};
TestMainFrameRedirection(redirections, PrerenderFinalStatus::kActivated);
}
IN_PROC_BROWSER_TEST_P(
PrerenderMainFrameNavigationBrowserTest,
Redirection_SameOrigin_SameSiteCrossOriginWithOptIn_SameSiteCrossOriginWithOptIn) {
std::vector<NavigationType> redirections = {
NavigationType::kSameOrigin,
NavigationType::kSameSiteCrossOriginWithOptIn,
NavigationType::kSameSiteCrossOriginWithOptIn};
TestMainFrameRedirection(redirections, PrerenderFinalStatus::kActivated);
}
IN_PROC_BROWSER_TEST_P(
PrerenderMainFrameNavigationBrowserTest,
Redirection_SameOrigin_SameSiteCrossOriginWithOptIn_SameSiteCrossOrigin) {
std::vector<NavigationType> redirections = {
NavigationType::kSameOrigin,
NavigationType::kSameSiteCrossOriginWithOptIn,
NavigationType::kSameSiteCrossOrigin};
TestMainFrameRedirection(
redirections,
PrerenderFinalStatus::
kSameSiteCrossOriginRedirectNotOptInInMainFrameNavigation);
}
IN_PROC_BROWSER_TEST_P(
PrerenderMainFrameNavigationBrowserTest,
Redirection_SameOrigin_SameSiteCrossOriginWithOptIn_CrossSite) {
std::vector<NavigationType> redirections = {
NavigationType::kSameOrigin,
NavigationType::kSameSiteCrossOriginWithOptIn,
NavigationType::kCrossSite};
TestMainFrameRedirection(
redirections,
PrerenderFinalStatus::kCrossSiteRedirectInMainFrameNavigation);
}
IN_PROC_BROWSER_TEST_P(
PrerenderMainFrameNavigationBrowserTest,
Redirection_SameSiteCrossOriginWithOptIn_SameOrigin_SameOrigin) {
std::vector<NavigationType> redirections = {
NavigationType::kSameSiteCrossOriginWithOptIn,
NavigationType::kSameOrigin, NavigationType::kSameOrigin};
TestMainFrameRedirection(redirections, PrerenderFinalStatus::kActivated);
}
IN_PROC_BROWSER_TEST_P(
PrerenderMainFrameNavigationBrowserTest,
Redirection_SameSiteCrossOriginWithOptIn_SameOrigin_SameSiteCrossOriginWithOptIn) {
std::vector<NavigationType> redirections = {
NavigationType::kSameSiteCrossOriginWithOptIn,
NavigationType::kSameOrigin,
NavigationType::kSameSiteCrossOriginWithOptIn};
TestMainFrameRedirection(redirections, PrerenderFinalStatus::kActivated);
}
IN_PROC_BROWSER_TEST_P(
PrerenderMainFrameNavigationBrowserTest,
Redirection_SameSiteCrossOriginWithOptIn_SameOrigin_SameSiteCrossOrigin) {
std::vector<NavigationType> redirections = {
NavigationType::kSameSiteCrossOriginWithOptIn,
NavigationType::kSameOrigin, NavigationType::kSameSiteCrossOrigin};
TestMainFrameRedirection(
redirections,
PrerenderFinalStatus::
kSameSiteCrossOriginRedirectNotOptInInMainFrameNavigation);
}
IN_PROC_BROWSER_TEST_P(
PrerenderMainFrameNavigationBrowserTest,
Redirection_SameSiteCrossOriginWithOptIn_SameOrigin_CrossSite) {
std::vector<NavigationType> redirections = {
NavigationType::kSameSiteCrossOriginWithOptIn,
NavigationType::kSameOrigin, NavigationType::kCrossSite};
TestMainFrameRedirection(
redirections,
PrerenderFinalStatus::kCrossSiteRedirectInMainFrameNavigation);
}
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, MainFrameNavigation_NonHttpUrl) {
const GURL initial_url = GetUrl("/empty.html");
const GURL prerendering_url = GetUrl("/empty.html?prerender");
// Note that local schemes (e.g., data URL) don't work for this test as
// renderer-initiated navigation to those schemes are blocked by unrelated
// navigation throttles like BlockedSchemeNavigationThrottle.
const GURL non_http_url("ftp://example.com/");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
ASSERT_EQ(web_contents()->GetLastCommittedURL(), initial_url);
// Start prerendering.
FrameTreeNodeId host_id = AddPrerender(prerendering_url);
ASSERT_TRUE(host_id);
// Navigation to a non-http(s) URL on a prerendered page should cancel
// prerendering.
TestNavigationManager navigation_observer(web_contents(), non_http_url);
NavigatePrerenderedPage(host_id, non_http_url);
ASSERT_TRUE(navigation_observer.WaitForNavigationFinished());
EXPECT_FALSE(navigation_observer.was_successful());
ExpectFinalStatusForSpeculationRule(
PrerenderFinalStatus::kInvalidSchemeNavigation);
}
// Regression test for https://crbug.com/1198051
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, MainFrameFragmentNavigation) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl =
GetUrl("/navigation_controller/hash_anchor_with_iframe.html");
const GURL kAnchorUrl =
GetUrl("/navigation_controller/hash_anchor_with_iframe.html#Test");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start a prerender.
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
// Do a fragment navigation.
NavigatePrerenderedPage(host_id, kAnchorUrl);
WaitForPrerenderLoadCompletion(host_id);
RedirectChainObserver redirect_chain_observer(*shell()->web_contents(),
kAnchorUrl);
// Activate.
NavigatePrimaryPage(kPrerenderingUrl);
// Regression test for https://crbug.com/1211274. Make sure that we don't
// crash when activating a prerendered page which performed a fragment
// navigation.
ASSERT_EQ(1u, redirect_chain_observer.redirect_chain().size());
EXPECT_EQ(kAnchorUrl, redirect_chain_observer.redirect_chain()[0]);
// Make sure the render is not dead by doing a same page navigation.
NavigatePrimaryPage(kAnchorUrl);
// Make sure we did activate the page and issued no network requests
EXPECT_EQ(GetRequestCount(kPrerenderingUrl), 1);
}
// Makes sure that activation on navigation for a pop-up window doesn't happen.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, Activation_PopUpWindow) {
// Navigate to an initial page.
const GURL kInitialUrl = GetUrl("/empty.html");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
EXPECT_TRUE(AddTestUtilJS(current_frame_host()));
// Start a prerender.
const GURL kPrerenderingUrl = GetUrl("/empty.html?prerender");
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
// Attempt to activate the prerendered page for a pop-up window. This should
// fail and fallback to network request.
ASSERT_EQ(GetRequestCount(kPrerenderingUrl), 1);
EXPECT_EQ("LOADED", EvalJs(web_contents(),
JsReplace("open_window($1)", kPrerenderingUrl)));
EXPECT_EQ(GetRequestCount(kPrerenderingUrl), 2);
// Activation shouldn't happen, so the prerender host should not be consumed.
EXPECT_EQ(GetHostForUrl(kPrerenderingUrl), host_id);
}
// Makes sure that activation on navigation for a page that has a pop-up window
// doesn't happen.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, Activation_PageWithPopUpWindow) {
// Navigate to an initial page.
const GURL kInitialUrl = GetUrl("/empty.html");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
EXPECT_TRUE(AddTestUtilJS(current_frame_host()));
// Start a prerender.
const GURL kPrerenderingUrl = GetUrl("/empty.html?prerender_next");
AddPrerender(kPrerenderingUrl);
ASSERT_TRUE(HasHostForUrl(kPrerenderingUrl));
// Open a pop-up window.
const GURL kWindowUrl = GetUrl("/empty.html?prerender_window");
EXPECT_EQ("LOADED",
EvalJs(web_contents(), JsReplace("open_window($1)", kWindowUrl)));
// Attempt to activate the prerendered page for the top-level frame. This
// should fail and fallback to network request because the pop-up window
// exists.
ASSERT_EQ(GetRequestCount(kPrerenderingUrl), 1);
NavigatePrimaryPage(kPrerenderingUrl);
EXPECT_EQ(web_contents()->GetLastCommittedURL(), kPrerenderingUrl);
EXPECT_EQ(GetRequestCount(kPrerenderingUrl), 2);
// The prerender host should be canceled.
ExpectFinalStatusForSpeculationRule(
PrerenderFinalStatus::kActivatedWithAuxiliaryBrowsingContexts);
}
// This is the same as Activation_PageWithPopUpWindow test but `window.opener`
// will be nullified after it is open. The window loses the communication with
// the opener but it is still treated as an auxiliary context in the browser
// internal, so the activation should fail.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
Activation_PageWithPopUpWindow_OpenerIsNullified) {
// Navigate to an initial page.
const GURL initial_url = GetUrl("/empty.html");
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
EXPECT_TRUE(AddTestUtilJS(current_frame_host()));
// Start a prerender.
const GURL prerendering_url = GetUrl("/empty.html?prerender_next");
AddPrerender(prerendering_url);
ASSERT_TRUE(HasHostForUrl(prerendering_url));
// Open a pop-up window that initially has an opener but it is nullified
// right away.
const GURL window_url = GetUrl("/empty.html?prerender_window");
const std::string kOpenWindowAndNullifyScript = R"(
const win = window.open($1, '_blank');
win.opener = null;
)";
TestNavigationObserver nav_observer(window_url);
nav_observer.StartWatchingNewWebContents();
EXPECT_TRUE(ExecJs(web_contents(),
JsReplace(kOpenWindowAndNullifyScript, window_url)));
nav_observer.WaitForNavigationFinished();
// Attempt to activate the prerendered page for the top-level frame. This
// should fail and fallback to network request because the pop-up window
// exists.
ASSERT_EQ(GetRequestCount(prerendering_url), 1);
NavigatePrimaryPage(prerendering_url);
EXPECT_EQ(web_contents()->GetLastCommittedURL(), prerendering_url);
EXPECT_EQ(GetRequestCount(prerendering_url), 2);
// The prerender host should be canceled.
ExpectFinalStatusForSpeculationRule(
PrerenderFinalStatus::kActivatedWithAuxiliaryBrowsingContexts);
}
// Tests that all RenderFrameHostImpls in the prerendering page know the
// prerendering state.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderIframe) {
TestHostPrerenderingState(GetUrl("/page_with_iframe.html"));
}
// Blank <iframe> is a special case. Tests that the blank iframe knows the
// prerendering state as well.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderBlankIframe) {
TestHostPrerenderingState(GetUrl("/page_with_blank_iframe.html"));
}
using PrerenderBrowserDeathTest = PrerenderBrowserTest;
// Tests that an inner WebContents cannot be attached in a prerendered page.
// See https://crbug.com/40191159 for details.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserDeathTest,
PrerenderCannotHaveInnerContents) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/page_with_blank_iframe.html");
const GURL kInnerContentsUrl = GetUrl("/empty.html?prerender");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
RenderFrameHostImpl* prerendered_render_frame_host =
GetPrerenderedMainFrameHost(host_id);
EXPECT_CHECK_DEATH({
CreateAndAttachInnerContents(
prerendered_render_frame_host->child_at(0)->current_frame_host());
});
}
// Ensure that whether or not a NavigationRequest is for a prerender activation
// is available in WebContentsObserver::DidStartNavigation.
class IsActivationObserver : public WebContentsObserver {
public:
IsActivationObserver(WebContents& web_contents, const GURL& url)
: WebContentsObserver(&web_contents), url_(url) {}
bool did_navigate() { return did_navigate_; }
bool was_activation() { return was_activation_; }
private:
void DidStartNavigation(NavigationHandle* handle) override {
if (handle->GetURL() != url_) {
return;
}
did_navigate_ = true;
was_activation_ = handle->IsPrerenderedPageActivation();
}
const GURL url_;
bool did_navigate_ = false;
bool was_activation_ = false;
};
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
NavigationRequestIsPrerenderedPageActivation) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/empty.html?prerender");
test::PrerenderHostObserver prerender_observer(*shell()->web_contents(),
kPrerenderingUrl);
// Navigate to an initial page and start a prerender. Note, AddPrerender will
// wait until the prerendered page has finished navigating.
{
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
ASSERT_EQ(web_contents()->GetLastCommittedURL(), kInitialUrl);
AddPrerender(kPrerenderingUrl);
}
IsActivationObserver is_activation_observer(*shell()->web_contents(),
kPrerenderingUrl);
// Now navigate the primary page to the prerendered URL so that we activate
// the prerender.
{
ASSERT_TRUE(ExecJs(web_contents()->GetPrimaryMainFrame(),
JsReplace("location = $1", kPrerenderingUrl)));
prerender_observer.WaitForActivation();
}
// Ensure that WebContentsObservers see the correct value for
// IsPrerenderedPageActivation in DidStartNavigation.
ASSERT_TRUE(is_activation_observer.did_navigate());
EXPECT_TRUE(is_activation_observer.was_activation());
}
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, ActivationDoesntRunThrottles) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/empty.html?prerender");
test::PrerenderHostObserver prerender_observer(*shell()->web_contents(),
kPrerenderingUrl);
// Navigate to the initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
ASSERT_EQ(web_contents()->GetLastCommittedURL(), kInitialUrl);
ASSERT_TRUE(WaitForLoadStop(shell()->web_contents()));
NavigationThrottle* throttle = nullptr;
// This will attempt to insert a throttle that DEFERs the navigation at
// WillStartRequest into all new navigations.
ShellContentBrowserClient::Get()
->set_create_throttles_for_navigation_callback(base::BindLambdaForTesting(
[&throttle](NavigationThrottleRegistry& registry) -> void {
auto throttle_ptr =
std::make_unique<TestNavigationThrottle>(registry);
CHECK(!throttle);
throttle = throttle_ptr.get();
throttle_ptr->SetResponse(
TestNavigationThrottle::WILL_START_REQUEST,
TestNavigationThrottle::SYNCHRONOUS, NavigationThrottle::DEFER);
registry.AddThrottle(std::move(throttle_ptr));
}));
// Start a prerender and ensure that a NavigationThrottle can defer the
// prerendering navigation. Then resume the navigation so the prerender
// navigation and load completes.
{
TestNavigationManager prerender_manager(shell()->web_contents(),
kPrerenderingUrl);
AddPrerenderAsync(kPrerenderingUrl);
ASSERT_TRUE(prerender_manager.WaitForFirstYieldAfterDidStartNavigation());
ASSERT_NE(throttle, nullptr);
auto* request =
NavigationRequest::From(prerender_manager.GetNavigationHandle());
ASSERT_TRUE(request->IsDeferredForTesting());
EXPECT_EQ(request->GetDeferringThrottleForTesting(), throttle);
throttle = nullptr;
request->GetNavigationThrottleRunnerForTesting()->CallResumeForTesting();
ASSERT_TRUE(prerender_manager.WaitForNavigationFinished());
FrameTreeNodeId host_id = GetHostForUrl(kPrerenderingUrl);
EXPECT_EQ(GetPrerenderedMainFrameHost(host_id)->GetLastCommittedURL(),
kPrerenderingUrl);
}
// Now navigate the primary page to the prerendered URL so that we activate
// the prerender. The throttle should not have been registered for the
// activating navigation.
{
NavigatePrimaryPage(kPrerenderingUrl);
prerender_observer.WaitForActivation();
EXPECT_EQ(web_contents()->GetLastCommittedURL(), kPrerenderingUrl);
EXPECT_EQ(throttle, nullptr);
}
}
// Ensures that if we attempt to open a URL while prerendering with a window
// disposition other than CURRENT_TAB, we fail.
IN_PROC_BROWSER_TEST_P(PrerenderTargetAgnosticBrowserTest, SuppressOpenURL) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/empty.html?prerender1");
const GURL kSecondUrl = GetUrl("/empty.html?prerender2");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
ASSERT_EQ(web_contents()->GetLastCommittedURL(), kInitialUrl);
// Start prerendering `kPrerenderingUrl`.
ASSERT_EQ(GetRequestCount(kPrerenderingUrl), 0);
FrameTreeNodeId host_id = prerender_helper()->AddPrerender(
kPrerenderingUrl, /*eagerness=*/std::nullopt, GetTargetHint());
auto* prerender_web_contents = WebContents::FromFrameTreeNodeId(host_id);
RenderFrameHost* prerendered_render_frame_host =
test::PrerenderTestHelper::GetPrerenderedMainFrameHost(
*prerender_web_contents, host_id);
EXPECT_EQ(GetRequestCount(kPrerenderingUrl), 1);
OpenURLParams params(kSecondUrl, Referrer(),
prerendered_render_frame_host->GetFrameTreeNodeId(),
WindowOpenDisposition::NEW_WINDOW,
ui::PAGE_TRANSITION_LINK, true);
params.initiator_origin =
prerendered_render_frame_host->GetLastCommittedOrigin();
params.source_render_process_id =
prerendered_render_frame_host->GetProcess()->GetDeprecatedID();
params.source_render_frame_id = prerendered_render_frame_host->GetRoutingID();
auto* new_web_contents = prerender_web_contents->OpenURL(
params, /*navigation_handle_callback=*/{});
EXPECT_EQ(nullptr, new_web_contents);
}
// Tests that `RenderFrameHostImpl::ForEachRenderFrameHostImpl` and
// `WebContentsImpl::ForEachRenderFrameHostImpl` behave correctly when
// prerendering.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, ForEachRenderFrameHostImpl) {
const GURL kInitialUrl = GetUrl("/empty.html");
// All frames are same-origin due to prerendering restrictions for
// cross-origin.
const GURL kPrerenderingUrl =
GetUrl("/cross_site_iframe_factory.html?a.test(a.test(a.test),a.test)");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
RenderFrameHostImpl* initiator_render_frame_host = current_frame_host();
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
RenderFrameHostImpl* prerendered_render_frame_host =
GetPrerenderedMainFrameHost(host_id);
RenderFrameHostImpl* rfh_sub_1 =
prerendered_render_frame_host->child_at(0)->current_frame_host();
RenderFrameHostImpl* rfh_sub_1_1 =
rfh_sub_1->child_at(0)->current_frame_host();
RenderFrameHostImpl* rfh_sub_2 =
prerendered_render_frame_host->child_at(1)->current_frame_host();
EXPECT_THAT(CollectAllRenderFrameHosts(prerendered_render_frame_host),
testing::ElementsAre(prerendered_render_frame_host, rfh_sub_1,
rfh_sub_2, rfh_sub_1_1));
// When iterating over all RenderFrameHosts in a WebContents, we should see
// the RFHs of both the primary page and the prerendered page.
EXPECT_THAT(CollectAllRenderFrameHosts(web_contents_impl()),
testing::UnorderedElementsAre(initiator_render_frame_host,
prerendered_render_frame_host,
rfh_sub_1, rfh_sub_2, rfh_sub_1_1));
EXPECT_EQ(nullptr, initiator_render_frame_host->GetParentOrOuterDocument());
EXPECT_EQ(nullptr, prerendered_render_frame_host->GetParentOrOuterDocument());
EXPECT_EQ(prerendered_render_frame_host,
rfh_sub_1->GetParentOrOuterDocument());
EXPECT_EQ(rfh_sub_1, rfh_sub_1_1->GetParentOrOuterDocument());
EXPECT_EQ(prerendered_render_frame_host,
rfh_sub_2->GetParentOrOuterDocument());
EXPECT_EQ(initiator_render_frame_host,
initiator_render_frame_host->GetOutermostMainFrame());
EXPECT_EQ(initiator_render_frame_host,
initiator_render_frame_host->GetOutermostMainFrameOrEmbedder());
// The outermost document of a prerendered page is the prerendered main
// RenderFrameHost, not the primary main RenderFrameHost.
EXPECT_EQ(prerendered_render_frame_host,
prerendered_render_frame_host->GetOutermostMainFrame());
EXPECT_EQ(prerendered_render_frame_host, rfh_sub_1->GetOutermostMainFrame());
EXPECT_EQ(prerendered_render_frame_host,
rfh_sub_1_1->GetOutermostMainFrame());
EXPECT_EQ(prerendered_render_frame_host, rfh_sub_2->GetOutermostMainFrame());
EXPECT_EQ(prerendered_render_frame_host,
prerendered_render_frame_host->GetOutermostMainFrameOrEmbedder());
EXPECT_EQ(prerendered_render_frame_host,
rfh_sub_1->GetOutermostMainFrameOrEmbedder());
EXPECT_EQ(prerendered_render_frame_host,
rfh_sub_1_1->GetOutermostMainFrameOrEmbedder());
EXPECT_EQ(prerendered_render_frame_host,
rfh_sub_2->GetOutermostMainFrameOrEmbedder());
// WebContentsImpl::ForEachFrameTree should include prerenders.
bool visited_prerender_frame_tree = false;
web_contents_impl()->ForEachFrameTree([&](FrameTree& frame_tree) {
if (&frame_tree == prerendered_render_frame_host->frame_tree()) {
visited_prerender_frame_tree = true;
}
});
EXPECT_TRUE(visited_prerender_frame_tree);
}
// Tests that a prerendering page cannot change the visible URL of the
// corresponding WebContentsImpl instance before activation.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, TabVisibleURL) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/title1.html");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
ASSERT_EQ(shell()->web_contents()->GetVisibleURL(), kInitialUrl);
AddPrerender(kPrerenderingUrl);
// The visible URL should not be modified by the prerendering page.
EXPECT_EQ(shell()->web_contents()->GetVisibleURL(), kInitialUrl);
// Activate the prerendered page.
NavigatePrimaryPage(kPrerenderingUrl);
// The visible URL should be updated after activation.
EXPECT_EQ(shell()->web_contents()->GetVisibleURL(), kPrerenderingUrl);
}
// Tests that prerendering will be cancelled if a prerendering page wants to set
// a WebContents-level preferred size.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, CancelOnPreferredSizeChanged) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/title1.html");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
test::PrerenderHostObserver host_observer(*web_contents_impl(), host_id);
// Enable PreferredSize mode in the prerendering page. Usually this mode is
// enabled by extentsions; here we enable it manually. Enabling this mode
// makes renderers ask the browser to update WebContents-level preferred size,
// which leads to the cancellation of prerendering.
RenderFrameHostImpl* prerender_main_frame =
GetPrerenderedMainFrameHost(host_id);
prerender_main_frame->GetRenderViewHost()->EnablePreferredSizeMode();
host_observer.WaitForDestroyed();
EXPECT_FALSE(HasHostForUrl(kPrerenderingUrl));
ExpectFinalStatusForSpeculationRule(
PrerenderFinalStatus::kInactivePageRestriction);
histogram_tester().ExpectUniqueSample(
"Prerender.CanceledForInactivePageRestriction.DisallowActivationReason."
"SpeculationRule",
DisallowActivationReasonId::kContentsPreferredSizeChanged, 1);
}
// Tests that prerendering cannot request the browser to create a popup widget.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, NoPopupWidget) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/title1.html");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
RenderFrameHostWrapper prerender_main_frame(
GetPrerenderedMainFrameHost(host_id));
std::string create_element_script = R"(
const widgetElement = document.createElement('input');
widgetElement.type = 'color';
widgetElement.id = 'chooser';
widgetElement.value = '#000000';
document.body.appendChild(widgetElement);
)";
EXPECT_TRUE(ExecJs(prerender_main_frame.get(), create_element_script,
EvalJsOptions::EXECUTE_SCRIPT_NO_USER_GESTURE));
std::string click_element_script = R"(
const element = document.getElementById('chooser');
element.click();
)";
// It should be ignored because prerendering page do not have user gestures.
EXPECT_TRUE(ExecJs(prerender_main_frame.get(), click_element_script));
// Give the test a chance to fail if the click() is not ignored.
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(HasHostForUrl(kPrerenderingUrl));
}
// This throttle cancels prerendering on subframe navigation in prerendered
// pages. The subframe navigation itself will keep proceeding.
class TestPrerenderCancellerSubframeNavigationThrottle
: public NavigationThrottle {
public:
explicit TestPrerenderCancellerSubframeNavigationThrottle(
NavigationHandle* navigation_handle)
: NavigationThrottle(navigation_handle),
navigation_request_(NavigationRequest::From(navigation_handle)) {}
ThrottleCheckResult WillStartRequest() override {
// Cancel prerendering if this navigation is for subframes in prerendered
// pages.
FrameTreeNode* frame_tree_node = navigation_request_->frame_tree_node();
if (frame_tree_node->frame_tree().is_prerendering() &&
!frame_tree_node->IsMainFrame()) {
PrerenderHostRegistry* prerender_host_registry =
frame_tree_node->current_frame_host()
->delegate()
->GetPrerenderHostRegistry();
prerender_host_registry->CancelHost(
frame_tree_node->frame_tree().root()->frame_tree_node_id(),
PrerenderFinalStatus::kMaxValue);
}
return PROCEED;
}
const char* GetNameForLogging() override {
return "TestPrerenderCancellerSubframeNavigationThrottle";
}
private:
raw_ptr<NavigationRequest> navigation_request_;
};
// Regression test for https://crbug.com/1323309.
// Tests that subframe navigation in prerendered pages starting while
// PrerenderHost is being destroyed should not crash.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
SubframeNavigationWhilePrerenderHostIsBeingDestroyed) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/empty.html?prerender");
const GURL kCrossOriginSubframeUrl =
GetCrossSiteUrl("/empty.html?cross_origin_iframe");
// Navigate to the initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
ASSERT_EQ(web_contents()->GetLastCommittedURL(), kInitialUrl);
ASSERT_TRUE(WaitForLoadStop(shell()->web_contents()));
// Start a prerender.
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
test::PrerenderHostObserver observer(*web_contents_impl(), host_id);
// Insert TestPrerenderCancellerSubframeNavigationThrottle that cancels
// prerendering on subframe navigation in a prerendered page. This should run
// before PrerenderSubframeNavigationThrottle.
ShellContentBrowserClient::Get()
->set_create_throttles_for_navigation_callback(base::BindLambdaForTesting(
[](NavigationThrottleRegistry& registry) -> void {
registry.AddThrottle(
std::make_unique<
TestPrerenderCancellerSubframeNavigationThrottle>(
®istry.GetNavigationHandle()));
}));
// Use ExecuteScriptAsync instead of EvalJs as inserted cross-origin iframe
// navigation should be canceled and script execution cannot wait for the
// completion.
RenderFrameHost* prerender_frame_host = GetPrerenderedMainFrameHost(host_id);
EXPECT_TRUE(AddTestUtilJS(prerender_frame_host));
ExecuteScriptAsync(prerender_frame_host, JsReplace("add_iframe_async($1)",
kCrossOriginSubframeUrl));
// Wait for the cancellation triggered by the throttle. The subframe
// navigation should not crash during the period.
observer.WaitForDestroyed();
EXPECT_FALSE(HasHostForUrl(kPrerenderingUrl));
ExpectFinalStatusForSpeculationRule(PrerenderFinalStatus::kMaxValue);
}
class MojoCapabilityControlTestContentBrowserClient
: public ContentBrowserTestContentBrowserClient,
public test::MojoCapabilityControlTestHelper {
public:
MojoCapabilityControlTestContentBrowserClient() = default;
~MojoCapabilityControlTestContentBrowserClient() override = default;
MojoCapabilityControlTestContentBrowserClient(
const MojoCapabilityControlTestContentBrowserClient&) = delete;
MojoCapabilityControlTestContentBrowserClient& operator=(
const MojoCapabilityControlTestContentBrowserClient&) = delete;
// ContentBrowserClient implementation.
void RegisterBrowserInterfaceBindersForFrame(
RenderFrameHost* render_frame_host,
mojo::BinderMapWithContext<RenderFrameHost*>* map) override {
RegisterTestBrowserInterfaceBindersForFrame(render_frame_host, map);
}
void RegisterMojoBinderPoliciesForSameOriginPrerendering(
MojoBinderPolicyMap& policy_map) override {
RegisterTestMojoBinderPolicies(policy_map);
}
};
// Tests that binding requests are handled according to MojoBinderPolicyMap
// during prerendering.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, MojoCapabilityControl) {
MojoCapabilityControlTestContentBrowserClient test_browser_client;
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/page_with_iframe.html");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
ASSERT_EQ(web_contents()->GetLastCommittedURL(), kInitialUrl);
// Start a prerender.
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
RenderFrameHost* prerendered_render_frame_host =
GetPrerenderedMainFrameHost(host_id);
std::vector<RenderFrameHost*> frames =
CollectAllRenderFrameHosts(prerendered_render_frame_host);
// A barrier closure to wait until a deferred interface is granted on all
// frames.
base::RunLoop run_loop;
auto barrier_closure =
base::BarrierClosure(frames.size(), run_loop.QuitClosure());
mojo::RemoteSet<mojom::TestInterfaceForDefer> defer_remote_set;
mojo::RemoteSet<mojom::TestInterfaceForGrant> grant_remote_set;
for (auto* frame : frames) {
auto* rfhi = static_cast<RenderFrameHostImpl*>(frame);
EXPECT_TRUE(rfhi->frame_tree()->is_prerendering());
EXPECT_EQ(rfhi->lifecycle_state(), LifecycleStateImpl::kPrerendering);
EXPECT_EQ(rfhi->GetLifecycleState(),
RenderFrameHost::LifecycleState::kPrerendering);
mojo::Receiver<blink::mojom::BrowserInterfaceBroker>& bib =
rfhi->browser_interface_broker_receiver_for_testing();
blink::mojom::BrowserInterfaceBroker* prerender_broker =
bib.internal_state()->impl();
// Try to bind a kDefer interface.
mojo::Remote<mojom::TestInterfaceForDefer> prerender_defer_remote;
prerender_broker->GetInterface(
prerender_defer_remote.BindNewPipeAndPassReceiver());
// The barrier closure will be called after the deferred interface is
// granted.
prerender_defer_remote->Ping(barrier_closure);
defer_remote_set.Add(std::move(prerender_defer_remote));
// Try to bind a kGrant interface.
mojo::Remote<mojom::TestInterfaceForGrant> prerender_grant_remote;
prerender_broker->GetInterface(
prerender_grant_remote.BindNewPipeAndPassReceiver());
grant_remote_set.Add(std::move(prerender_grant_remote));
}
// Verify that BrowserInterfaceBrokerImpl defers running binders whose
// policies are kDefer until the prerendered page is activated.
EXPECT_EQ(test_browser_client.GetDeferReceiverSetSize(), 0U);
// Verify that BrowserInterfaceBrokerImpl executes kGrant binders immediately.
EXPECT_EQ(test_browser_client.GetGrantReceiverSetSize(), frames.size());
// Activate the prerendered page.
NavigatePrimaryPage(kPrerenderingUrl);
EXPECT_EQ(web_contents()->GetLastCommittedURL(), kPrerenderingUrl);
// Wait until the deferred interface is granted on all frames.
run_loop.Run();
EXPECT_EQ(test_browser_client.GetDeferReceiverSetSize(), frames.size());
}
// Tests that mojo capability control will cancel prerendering if the main frame
// receives a request for a kCancel interface.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
MojoCapabilityControl_CancelMainFrame) {
MojoCapabilityControlTestContentBrowserClient test_browser_client;
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/page_with_iframe.html");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
ASSERT_EQ(web_contents()->GetLastCommittedURL(), kInitialUrl);
// Start a prerender.
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
auto* prerendered_render_frame_host = GetPrerenderedMainFrameHost(host_id);
mojo::Receiver<blink::mojom::BrowserInterfaceBroker>& bib =
prerendered_render_frame_host
->browser_interface_broker_receiver_for_testing();
blink::mojom::BrowserInterfaceBroker* prerender_broker =
bib.internal_state()->impl();
// Send a kCancel request to cancel prerendering.
EXPECT_TRUE(HasHostForUrl(kPrerenderingUrl));
mojo::Remote<mojom::TestInterfaceForCancel> remote;
prerender_broker->GetInterface(remote.BindNewPipeAndPassReceiver());
EXPECT_FALSE(HasHostForUrl(kPrerenderingUrl));
ExpectFinalStatusForSpeculationRule(PrerenderFinalStatus::kMojoBinderPolicy);
// `TestInterfaceForCancel` doesn't have a enum value because it is not used
// in production, so histogram_tester_ should log
// PrerenderCancelledInterface::kUnkown here.
histogram_tester().ExpectUniqueSample(
"Prerender.Experimental.PrerenderCancelledInterface.SpeculationRule",
PrerenderCancelledInterface::kUnknown, 1);
histogram_tester().ExpectUniqueSample(
"Prerender.Experimental.PrerenderCancelledUnknownInterface."
"SpeculationRule",
InterfaceNameHasher(mojom::TestInterfaceForCancel::Name_), 1);
}
// Tests that mojo capability control will cancel prerendering if child frames
// receive a request for a kCancel interface.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
MojoCapabilityControl_CancelIframe) {
MojoCapabilityControlTestContentBrowserClient test_browser_client;
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/page_with_iframe.html");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
ASSERT_EQ(web_contents()->GetLastCommittedURL(), kInitialUrl);
// Start a prerender.
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
auto* main_render_frame_host = GetPrerenderedMainFrameHost(host_id);
ASSERT_GE(main_render_frame_host->child_count(), 1U);
RenderFrameHostImpl* child_render_frame_host =
main_render_frame_host->child_at(0U)->current_frame_host();
EXPECT_NE(main_render_frame_host->GetLastCommittedURL(),
child_render_frame_host->GetLastCommittedURL());
mojo::Receiver<blink::mojom::BrowserInterfaceBroker>& bib =
child_render_frame_host->browser_interface_broker_receiver_for_testing();
blink::mojom::BrowserInterfaceBroker* prerender_broker =
bib.internal_state()->impl();
// Send a kCancel request to cancel prerendering.
EXPECT_TRUE(HasHostForUrl(kPrerenderingUrl));
mojo::Remote<mojom::TestInterfaceForCancel> remote;
prerender_broker->GetInterface(remote.BindNewPipeAndPassReceiver());
EXPECT_FALSE(HasHostForUrl(kPrerenderingUrl));
ExpectFinalStatusForSpeculationRule(PrerenderFinalStatus::kMojoBinderPolicy);
// `TestInterfaceForCancel` doesn't have a enum value because it is not used
// in production, so histogram_tester_ should log
// PrerenderCancelledInterface::kUnkown here.
histogram_tester().ExpectUniqueSample(
"Prerender.Experimental.PrerenderCancelledInterface.SpeculationRule",
PrerenderCancelledInterface::kUnknown, 1);
histogram_tester().ExpectUniqueSample(
"Prerender.Experimental.PrerenderCancelledUnknownInterface."
"SpeculationRule",
InterfaceNameHasher(mojom::TestInterfaceForCancel::Name_), 1);
}
// Tests that mojo capability control will crash the prerender if the browser
// process receives a kUnexpected interface.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
MojoCapabilityControl_HandleUnexpected) {
MojoCapabilityControlTestContentBrowserClient test_browser_client;
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/empty.html?prerender1");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
ASSERT_EQ(web_contents()->GetLastCommittedURL(), kInitialUrl);
// Set up the error handler for bad mojo messages.
std::string bad_message_error;
mojo::SetDefaultProcessErrorHandler(
base::BindLambdaForTesting([&](const std::string& error) {
EXPECT_FALSE(error.empty());
EXPECT_TRUE(bad_message_error.empty());
bad_message_error = error;
}));
// Start a prerender.
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
auto* main_render_frame_host = GetPrerenderedMainFrameHost(host_id);
// Rebind a receiver for testing.
// mojo::ReportBadMessage must be called within the stack frame derived from
// mojo IPC calls, so this browser test should call the
// remote<blink::mojom::BrowserInterfaceBroker>::GetInterface() to test
// unexpected interfaces. But its remote end is in renderer processes and
// inaccessible, so the test code has to create another BrowserInterfaceBroker
// pipe and rebind the receiver end so as to send the request from the remote.
mojo::Receiver<blink::mojom::BrowserInterfaceBroker>& bib =
main_render_frame_host->browser_interface_broker_receiver_for_testing();
auto broker_receiver_of_previous_document = bib.Unbind();
ASSERT_TRUE(broker_receiver_of_previous_document);
mojo::Remote<blink::mojom::BrowserInterfaceBroker> remote_broker;
mojo::PendingReceiver<blink::mojom::BrowserInterfaceBroker> fake_receiver =
remote_broker.BindNewPipeAndPassReceiver();
main_render_frame_host->BindBrowserInterfaceBrokerReceiver(
std::move(fake_receiver));
// Send a kUnexpected request.
EXPECT_TRUE(HasHostForUrl(kPrerenderingUrl));
mojo::Remote<mojom::TestInterfaceForUnexpected> remote;
remote_broker->GetInterface(remote.BindNewPipeAndPassReceiver());
remote_broker.FlushForTesting();
EXPECT_FALSE(HasHostForUrl(kPrerenderingUrl));
EXPECT_EQ(bad_message_error,
"MBPA_BAD_INTERFACE: content.mojom.TestInterfaceForUnexpected");
}
// Regression test for https://crbug.com/1268714 and https://crbug.com/1424250.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, MojoCapabilityControl_LoosenMode) {
MojoCapabilityControlTestContentBrowserClient test_browser_client;
// Some Android bots run with the site isolation disabled and behave
// differently on cross-origin iframe creation in a prerendered page. More
// specifically, when the site isolation is disabled, cross-site iframe will
// not create a speculative RenderFrameHost, and it results in test failures.
// To avoid it, this test explicitly runs with the site isolation enabled.
IsolateAllSitesForTesting(base::CommandLine::ForCurrentProcess());
GURL initial_url = GetUrl("/empty.html");
GURL prerendering_url =
GetUrl("/cross_site_iframe_factory.html?a.test(a.test,a.test)");
GURL cross_origin_iframe_url = GetCrossSiteUrl("/title1.html");
// 1. Navigate to an initial page and prerender a page.
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
FrameTreeNodeId host_id = AddPrerender(prerendering_url);
RenderFrameHostImpl* prerendered_render_frame_host =
GetPrerenderedMainFrameHost(host_id);
// 2. Let the first iframe navigate to a cross-origin url. It will create a
// speculative RFH and the navigation will be deferred.
TestNavigationManager subframe_navigation_manager(web_contents(),
cross_origin_iframe_url);
std::string js = R"(
const frame = document.getElementById($1);
frame.contentWindow.location.href = $2;
)";
EXPECT_TRUE(ExecJs(prerendered_render_frame_host,
JsReplace(js, "child-0", cross_origin_iframe_url.spec())));
// 3. Wait until the navigation to `cross_origin_iframe_url` is deferred by
// NavigationThrottle.
ASSERT_TRUE(
subframe_navigation_manager.WaitForFirstYieldAfterDidStartNavigation());
FrameTreeNode* child_ftn =
FrameTreeNode::GloballyFindByID(host_id)->child_at(0);
NavigationRequest* child_navigation = child_ftn->navigation_request();
ASSERT_NE(child_navigation, nullptr);
ASSERT_TRUE(child_navigation->IsDeferredForTesting());
// 4. Collect all RenderFrameHosts in the frame tree.
std::vector<RenderFrameHostImpl*> all_prerender_frames;
size_t count_speculative = 0;
prerendered_render_frame_host->ForEachRenderFrameHostImplIncludingSpeculative(
[&](RenderFrameHostImpl* rfh) {
all_prerender_frames.push_back(rfh);
count_speculative +=
(rfh->lifecycle_state() == LifecycleStateImpl::kSpeculative);
});
// With feature DeferSpeculativeRFHCreation, the speculative RFH won't be
// created when the navigation starts.
if (base::FeatureList::IsEnabled(features::kDeferSpeculativeRFHCreation)) {
ASSERT_EQ(all_prerender_frames.size(), 3u);
ASSERT_EQ(count_speculative, 0u);
} else {
ASSERT_EQ(all_prerender_frames.size(), 4u);
ASSERT_EQ(count_speculative, 1u);
}
// 5. Renderers attempt to build Mojo connections for kDefer and kGrant
// interfaces during prerendering. This part simulates them.
// A barrier closure to wait until a deferred interface is granted on all
// frames.
base::RunLoop run_loop;
auto barrier_closure =
base::BarrierClosure(all_prerender_frames.size(), run_loop.QuitClosure());
// Iterate all the frames to bind interfaces.
mojo::RemoteSet<mojom::TestInterfaceForDefer> defer_remote_set;
mojo::RemoteSet<mojom::TestInterfaceForGrant> grant_remote_set;
for (auto* rfhi : all_prerender_frames) {
mojo::Receiver<blink::mojom::BrowserInterfaceBroker>& bib =
rfhi->browser_interface_broker_receiver_for_testing();
blink::mojom::BrowserInterfaceBroker* prerender_broker =
bib.internal_state()->impl();
// Try to bind a kDefer interface.
mojo::Remote<mojom::TestInterfaceForDefer> prerender_defer_remote;
prerender_broker->GetInterface(
prerender_defer_remote.BindNewPipeAndPassReceiver());
// The barrier closure will be called after the deferred interface is
// granted.
prerender_defer_remote->Ping(barrier_closure);
defer_remote_set.Add(std::move(prerender_defer_remote));
// Try to bind a kGrant interface.
mojo::Remote<mojom::TestInterfaceForGrant> prerender_grant_remote;
prerender_broker->GetInterface(
prerender_grant_remote.BindNewPipeAndPassReceiver());
grant_remote_set.Add(std::move(prerender_grant_remote));
}
// Verify that BrowserInterfaceBrokerImpl defers running binders whose
// policies are kDefer until the prerendered page is activated.
EXPECT_EQ(test_browser_client.GetDeferReceiverSetSize(), 0U);
// Verify that BrowserInterfaceBrokerImpl executes kGrant binders immediately.
EXPECT_EQ(test_browser_client.GetGrantReceiverSetSize(),
all_prerender_frames.size());
// 6. Activate the prerendered page and listen to the DidFinishNavigation
// event, to ensure the Activate IPC is sent.
TestActivationManager prerendered_activation_navigation(web_contents(),
prerendering_url);
ASSERT_TRUE(ExecJs(web_contents()->GetPrimaryMainFrame(),
JsReplace("location = $1", prerendering_url)));
prerendered_activation_navigation.WaitForNavigationFinished();
EXPECT_TRUE(prerendered_activation_navigation.was_activated());
// Make sure all the deferred interfaces are granted after activation. This is
// a regression test for https://crbug.com/1424250.
run_loop.Run();
EXPECT_EQ(test_browser_client.GetDeferReceiverSetSize(),
all_prerender_frames.size());
// 7. Renderers attempt to build Mojo connections for kCancel interfaces.
// This part simulates some subframe documents start sending kCancel
// interfaces after they know about the activation. It tests the regression
// situation caught by https://crbug.com/1268714. If some RenderFrameHostImpls
// are not informed of the activation, this test will crash.
for (auto* rfhi : all_prerender_frames) {
mojo::Receiver<blink::mojom::BrowserInterfaceBroker>& bib =
rfhi->browser_interface_broker_receiver_for_testing();
blink::mojom::BrowserInterfaceBroker* prerender_broker =
bib.internal_state()->impl();
// Send a kCancel request to the browser. This test should not crash.
mojo::Remote<mojom::TestInterfaceForCancel> remote;
prerender_broker->GetInterface(remote.BindNewPipeAndPassReceiver());
remote.FlushForTesting();
}
}
// Test that prerenders triggered by speculation rules are canceled when a
// background timeout timer is fired.
void PrerenderBrowserTest::TestCancelPrerendersWhenTimeout(
std::vector<Visibility> visibility_transitions) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderUrl1 = GetUrl("/empty.html?prerender1");
const GURL kPrerenderUrl2 = GetUrl("/empty.html?prerender2");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
AddPrerender(kPrerenderUrl1);
AddPrerender(kPrerenderUrl2);
test::PrerenderHostObserver prerender_observer(*web_contents_impl(),
kPrerenderUrl1);
PrerenderHostRegistry* registry =
web_contents_impl()->GetPrerenderHostRegistry();
// The timers should not start yet when the prerendered page is in the
// foreground.
ASSERT_FALSE(registry->GetEmbedderTimerForTesting()->IsRunning());
ASSERT_FALSE(registry->GetSpeculationRulesTimerForTesting()->IsRunning());
// Inject mock time task runner.
auto task_runner = base::MakeRefCounted<base::TestMockTimeTaskRunner>();
registry->SetTaskRunnerForTesting(task_runner);
// Changing the visibility state starts/stops the timeout timer.
for (Visibility visibility : visibility_transitions) {
switch (visibility) {
case Visibility::HIDDEN:
web_contents()->WasHidden();
ASSERT_TRUE(registry->GetEmbedderTimerForTesting()->IsRunning());
ASSERT_TRUE(
registry->GetSpeculationRulesTimerForTesting()->IsRunning());
break;
case Visibility::OCCLUDED:
web_contents()->WasOccluded();
ASSERT_TRUE(registry->GetEmbedderTimerForTesting()->IsRunning());
ASSERT_TRUE(
registry->GetSpeculationRulesTimerForTesting()->IsRunning());
break;
case Visibility::VISIBLE:
web_contents()->WasShown();
ASSERT_FALSE(registry->GetEmbedderTimerForTesting()->IsRunning());
ASSERT_FALSE(
registry->GetSpeculationRulesTimerForTesting()->IsRunning());
break;
}
}
// The remaining part of this test assumes the timers are running.
ASSERT_TRUE(registry->GetEmbedderTimerForTesting()->IsRunning());
ASSERT_TRUE(registry->GetSpeculationRulesTimerForTesting()->IsRunning());
// Expire the timers.
task_runner->FastForwardBy(
PrerenderHostRegistry::kTimeToLiveInBackgroundForSpeculationRules);
ASSERT_FALSE(registry->GetEmbedderTimerForTesting()->IsRunning());
ASSERT_FALSE(registry->GetSpeculationRulesTimerForTesting()->IsRunning());
// The timers should cancel prerendering.
prerender_observer.WaitForDestroyed();
histogram_tester().ExpectUniqueSample(
"Prerender.Experimental.PrerenderHostFinalStatus.SpeculationRule",
PrerenderFinalStatus::kTimeoutBackgrounded, 2);
}
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
CancelPrerendersWhenTimeout_Hidden) {
// The timeout timers should start on the hidden state.
TestCancelPrerendersWhenTimeout({Visibility::HIDDEN});
}
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
CancelPrerendersWhenTimeout_Occluded) {
// The timeout timers should start on the occluded state.
TestCancelPrerendersWhenTimeout({Visibility::OCCLUDED});
}
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
CancelPrerendersWhenTimeout_OccludedHidden) {
// The timeout timers should start on the occluded state and then keep running
// on the hidden state.
TestCancelPrerendersWhenTimeout({Visibility::OCCLUDED, Visibility::HIDDEN});
}
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
CancelPrerendersWhenTimeout_OccludedVisibleHidden) {
// The timeout timers should start on the occluded state, stop on the visible
// state, and then restart on the hidden state.
TestCancelPrerendersWhenTimeout(
{Visibility::OCCLUDED, Visibility::VISIBLE, Visibility::HIDDEN});
}
// Test that a PrerenderHost triggered by embedder is canceled when it times out
// in the background.
void PrerenderBrowserTest::TestCancelOnlyEmbedderTriggeredPrerenderWhenTimeout(
std::vector<Visibility> visibility_transitions) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderUrl1 = GetUrl("/empty.html?prerender1");
const GURL kPrerenderUrl2 = GetUrl("/empty.html?prerender2");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start prerendering by speculation rules.
AddPrerender(kPrerenderUrl1);
test::PrerenderHostObserver host_observer(*web_contents_impl(),
kPrerenderUrl2);
// Start prerendering by embedder.
std::unique_ptr<PrerenderHandle> prerender_handle =
AddEmbedderTriggeredPrerenderAsync(kPrerenderUrl2);
PrerenderHostRegistry* registry =
web_contents_impl()->GetPrerenderHostRegistry();
// The timers should not start yet when the prerendered page is in the
// foreground.
ASSERT_FALSE(registry->GetEmbedderTimerForTesting()->IsRunning());
ASSERT_FALSE(registry->GetSpeculationRulesTimerForTesting()->IsRunning());
// Inject mock time task runner.
auto task_runner = base::MakeRefCounted<base::TestMockTimeTaskRunner>();
registry->SetTaskRunnerForTesting(task_runner);
// Changing the visibility state starts/stops the timeout timer.
for (Visibility visibility : visibility_transitions) {
switch (visibility) {
case Visibility::HIDDEN:
web_contents()->WasHidden();
ASSERT_TRUE(registry->GetEmbedderTimerForTesting()->IsRunning());
ASSERT_TRUE(
registry->GetSpeculationRulesTimerForTesting()->IsRunning());
break;
case Visibility::OCCLUDED:
web_contents()->WasOccluded();
ASSERT_TRUE(registry->GetEmbedderTimerForTesting()->IsRunning());
ASSERT_TRUE(
registry->GetSpeculationRulesTimerForTesting()->IsRunning());
break;
case Visibility::VISIBLE:
web_contents()->WasShown();
ASSERT_FALSE(registry->GetEmbedderTimerForTesting()->IsRunning());
ASSERT_FALSE(
registry->GetSpeculationRulesTimerForTesting()->IsRunning());
break;
}
}
// The remaining part of this test assumes the timers are running.
ASSERT_TRUE(registry->GetEmbedderTimerForTesting()->IsRunning());
ASSERT_TRUE(registry->GetSpeculationRulesTimerForTesting()->IsRunning());
// PrerenderHost triggered by embedder should be destroyed and PrerenderHost
// triggered by speculation rules should be alive, since the timeout value
// differs depending on the trigger type.
ASSERT_GT(PrerenderHostRegistry::kTimeToLiveInBackgroundForSpeculationRules,
PrerenderHostRegistry::kTimeToLiveInBackgroundForEmbedder);
task_runner->FastForwardBy(
PrerenderHostRegistry::kTimeToLiveInBackgroundForEmbedder);
host_observer.WaitForDestroyed();
// The timer for speculation rules is still running and PrerenderHost for
// speculation rules is alive.
ASSERT_FALSE(registry->GetEmbedderTimerForTesting()->IsRunning());
ASSERT_TRUE(registry->GetSpeculationRulesTimerForTesting()->IsRunning());
EXPECT_TRUE(GetHostForUrl(kPrerenderUrl1));
histogram_tester().ExpectUniqueSample(
"Prerender.Experimental.PrerenderHostFinalStatus.Embedder_"
"EmbedderSuffixForTest",
PrerenderFinalStatus::kTimeoutBackgrounded, 1);
histogram_tester().ExpectBucketCount(
"Prerender.Experimental.PrerenderHostFinalStatus.SpeculationRule",
PrerenderFinalStatus::kTimeoutBackgrounded, 0);
}
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
CancelOnlyEmbedderTriggeredPrerenderWhenTimeout_Hidden) {
// The timeout timers should start on the hidden state.
TestCancelOnlyEmbedderTriggeredPrerenderWhenTimeout({Visibility::HIDDEN});
}
IN_PROC_BROWSER_TEST_F(
PrerenderBrowserTest,
CancelOnlyEmbedderTriggeredPrerenderWhenTimeout_Occluded) {
// The timeout timers should start on the occluded state.
TestCancelOnlyEmbedderTriggeredPrerenderWhenTimeout({Visibility::OCCLUDED});
}
IN_PROC_BROWSER_TEST_F(
PrerenderBrowserTest,
CancelOnlyEmbedderTriggeredPrerenderWhenTimeout_OccludedHidden) {
// The timeout timers should start on the occluded state and then keep running
// on the hidden state.
TestCancelOnlyEmbedderTriggeredPrerenderWhenTimeout(
{Visibility::OCCLUDED, Visibility::HIDDEN});
}
IN_PROC_BROWSER_TEST_F(
PrerenderBrowserTest,
CancelOnlyEmbedderTriggeredPrerenderWhenTimeout_OccludedVisibleHidden) {
// The timeout timers should start on the occluded state, stop on the visible
// state, and then restart on the hidden state.
TestCancelOnlyEmbedderTriggeredPrerenderWhenTimeout(
{Visibility::OCCLUDED, Visibility::VISIBLE, Visibility::HIDDEN});
}
// Test that the timers for PrerenderHost timeout is reset when the
// hidden/occluded page gets visible.
void PrerenderBrowserTest::TestTimerResetWhenPageGoBackToForeground(
Visibility visibility) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderUrl = GetUrl("/empty.html?prerender");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
AddPrerender(kPrerenderUrl);
PrerenderHostRegistry* registry =
web_contents_impl()->GetPrerenderHostRegistry();
// The timers should not start yet when the prerendered page is in the
// foreground.
ASSERT_FALSE(registry->GetEmbedderTimerForTesting()->IsRunning());
ASSERT_FALSE(registry->GetSpeculationRulesTimerForTesting()->IsRunning());
// Changing the visibility state to HIDDEN/OCCLUDED will not stop prerendering
// immediately, but start the timers.
switch (visibility) {
case Visibility::HIDDEN:
web_contents()->WasHidden();
break;
case Visibility::OCCLUDED:
web_contents()->WasOccluded();
break;
case Visibility::VISIBLE:
ASSERT_TRUE(false);
break;
}
// The remaining part of this test assumes the timers are running.
ASSERT_TRUE(registry->GetEmbedderTimerForTesting()->IsRunning());
ASSERT_TRUE(registry->GetSpeculationRulesTimerForTesting()->IsRunning());
// The timers should be reset when the HIDDEN/OCCLUDED page goes back to the
// foreground.
web_contents()->WasShown();
ASSERT_FALSE(registry->GetEmbedderTimerForTesting()->IsRunning());
ASSERT_FALSE(registry->GetSpeculationRulesTimerForTesting()->IsRunning());
// Activate the prerendered page.
test::PrerenderHostObserver prerender_observer(*web_contents(),
GetHostForUrl(kPrerenderUrl));
NavigatePrimaryPage(kPrerenderUrl);
prerender_observer.WaitForActivation();
EXPECT_EQ(web_contents()->GetLastCommittedURL(), kPrerenderUrl);
histogram_tester().ExpectUniqueSample(
"Prerender.Experimental.PrerenderHostFinalStatus.SpeculationRule",
PrerenderFinalStatus::kActivated, 1);
}
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
TimerResetWhenPageGoBackToForeground_Hidden) {
TestTimerResetWhenPageGoBackToForeground(Visibility::HIDDEN);
}
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
TimerResetWhenPageGoBackToForeground_Occluded) {
TestTimerResetWhenPageGoBackToForeground(Visibility::OCCLUDED);
}
// Test that a PrerenderHost in a triggered by speculation rules with
// "target=_blank" are canceled when it times out in the background .
void PrerenderBrowserTest::TestCancelPrerenderWithTargetBlankWhenTimeout(
Visibility visibility) {
const GURL kInitialUrl = GetUrl("/simple_links.html");
const GURL kPrerenderUrl = GetUrl("/title2.html");
// Navigate to an initial page which has a link to `kPrerenderUrl`.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start prerendering `kPrerenderUrl`.
FrameTreeNodeId host_id = prerender_helper()->AddPrerender(
kPrerenderUrl, /*eagerness=*/std::nullopt, "_blank");
auto* prerender_web_contents = WebContents::FromFrameTreeNodeId(host_id);
ASSERT_NE(prerender_web_contents, web_contents_impl());
ExpectWebContentsIsForNewTabPrerendering(*prerender_web_contents);
PrerenderHostRegistry* registry =
web_contents_impl()->GetPrerenderHostRegistry();
// The timers should not start yet when the prerendered page is in the
// foreground.
ASSERT_FALSE(registry->GetEmbedderTimerForTesting()->IsRunning());
ASSERT_FALSE(registry->GetSpeculationRulesTimerForTesting()->IsRunning());
// Inject mock time task runner.
auto task_runner = base::MakeRefCounted<base::TestMockTimeTaskRunner>();
registry->SetTaskRunnerForTesting(task_runner);
test::PrerenderHostObserver prerender_observer(*prerender_web_contents,
host_id);
// Changing the visibility state to HIDDEN/OCCLUDED will not stop prerendering
// immediately, but start the timers.
switch (visibility) {
case Visibility::HIDDEN:
web_contents()->WasHidden();
break;
case Visibility::OCCLUDED:
web_contents()->WasOccluded();
break;
case Visibility::VISIBLE:
ASSERT_TRUE(false);
break;
}
// The remaining part of this test assumes the timers are running.
ASSERT_TRUE(registry->GetEmbedderTimerForTesting()->IsRunning());
ASSERT_TRUE(registry->GetSpeculationRulesTimerForTesting()->IsRunning());
// Expire the timers.
task_runner->FastForwardBy(
PrerenderHostRegistry::kTimeToLiveInBackgroundForSpeculationRules);
ASSERT_FALSE(registry->GetEmbedderTimerForTesting()->IsRunning());
ASSERT_FALSE(registry->GetSpeculationRulesTimerForTesting()->IsRunning());
prerender_observer.WaitForDestroyed();
histogram_tester().ExpectUniqueSample(
"Prerender.Experimental.PrerenderHostFinalStatus.SpeculationRule",
PrerenderFinalStatus::kTimeoutBackgrounded, 1);
// The navigation occurred in a new WebContents, so the original WebContents
// should still be showing the initial trigger page.
EXPECT_EQ(web_contents()->GetLastCommittedURL(), kInitialUrl);
}
IN_PROC_BROWSER_TEST_F(PrerenderTargetHintEnabledBrowserTest,
CancelPrerenderWithTargetBlankWhenTimeout_Hidden) {
TestCancelPrerenderWithTargetBlankWhenTimeout(Visibility::HIDDEN);
}
IN_PROC_BROWSER_TEST_F(PrerenderTargetHintEnabledBrowserTest,
CancelPrerenderWithTargetBlankWhenTimeout_Occluded) {
TestCancelPrerenderWithTargetBlankWhenTimeout(Visibility::OCCLUDED);
}
enum class SSLPrerenderTestErrorBlockType { kClientCertRequested, kCertError };
std::string SSLPrerenderTestErrorBlockTypeToString(
const testing::TestParamInfo<SSLPrerenderTestErrorBlockType>& info) {
switch (info.param) {
case SSLPrerenderTestErrorBlockType::kClientCertRequested:
return "ClientCertRequested";
case SSLPrerenderTestErrorBlockType::kCertError:
return "CertError";
}
}
class SSLPrerenderBrowserTest
: public testing::WithParamInterface<SSLPrerenderTestErrorBlockType>,
public PrerenderBrowserTest {
protected:
void RequireClientCertsOrSendExpiredCerts() {
net::SSLServerConfig ssl_config;
switch (GetParam()) {
case SSLPrerenderTestErrorBlockType::kClientCertRequested:
ssl_config.client_cert_type =
net::SSLServerConfig::ClientCertType::REQUIRE_CLIENT_CERT;
ResetSSLConfig(net::test_server::EmbeddedTestServer::CERT_TEST_NAMES,
ssl_config);
break;
case SSLPrerenderTestErrorBlockType::kCertError:
ResetSSLConfig(net::test_server::EmbeddedTestServer::CERT_EXPIRED,
ssl_config);
break;
}
}
PrerenderFinalStatus GetExpectedFinalStatus() {
switch (GetParam()) {
case SSLPrerenderTestErrorBlockType::kClientCertRequested:
return PrerenderFinalStatus::kClientCertRequested;
case SSLPrerenderTestErrorBlockType::kCertError:
return PrerenderFinalStatus::kSslCertificateError;
}
}
};
INSTANTIATE_TEST_SUITE_P(
All,
SSLPrerenderBrowserTest,
testing::Values(SSLPrerenderTestErrorBlockType::kClientCertRequested,
SSLPrerenderTestErrorBlockType::kCertError),
SSLPrerenderTestErrorBlockTypeToString);
// For a prerendering navigation request, if the server requires a client
// certificate or responds to the request with an invalid certificate, the
// prernedering should be canceled.
IN_PROC_BROWSER_TEST_P(SSLPrerenderBrowserTest,
CertificateValidation_Navigation) {
// Navigate to an initial page.
const GURL kInitialUrl = GetUrl("/empty.html");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Reset the server's config.
RequireClientCertsOrSendExpiredCerts();
const GURL kPrerenderingUrl = GetUrl("/title1.html");
// Start prerendering `kPrerenderingUrl`.
test::PrerenderHostObserver host_observer(*web_contents(), kPrerenderingUrl);
prerender_helper()->AddPrerenderAsync(kPrerenderingUrl);
// The prerender should be destroyed.
host_observer.WaitForDestroyed();
EXPECT_TRUE(prerender_helper()->GetHostForUrl(kPrerenderingUrl).is_null());
ExpectFinalStatusForSpeculationRule(GetExpectedFinalStatus());
}
// For a prerendering subresource request, if the server requires a client
// certificate or responds to the request with an invalid certificate, the
// prernedering should be canceled.
IN_PROC_BROWSER_TEST_P(SSLPrerenderBrowserTest,
CertificateValidation_Subresource) {
// Navigate to an initial page.
const GURL kInitialUrl = GetUrl("/empty.html");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start prerendering `kPrerenderingUrl`.
const GURL kPrerenderingUrl = GetUrl("/title1.html");
FrameTreeNodeId host_id = prerender_helper()->AddPrerender(kPrerenderingUrl);
test::PrerenderHostObserver host_observer(*web_contents(), host_id);
// Reset the server's config.
RequireClientCertsOrSendExpiredCerts();
ASSERT_TRUE(prerender_helper()->GetHostForUrl(kPrerenderingUrl));
// Fetch a subresrouce.
std::string fetch_subresource_script = R"(
const imgElement = document.createElement('img');
imgElement.src = '/load_image/image.png';
document.body.appendChild(imgElement);
)";
std::ignore = ExecJs(prerender_helper()->GetPrerenderedMainFrameHost(host_id),
fetch_subresource_script);
// The prerender should be destroyed.
host_observer.WaitForDestroyed();
EXPECT_TRUE(prerender_helper()->GetHostForUrl(kPrerenderingUrl).is_null());
ExpectFinalStatusForSpeculationRule(GetExpectedFinalStatus());
}
// Tests that prerendering will be cancelled if the server asks for client
// certificates or responds with an expired certificate, even if the main
// resource request is intercepted and sent by a service worker.
IN_PROC_BROWSER_TEST_P(SSLPrerenderBrowserTest,
CertificateValidation_SWMainResource) {
// Register a service worker that intercepts resource requests.
const GURL kInitialUrl = GetUrl("/workers/service_worker_setup.html");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
EXPECT_EQ("ok", EvalJs(web_contents(), "setup();"));
// Reset the server's config.
RequireClientCertsOrSendExpiredCerts();
const GURL kPrerenderingUrl = GetUrl("/workers/simple.html?intercept");
test::PrerenderHostObserver host_observer(*web_contents(), kPrerenderingUrl);
prerender_helper()->AddPrerenderAsync(kPrerenderingUrl);
// The prerender should be destroyed.
host_observer.WaitForDestroyed();
EXPECT_TRUE(prerender_helper()->GetHostForUrl(kPrerenderingUrl).is_null());
// For the kCertError case, StoragePartitionImpl cannot locate any
// WebContents. So, the certificate error does not cause any UI changes; it
// just cancels the url request, and leads to the cancellation of
// prerendering with kNavigationRequestNetworkError.
ExpectFinalStatusForSpeculationRule(
GetParam() == SSLPrerenderTestErrorBlockType::kClientCertRequested
? PrerenderFinalStatus::kClientCertRequested
: PrerenderFinalStatus::kNavigationRequestNetworkError);
}
// Tests that prerendering will be cancelled if the server asks for client
// certificates or responds with an expired certificate, even if the subresource
// request is intercepted by a service worker.
IN_PROC_BROWSER_TEST_P(SSLPrerenderBrowserTest,
CertificateValidation_SWSubResource) {
// Skip the test when the block type is kCertError. With the type, this test
// times out due to https://crbug.com/1311887.
// TODO(crbug.com/40220378): Enable the test with kCertError.
if (GetParam() == SSLPrerenderTestErrorBlockType::kCertError) {
return;
}
// Load an initial page and register a service worker that intercepts
// resources requests.
const GURL kInitialUrl = GetUrl("/workers/service_worker_setup.html");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
EXPECT_EQ("ok", EvalJs(current_frame_host(), "setup();"));
// Prerender a page.
const GURL kPrerenderingUrl = GetUrl("/workers/empty.html");
FrameTreeNodeId host_id = prerender_helper()->AddPrerender(kPrerenderingUrl);
test::PrerenderHostObserver host_observer(*web_contents(), host_id);
RequireClientCertsOrSendExpiredCerts();
// Try to fetch a sub resource through the registered service worker. The
// server should ask for a client certificate or respond with an expired
// certificate, which leads to the cancellation of prerendering.
std::string resource_url = GetUrl("/workers/empty.js?intercept").spec();
std::ignore = ExecJs(prerender_helper()->GetPrerenderedMainFrameHost(host_id),
JsReplace("fetch($1);", resource_url));
// Check the prerender was destroyed.
host_observer.WaitForDestroyed();
EXPECT_TRUE(prerender_helper()->GetHostForUrl(kPrerenderingUrl).is_null());
ExpectFinalStatusForSpeculationRule(GetExpectedFinalStatus());
}
// Tests for feature restrictions in prerendered pages =========================
// Tests that window.open() in a prerendering page fails.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, FeatureRestriction_WindowOpen) {
// Navigate to an initial page.
const GURL kInitialUrl = GetUrl("/empty.html");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start a prerender.
const GURL kPrerenderingUrl = GetUrl("/empty.html?prerendering");
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
auto* prerender_frame = GetPrerenderedMainFrameHost(host_id);
EXPECT_TRUE(AddTestUtilJS(prerender_frame));
// Attempt to open a window in the prerendered page. This should fail.
const GURL kWindowOpenUrl = GetUrl("/empty.html?prerender");
EXPECT_EQ("FAILED", EvalJs(prerender_frame,
JsReplace("open_window($1)", kWindowOpenUrl)));
EXPECT_EQ(GetRequestCount(kWindowOpenUrl), 0);
// Opening a window shouldn't cancel prerendering.
EXPECT_EQ(GetHostForUrl(kPrerenderingUrl), host_id);
}
IN_PROC_BROWSER_TEST_P(PrerenderTargetAgnosticBrowserTest,
RenderFrameHostLifecycleState) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/empty.html");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
EXPECT_EQ(current_frame_host()->lifecycle_state(),
LifecycleStateImpl::kActive);
// Start a prerender.
FrameTreeNodeId host_id = prerender_helper()->AddPrerender(
kPrerenderingUrl, /*eagerness=*/std::nullopt, GetTargetHint());
auto* prerender_web_contents = WebContents::FromFrameTreeNodeId(host_id);
// Open an iframe in the prerendered page.
auto* rfh_a = static_cast<RenderFrameHostImpl*>(
test::PrerenderTestHelper::GetPrerenderedMainFrameHost(
*prerender_web_contents, host_id));
EXPECT_TRUE(AddTestUtilJS(rfh_a));
EXPECT_EQ("LOADED",
EvalJs(rfh_a, JsReplace("add_iframe($1)",
GetUrl("/empty.html?prerender"))));
RenderFrameHostImpl* rfh_b = rfh_a->child_at(0)->current_frame_host();
// Both rfh_a and rfh_b lifecycle state's should be kPrerendering.
EXPECT_EQ(LifecycleStateImpl::kPrerendering, rfh_a->lifecycle_state());
EXPECT_EQ(LifecycleStateImpl::kPrerendering, rfh_b->lifecycle_state());
EXPECT_FALSE(rfh_a->IsInPrimaryMainFrame());
EXPECT_FALSE(rfh_b->IsInPrimaryMainFrame());
// Activate the prerendered page.
ActivatePrerenderedPage(*prerender_web_contents, kPrerenderingUrl);
// Both rfh_a and rfh_b lifecycle state's should be kActive after activation.
EXPECT_EQ(LifecycleStateImpl::kActive, rfh_a->lifecycle_state());
EXPECT_EQ(LifecycleStateImpl::kActive, rfh_b->lifecycle_state());
EXPECT_TRUE(rfh_a->IsInPrimaryMainFrame());
EXPECT_FALSE(rfh_b->IsInPrimaryMainFrame());
// "Navigation.TimeToActivatePrerender.SpeculationRule" histogram should be
// recorded on every prerender activation.
histogram_tester().ExpectTotalCount(
"Navigation.TimeToActivatePrerender.SpeculationRule", 1u);
}
// Test that prerender activation is deferred and resumed after the ongoing
// (in-flight) main-frame navigation in the prerendering frame tree commits.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
SupportActivationWithOngoingMainFrameNavigation) {
// Create a HTTP response to control prerendering main-frame navigation.
net::test_server::ControllableHttpResponse main_document_response(
embedded_test_server(), "/main_document");
ASSERT_TRUE(embedded_test_server()->Start());
const GURL kInitialUrl = embedded_test_server()->GetURL("/empty.html");
const GURL kPrerenderingUrl =
embedded_test_server()->GetURL("/main_document");
// Navigate to an initial page in primary frame tree.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start a prerender, and navigate to a page that doesn't commit navigation.
{
test::PrerenderHostRegistryObserver registry_observer(*web_contents_impl());
AddPrerenderAsync(kPrerenderingUrl);
registry_observer.WaitForTrigger(kPrerenderingUrl);
EXPECT_TRUE(HasHostForUrl(kPrerenderingUrl));
}
FrameTreeNodeId host_id = GetHostForUrl(kPrerenderingUrl);
test::PrerenderHostObserver prerender_observer(*web_contents_impl(), host_id);
EXPECT_FALSE(prerender_observer.was_activated());
// Defer the activation until the ongoing main-frame navigation in prerender
// frame tree commits.
{
// Start navigation in primary page to kPrerenderingUrl.
TestActivationManager primary_page_manager(shell()->web_contents(),
kPrerenderingUrl);
ASSERT_TRUE(ExecJs(shell()->web_contents()->GetPrimaryMainFrame(),
JsReplace("location = $1", kPrerenderingUrl)));
NavigationRequest* request =
web_contents_impl()->GetPrimaryFrameTree().root()->navigation_request();
// Wait until the navigation is deferred by CommitDeferringCondition.
ASSERT_TRUE(primary_page_manager.WaitForBeforeChecks());
primary_page_manager.ResumeActivation();
// TODO(bokan): This could be any CommitDeferringCondition, we should have
// a way to pause on a specific CommitDeferringCondition.
EXPECT_TRUE(request->IsCommitDeferringConditionDeferredForTesting());
// The navigation should not have proceeded past NOT_STARTED because the
// PrerenderCommitDeferringCondition is deferring it.
EXPECT_EQ(request->state(), NavigationRequest::NOT_STARTED);
// Complete the prerender response and finish ongoing prerender main frame
// navigation.
main_document_response.WaitForRequest();
main_document_response.Send(net::HTTP_OK, "main_document");
main_document_response.Done();
// The URL should still point to the kInitialUrl until the activation is
// completed.
EXPECT_EQ(shell()->web_contents()->GetLastCommittedURL(), kInitialUrl);
// Make sure that the prerender was not activated yet.
EXPECT_FALSE(prerender_observer.was_activated());
primary_page_manager.WaitForNavigationFinished();
prerender_observer.WaitForActivation();
}
// Prerender should be activated and the URL should point to kPrerenderingUrl.
{
EXPECT_TRUE(prerender_observer.was_activated());
EXPECT_FALSE(HasHostForUrl(kPrerenderingUrl));
EXPECT_EQ(shell()->web_contents()->GetLastCommittedURL(), kPrerenderingUrl);
}
// "Navigation.Prerender.ActivationCommitDeferTime" histogram should be
// recorded as PrerenderCommitDeferringCondition defers the navigation.
histogram_tester().ExpectTotalCount(
"Navigation.Prerender.ActivationCommitDeferTime.SpeculationRule", 1u);
}
// TODO(crbug.com/40170624): Now the File System Access API is not
// supported on Android. Enable this browser test after
// https://crbug.com/1011535 is fixed.
#if BUILDFLAG(IS_ANDROID)
#define MAYBE_DeferPrivateOriginFileSystem DISABLED_DeferPrivateOriginFileSystem
#else
#define MAYBE_DeferPrivateOriginFileSystem DeferPrivateOriginFileSystem
#endif
// Tests that access to the origin private file system via the File System
// Access API is deferred until activating the prerendered page.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
MAYBE_DeferPrivateOriginFileSystem) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl =
GetUrl("/prerender/restriction_file_system.html");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Make a prerendered page.
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
auto* prerender_render_frame_host = GetPrerenderedMainFrameHost(host_id);
EXPECT_EQ(
true,
ExecJs(prerender_render_frame_host, "accessOriginPrivateFileSystem();",
EvalJsOptions::EXECUTE_SCRIPT_NO_USER_GESTURE |
EvalJsOptions::EXECUTE_SCRIPT_NO_RESOLVE_PROMISES));
// Run a event loop so the page can fail the test.
EXPECT_TRUE(ExecJs(prerender_render_frame_host, "runLoop();"));
// Activate the page.
NavigatePrimaryPage(kPrerenderingUrl);
// Wait for the completion of `accessOriginPrivateFileSystem`.
EXPECT_EQ(true, EvalJs(prerender_render_frame_host, "result;"));
// Check the event sequence seen in the prerendered page.
EvalJsResult results = EvalJs(prerender_render_frame_host, "eventsSeen");
std::vector<std::string> eventsSeen;
base::Value::List results_list = results.ExtractList();
for (auto& result : results_list) {
eventsSeen.push_back(result.GetString());
}
EXPECT_THAT(eventsSeen,
testing::ElementsAreArray(
{"accessOriginPrivateFileSystem (prerendering: true)",
"prerenderingchange (prerendering: false)",
"getDirectory (prerendering: false)"}));
}
// Tests that DocumentUserData object is not cleared on activating a
// prerendered page.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, DocumentUserData) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/empty.html?prerender");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
ASSERT_EQ(web_contents()->GetLastCommittedURL(), kInitialUrl);
// Start a prerender.
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
auto* prerender_render_frame_host = GetPrerenderedMainFrameHost(host_id);
// Get the DocumentData associated with prerender RenderFrameHost.
DocumentData::CreateForCurrentDocument(prerender_render_frame_host);
base::WeakPtr<DocumentData> data =
DocumentData::GetForCurrentDocument(prerender_render_frame_host)
->GetWeakPtr();
EXPECT_TRUE(data);
// Activate the prerendered page.
NavigatePrimaryPage(kPrerenderingUrl);
EXPECT_EQ(web_contents()->GetLastCommittedURL(), kPrerenderingUrl);
// The prerender host should be consumed.
EXPECT_FALSE(HasHostForUrl(kPrerenderingUrl));
// DocumentData associated with document shouldn't have been cleared on
// activating prerendered page.
base::WeakPtr<DocumentData> data_after_activation =
DocumentData::GetForCurrentDocument(current_frame_host())->GetWeakPtr();
EXPECT_TRUE(data_after_activation);
// Both the instances of DocumentData before and after activation should point
// to the same object and make sure they aren't null.
EXPECT_EQ(data_after_activation.get(), data.get());
}
// Tests that executing the GamepadMonitor API on a prerendering before
// navigating to the prerendered page causes cancel prerendering.
// This test cannot be a web test because web tests handles the GamepadMonitor
// interface on the renderer side. See GamepadController::Install().
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, GamepadMonitorCancelPrerendering) {
const GURL initial_url = GetUrl("/empty.html");
const GURL prerender_url = GetUrl("/empty.html?prerender");
GURL url_ping(GetUrl(kPagehideEventPath));
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
// Make a prerendered page.
FrameTreeNodeId host_id = AddPrerender(prerender_url);
auto* prerender_render_frame_host = GetPrerenderedMainFrameHost(host_id);
// Call fetchLater() to record that the pagehide event is fired.
std::string js = R"(
addEventListener('pagehide', () => {
fetchLater($1);
});)";
EXPECT_TRUE(ExecJs(prerender_render_frame_host, JsReplace(js, url_ping)));
EXPECT_FALSE(PageHideReceived());
// Executing `navigator.getGamepads()` to start binding the GamepadMonitor
// interface.
std::ignore = EvalJs(prerender_render_frame_host, "navigator.getGamepads()",
EvalJsOptions::EXECUTE_SCRIPT_NO_USER_GESTURE);
// Verify Mojo capability control cancels prerendering.
EXPECT_FALSE(HasHostForUrl(prerender_url));
ExpectFinalStatusForSpeculationRule(PrerenderFinalStatus::kMojoBinderPolicy);
histogram_tester().ExpectUniqueSample(
"Prerender.Experimental.PrerenderCancelledInterface.SpeculationRule",
PrerenderCancelledInterface::kGamepadMonitor, 1);
// Non-intentional prerender cancellation should not receive page hide.
EXPECT_FALSE(PageHideReceived());
}
// Tests that requesting to bind the GamepadMonitor interface after the
// prerenderingchange event dispatched does not cancel prerendering.
// This test cannot be a web test because web tests handles the GamepadMonitor
// interface on the renderer side. See GamepadController::Install().
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, GamepadMonitorAfterNavigation) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/prerender/restriction-gamepad.html");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Make a prerendered page.
ASSERT_EQ(GetRequestCount(kPrerenderingUrl), 0);
AddPrerender(kPrerenderingUrl);
ASSERT_EQ(GetRequestCount(kPrerenderingUrl), 1);
// Activate the prerendered page to dispatch the prerenderingchange event and
// run the Gamepad API in the event.
NavigatePrimaryPage(kPrerenderingUrl);
EXPECT_EQ(shell()->web_contents()->GetLastCommittedURL(), kPrerenderingUrl);
// Wait for the completion of the prerenderingchange event to make sure the
// API is called.
EXPECT_EQ(true, EvalJs(shell()->web_contents(), "prerenderingChanged"));
// The API call shouldn't discard the prerendered page and shouldn't restart
// navigation.
EXPECT_EQ(GetRequestCount(kPrerenderingUrl), 1);
}
// Tests that accessing the clipboard via the execCommand API fails because the
// page does not has any user activation.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, ClipboardByExecCommandFail) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/empty.html?prerender");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Make a prerendered page.
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
auto* prerender_render_frame_host = GetPrerenderedMainFrameHost(host_id);
// Access the clipboard and fail.
EXPECT_EQ(false,
EvalJs(prerender_render_frame_host, "document.execCommand('copy');",
EvalJsOptions::EXECUTE_SCRIPT_NO_USER_GESTURE));
EXPECT_EQ(false, EvalJs(prerender_render_frame_host,
"document.execCommand('paste');",
EvalJsOptions::EXECUTE_SCRIPT_NO_USER_GESTURE));
}
void LoadAndWaitForPrerenderDestroyed(test::PrerenderTestHelper* helper,
const GURL prerendering_url,
const std::string& target_hint) {
test::PrerenderHostCreationWaiter host_creation_waiter;
helper->AddPrerendersAsync({prerendering_url}, /*eagerness=*/std::nullopt,
target_hint);
FrameTreeNodeId host_id = host_creation_waiter.Wait();
auto* prerender_web_contents = WebContents::FromFrameTreeNodeId(host_id);
test::PrerenderHostObserver host_observer(*prerender_web_contents, host_id);
host_observer.WaitForDestroyed();
if (target_hint == "_blank") {
EXPECT_FALSE(helper->HasNewTabHandle(host_id));
} else {
EXPECT_TRUE(helper->GetHostForUrl(*prerender_web_contents, prerendering_url)
.is_null());
}
}
#if BUILDFLAG(ENABLE_PPAPI)
// Tests that we will cancel the prerendering if the prerendering page attempts
// to use plugins.
//
// TODO(crbug.com/40180674): This does not cover embedders that override
// `ContentRendererClient::OverrideCreatePlugin()` (such as for Chrome's PDF
// viewer), as cancellation depends on the renderer attempting to bind
// `content::mojom::PepperHost`.
IN_PROC_BROWSER_TEST_P(PrerenderTargetAgnosticBrowserTest,
PluginsCancelPrerendering) {
const GURL kInitialUrl = GetUrl("/empty.html");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
LoadAndWaitForPrerenderDestroyed(
prerender_helper(), GetUrl("/prerender/page-with-embedded-plugin.html"),
GetTargetHint());
ExpectFinalStatusForSpeculationRule(PrerenderFinalStatus::kMojoBinderPolicy);
histogram_tester().ExpectUniqueSample(
"Prerender.Experimental.PrerenderCancelledInterface.SpeculationRule",
PrerenderCancelledInterface::kUnknown, 1);
histogram_tester().ExpectUniqueSample(
"Prerender.Experimental.PrerenderCancelledUnknownInterface."
"SpeculationRule",
InterfaceNameHasher(mojom::PepperHost::Name_), 1);
LoadAndWaitForPrerenderDestroyed(
prerender_helper(), GetUrl("/prerender/page-with-object-plugin.html"),
GetTargetHint());
histogram_tester().ExpectUniqueSample(
"Prerender.Experimental.PrerenderHostFinalStatus.SpeculationRule",
PrerenderFinalStatus::kMojoBinderPolicy, 2);
histogram_tester().ExpectUniqueSample(
"Prerender.Experimental.PrerenderCancelledInterface.SpeculationRule",
PrerenderCancelledInterface::kUnknown, 2);
histogram_tester().ExpectUniqueSample(
"Prerender.Experimental.PrerenderCancelledUnknownInterface."
"SpeculationRule",
InterfaceNameHasher(mojom::PepperHost::Name_), 2);
// Run JavaScript code to inject a new iframe to load a page, and see if it
// correctly runs and results in making a navigation request in the iframe. If
// the initiator is still working normally after prerendering cancellation,
// this request should arrive.
RenderFrameHostImpl* main_frame_host = current_frame_host();
EXPECT_TRUE(AddTestUtilJS(main_frame_host));
EXPECT_TRUE(ExecJs(main_frame_host, "add_iframe_async('/title1.html')",
EvalJsOptions::EXECUTE_SCRIPT_NO_RESOLVE_PROMISES));
WaitForRequest(GetUrl("/title1.html"), 1);
}
#endif // BUILDFLAG(ENABLE_PPAPI)
#if BUILDFLAG(IS_ANDROID)
// On Android the Notification constructor throws an exception regardless of
// whether the page is being prerendered.
// Tests that we will get the exception from the prerendering if the
// prerendering page attempts to use notification.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, NotificationConstructorAndroid) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/empty.html?prerender");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Make a prerendered page.
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
auto* prerender_render_frame_host = GetPrerenderedMainFrameHost(host_id);
// Create the Notification and fail.
EXPECT_EQ(false, EvalJs(prerender_render_frame_host, R"(
(() => {
try { new Notification('My Notification'); return true;
} catch(e) { return false; }
})();
)"));
}
#endif // BUILDFLAG(IS_ANDROID)
// TODO(crbug.com/40184233): Make a WPT when we have a stable way to wait
// cancellation runs.
IN_PROC_BROWSER_TEST_P(PrerenderTargetAgnosticBrowserTest, DownloadByScript) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/empty.html?prerendering");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Make a prerendered page.
test::PrerenderHostCreationWaiter host_creation_waiter;
prerender_helper()->AddPrerendersAsync(
{kPrerenderingUrl}, /*eagerness=*/std::nullopt, GetTargetHint());
FrameTreeNodeId host_id = host_creation_waiter.Wait();
auto* prerender_web_contents = WebContents::FromFrameTreeNodeId(host_id);
test::PrerenderTestHelper::WaitForPrerenderLoadCompletion(
*prerender_web_contents, kPrerenderingUrl);
test::PrerenderHostObserver host_observer(*prerender_web_contents, host_id);
auto* prerender_host = test::PrerenderTestHelper::GetPrerenderedMainFrameHost(
*prerender_web_contents, host_id);
const std::string js_string = R"(
document.body.innerHTML =
"<a id='target' download='download-link' href='cache.txt'>here</a>";
document.getElementById('target').click();
)";
ExecuteScriptAsync(prerender_host, js_string);
host_observer.WaitForDestroyed();
if (GetTargetHint() == "_blank") {
EXPECT_FALSE(prerender_helper()->HasNewTabHandle(host_id));
} else {
EXPECT_TRUE(prerender_helper()
->GetHostForUrl(*prerender_web_contents, kPrerenderingUrl)
.is_null());
}
ExpectFinalStatusForSpeculationRule(PrerenderFinalStatus::kDownload);
}
IN_PROC_BROWSER_TEST_P(PrerenderTargetAgnosticBrowserTest,
DownloadInMainFrame) {
const GURL kInitialUrl = GetUrl("/empty.html");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// TODO(crbug.com/40184233): Make a WPT for the content-disposition WPT test.
const GURL kDownloadUrl =
GetUrl("/set-header?Content-Disposition: attachment");
LoadAndWaitForPrerenderDestroyed(prerender_helper(), kDownloadUrl,
GetTargetHint());
ExpectFinalStatusForSpeculationRule(PrerenderFinalStatus::kDownload);
}
IN_PROC_BROWSER_TEST_P(PrerenderTargetAgnosticBrowserTest, DownloadInSubframe) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/empty.html?prerendering");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Make a prerendered page.
test::PrerenderHostCreationWaiter host_creation_waiter;
prerender_helper()->AddPrerendersAsync(
{kPrerenderingUrl}, /*eagerness=*/std::nullopt, GetTargetHint());
FrameTreeNodeId host_id = host_creation_waiter.Wait();
auto* prerender_web_contents = WebContents::FromFrameTreeNodeId(host_id);
test::PrerenderTestHelper::WaitForPrerenderLoadCompletion(
*prerender_web_contents, kPrerenderingUrl);
test::PrerenderHostObserver host_observer(*prerender_web_contents, host_id);
auto* prerender_host = test::PrerenderTestHelper::GetPrerenderedMainFrameHost(
*prerender_web_contents, host_id);
EXPECT_TRUE(AddTestUtilJS(prerender_host));
// TODO(crbug.com/40184233): Make a WPT for the content-disposition WPT test.
const GURL kDownloadUrl =
GetUrl("/set-header?Content-Disposition: attachment");
ExecuteScriptAsync(prerender_host,
JsReplace("add_iframe_async($1)", kDownloadUrl));
host_observer.WaitForDestroyed();
if (GetTargetHint() == "_blank") {
EXPECT_FALSE(prerender_helper()->HasNewTabHandle(host_id));
} else {
EXPECT_TRUE(prerender_helper()
->GetHostForUrl(*prerender_web_contents, kPrerenderingUrl)
.is_null());
}
ExpectFinalStatusForSpeculationRule(PrerenderFinalStatus::kDownload);
}
// The viewport meta tag is only enabled on Android.
#if BUILDFLAG(IS_ANDROID)
namespace {
// Used to observe the viewport change in the WebContents.
class TestViewportWebContentsObserver : public WebContentsObserver {
public:
TestViewportWebContentsObserver(WebContents* web_contents,
blink::mojom::ViewportFit wanted_value)
: WebContentsObserver(web_contents), wanted_value_(wanted_value) {}
TestViewportWebContentsObserver(const TestViewportWebContentsObserver&) =
delete;
TestViewportWebContentsObserver& operator=(
const TestViewportWebContentsObserver&) = delete;
// WebContentsObserver implementation.
void ViewportFitChanged(blink::mojom::ViewportFit value) override {
value_ = value;
if (waiting_for_wanted_value_ && value == wanted_value_) {
std::move(waiting_for_wanted_value_).Run();
}
}
void WaitForWantedValue() {
if (value_.has_value() && value_.value() == wanted_value_) {
return;
}
base::RunLoop loop;
waiting_for_wanted_value_ = loop.QuitClosure();
loop.Run();
}
private:
base::OnceClosure waiting_for_wanted_value_;
std::optional<blink::mojom::ViewportFit> value_;
const blink::mojom::ViewportFit wanted_value_;
};
} // namespace
// Tests that the viewport-fit property works well on prerendering page:
// * The property in prerendering page shouldn't affect the primary page.
// * After activating the prerendered page, WebContents's viewport property can
// be updated.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, ViewportFit) {
const GURL kInitialUrl = GetUrl("/prerender/viewport.html");
const GURL kPrerenderingUrl = GetUrl("/prerender/viewport.html?prerendering");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
test::PrerenderHostObserver host_observer(*web_contents(), host_id);
RenderFrameHostImpl* prerender_rfh = GetPrerenderedMainFrameHost(host_id);
RenderFrameHostImpl* primary_rfh = web_contents_impl()->GetPrimaryMainFrame();
{
// Set viewport-fit property in the primary page and the prerendering page.
// Prerendering shouldn't be cancelled, nor should its property affect the
// corresponding WebContents's property.
TestViewportWebContentsObserver observer(web_contents_impl(),
blink::mojom::ViewportFit::kCover);
EXPECT_TRUE(ExecJs(prerender_rfh, "setViewportFit('contain')"));
EXPECT_TRUE(ExecJs(primary_rfh, "setViewportFit('cover')"));
web_contents_impl()->FullscreenStateChanged(
primary_rfh, true, blink::mojom::FullscreenOptions::New());
observer.WaitForWantedValue();
}
{
// After the prerendering page is activated, the WebContents's property
// should be updated.
TestViewportWebContentsObserver observer(
web_contents_impl(), blink::mojom::ViewportFit::kContain);
prerender_helper()->NavigatePrimaryPage(kPrerenderingUrl);
web_contents_impl()->FullscreenStateChanged(
prerender_rfh, true, blink::mojom::FullscreenOptions::New());
observer.WaitForWantedValue();
}
EXPECT_TRUE(host_observer.was_activated());
}
#endif // BUILDFLAG(IS_ANDROID)
// End: Tests for feature restrictions in prerendered pages ====================
// Tests prerendering for low-end devices.
class PrerenderLowMemoryBrowserTest : public PrerenderBrowserTest {
public:
PrerenderLowMemoryBrowserTest() {
// Set the value of memory threshold more than the physical memory. The
// test will expect that prerendering does not occur.
std::string memory_threshold =
base::NumberToString(base::SysInfo::AmountOfPhysicalMemoryMB() + 1);
feature_list_.InitWithFeaturesAndParameters(
{{blink::features::kPrerender2MemoryControls,
{{blink::features::kPrerender2MemoryThresholdParamName,
memory_threshold}}}},
{});
}
private:
base::test::ScopedFeatureList feature_list_;
};
// Tests that prerendering doesn't run for low-end devices.
IN_PROC_BROWSER_TEST_F(PrerenderLowMemoryBrowserTest, NoPrerender) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/empty.html?prerender");
// Attempt to prerender.
test::PrerenderHostRegistryObserver observer(*web_contents_impl());
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
AddPrerenderAsync(kPrerenderingUrl);
observer.WaitForTrigger(kPrerenderingUrl);
// It should fail.
EXPECT_FALSE(HasHostForUrl(kPrerenderingUrl));
ExpectFinalStatusForSpeculationRule(PrerenderFinalStatus::kLowEndDevice);
// Navigate primary page to flush the metrics.
NavigatePrimaryPage(kPrerenderingUrl);
// Cross-check that in case of low memory the eligibility reason points to
// kLowMemory.
ExpectPreloadingAttemptUkm({attempt_ukm_entry_builder().BuildEntry(
PrimaryPageSourceId(), PreloadingType::kPrerender,
PreloadingEligibility::kLowMemory, PreloadingHoldbackStatus::kUnspecified,
PreloadingTriggeringOutcome::kUnspecified,
PreloadingFailureReason::kUnspecified,
/*accurate=*/true,
/*ready_time=*/std::nullopt,
blink::mojom::SpeculationEagerness::kEager)});
}
class PrerenderSequentialPrerenderingBrowserTest : public PrerenderBrowserTest {
public:
PrerenderSequentialPrerenderingBrowserTest() {
std::vector<base::test::FeatureRefAndParams> enabled_features;
// Explicitly enables blink::features::kPrerender2InNewTab to override
// SpeculationRulesTargetHint.
enabled_features.push_back(base::test::FeatureRefAndParams(
blink::features::kPrerender2InNewTab, {}));
enabled_features.push_back(base::test::FeatureRefAndParams(
features::kPrerender2NewLimitAndScheduler,
{{"max_num_of_running_speculation_rules_eager_prerenders",
base::NumberToString(MaxNumOfRunningPrerenders())}}));
feature_list_.InitWithFeaturesAndParameters(enabled_features, {});
}
int MaxNumOfRunningPrerenders() const { return 4; }
protected:
void TestSequentialPrerenderingVisibilityStateTransition(
Visibility initial_visibility,
Visibility background_visibility);
private:
base::test::ScopedFeatureList feature_list_;
};
namespace {
// Records all the navigation start and finish events until the navigation to
// `target_url` finished.
class SequentialPrerenderObserver : public WebContentsObserver {
public:
enum class EventType {
kStart,
kFinish,
};
SequentialPrerenderObserver(WebContents& web_contents, const GURL& target_url)
: WebContentsObserver(&web_contents), target_url_(target_url) {}
const std::vector<std::pair<GURL, EventType>>& events_sequence() const {
return events_sequence_;
}
void WaitForTargetNavigationFinished() {
if (target_navigation_finished_) {
return;
}
base::RunLoop loop;
quit_closure_ = loop.QuitClosure();
loop.Run();
}
private:
void DidStartNavigation(NavigationHandle* handle) override {
events_sequence_.emplace_back(handle->GetURL(), EventType::kStart);
}
void DidFinishNavigation(NavigationHandle* handle) override {
events_sequence_.emplace_back(handle->GetURL(), EventType::kFinish);
if (handle->GetURL() != target_url_) {
return;
}
target_navigation_finished_ = true;
if (quit_closure_) {
std::move(quit_closure_).Run();
}
}
const GURL target_url_;
base::OnceClosure quit_closure_;
bool target_navigation_finished_ = false;
std::vector<std::pair<GURL, EventType>> events_sequence_;
};
} // namespace
// Tests that multiple prerenderings should be enqueued and the pending request
// starts right after the previous prerender calls DidFinishNavigation.
IN_PROC_BROWSER_TEST_F(PrerenderSequentialPrerenderingBrowserTest,
SequentialPrerendering) {
const GURL kInitialUrl = GetUrl("/empty.html");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
std::vector<GURL> prerender_urls;
for (int i = 0; i < 3; i++) {
prerender_urls.push_back(
GetUrl("/empty.html?prerender" + base::NumberToString(i)));
}
SequentialPrerenderObserver observer(*web_contents(), prerender_urls[2]);
// Insert 3 URLs into the speculation rules at the same time.
AddPrerendersAsync(prerender_urls);
// Wait for DidFinishNavigation on the last URL.
observer.WaitForTargetNavigationFinished();
// Check if all the prerender requests are handled sequentially.
std::vector<std::pair<GURL, SequentialPrerenderObserver::EventType>>
expected_sequence = {
{prerender_urls[0], SequentialPrerenderObserver::EventType::kStart},
{prerender_urls[1], SequentialPrerenderObserver::EventType::kStart},
{prerender_urls[0], SequentialPrerenderObserver::EventType::kFinish},
{prerender_urls[2], SequentialPrerenderObserver::EventType::kStart},
{prerender_urls[1], SequentialPrerenderObserver::EventType::kFinish},
{prerender_urls[2], SequentialPrerenderObserver::EventType::kFinish},
};
EXPECT_EQ(observer.events_sequence(), expected_sequence);
// Make sure if the activation succeeds and other prerender hosts are
// destroyed.
std::vector<std::unique_ptr<test::PrerenderHostObserver>> prerender_observers;
for (int i = 0; i < 3; i++) {
prerender_observers.push_back(std::make_unique<test::PrerenderHostObserver>(
*web_contents(), GetHostForUrl(prerender_urls[i])));
}
NavigatePrimaryPage(prerender_urls[1]);
prerender_observers[0]->WaitForDestroyed();
prerender_observers[1]->WaitForActivation();
prerender_observers[2]->WaitForDestroyed();
EXPECT_TRUE(prerender_observers[1]->was_activated());
EXPECT_FALSE(HasHostForUrl(prerender_urls[1]));
EXPECT_EQ(web_contents()->GetLastCommittedURL(), prerender_urls[1]);
histogram_tester().ExpectBucketCount(
"Prerender.Experimental.PrerenderHostFinalStatus.SpeculationRule",
PrerenderFinalStatus::kActivated, 1);
histogram_tester().ExpectBucketCount(
"Prerender.Experimental.PrerenderHostFinalStatus.SpeculationRule",
PrerenderFinalStatus::kOtherPrerenderedPageActivated, 2);
}
// Tests that a cancelled request in the pending queue is skipped and the next
// prerender starts.
IN_PROC_BROWSER_TEST_F(PrerenderSequentialPrerenderingBrowserTest,
SkipCancelledPrerenderAndStartNextPrerender) {
net::test_server::ControllableHttpResponse response1(
embedded_test_server(), "/empty.html?prerender1");
ASSERT_TRUE(embedded_test_server()->Start());
const GURL kInitialUrl = embedded_test_server()->GetURL("/empty.html");
const GURL kPrerender1 =
embedded_test_server()->GetURL("/empty.html?prerender1");
const GURL kPrerender2 =
embedded_test_server()->GetURL("/empty.html?prerender2");
const GURL kPrerender3 =
embedded_test_server()->GetURL("/empty.html?prerender3");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
test::PrerenderHostRegistryObserver registry_observer(*web_contents_impl());
// Insert 3 URLs into the speculation rules at the same time. The first
// prerender should start immediately, and the other two requests enqueued.
AddPrerendersAsync({kPrerender1, kPrerender2, kPrerender3});
registry_observer.WaitForTrigger(kPrerender3);
test::PrerenderHostObserver prerender3_observer(*web_contents(),
GetHostForUrl(kPrerender3));
// Stop the first prerendering initial navigation.
response1.WaitForRequest();
// Cancel the second prerender, and this cancellation shouldn't prevent the
// incoming third prerender from starting.
web_contents_impl()->GetPrerenderHostRegistry()->CancelHost(
GetHostForUrl(kPrerender2), PrerenderFinalStatus::kDestroyed);
// Resume the first prerender. The second one doesn't send
// request as the host has been already destroyed.
response1.Send(net::HTTP_OK, "");
response1.Done();
// Wait for the third prerender completes its initial navigation.
WaitForPrerenderLoadCompletion(kPrerender3);
// Activate the third prerender and it should succeed.
NavigatePrimaryPage(kPrerender3);
prerender3_observer.WaitForActivation();
EXPECT_EQ(web_contents()->GetLastCommittedURL(), kPrerender3);
EXPECT_TRUE(prerender3_observer.was_activated());
// The first prerender is destroyed during activation.
histogram_tester().ExpectBucketCount(
"Prerender.Experimental.PrerenderHostFinalStatus.SpeculationRule",
PrerenderFinalStatus::kOtherPrerenderedPageActivated, 1);
// The second prerender is destroyed directly.
histogram_tester().ExpectBucketCount(
"Prerender.Experimental.PrerenderHostFinalStatus.SpeculationRule",
PrerenderFinalStatus::kDestroyed, 1);
// The third prerender is successfully activated.
histogram_tester().ExpectBucketCount(
"Prerender.Experimental.PrerenderHostFinalStatus.SpeculationRule",
PrerenderFinalStatus::kActivated, 1);
}
// Test to make sure that the completion of iframe navigation in a prerendering
// page doesn't start another pending prerender request.
IN_PROC_BROWSER_TEST_F(
PrerenderSequentialPrerenderingBrowserTest,
IframeNavigationFinishDontDisruptPrerenderNavigationFinish) {
net::test_server::ControllableHttpResponse response2(
embedded_test_server(), "/empty.html?prerender2");
ASSERT_TRUE(embedded_test_server()->Start());
const GURL kInitialUrl = embedded_test_server()->GetURL("/empty.html");
const GURL kPrerender1 =
embedded_test_server()->GetURL("/empty.html?prerender1");
const GURL kPrerender2 =
embedded_test_server()->GetURL("/empty.html?prerender2");
const GURL kPrerender3 =
embedded_test_server()->GetURL("/empty.html?prerender3");
const GURL kIframeUrl = embedded_test_server()->GetURL("/empty.html?iframe");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Insert 3 URLs into the speculation rules at the same time. The first
// prerender should start immediately.
AddPrerendersAsync({kPrerender1, kPrerender2, kPrerender3});
// Stop the second prerendering initial navigation.
response2.WaitForRequest();
WaitForPrerenderLoadCompletion(kPrerender1);
FrameTreeNodeId host_id = GetHostForUrl(kPrerender1);
ASSERT_TRUE(host_id);
// Insert an iframe into the first prerender's main frame host.
RenderFrameHost* prerender_frame_host = GetPrerenderedMainFrameHost(host_id);
EXPECT_TRUE(AddTestUtilJS(prerender_frame_host));
EXPECT_EQ("LOADED", EvalJs(prerender_frame_host,
JsReplace("add_iframe($1)", kIframeUrl)));
RenderFrameHost* child_frame_host = ChildFrameAt(prerender_frame_host, 0);
ASSERT_NE(child_frame_host, nullptr);
ASSERT_EQ(child_frame_host->GetLastCommittedURL(), kIframeUrl);
// Confirm that the third prerender doesn't start even if the iframe
// navigation within the prerendered main frame has finished.
PrerenderHost* prerender3_host =
web_contents_impl()->GetPrerenderHostRegistry()->FindHostByUrlForTesting(
kPrerender3);
EXPECT_FALSE(prerender3_host->GetInitialNavigationId().has_value());
}
// Tests that if PrerenderHostRegistry is attempting to activate a pending
// prerender host, it will be successfully canceled with the final status of
// `kActivatedBeforeStarted`.
IN_PROC_BROWSER_TEST_F(PrerenderSequentialPrerenderingBrowserTest,
ActivateBeforePrerenderStarts) {
net::test_server::ControllableHttpResponse response(embedded_test_server(),
"/empty.html?prerender1");
ASSERT_TRUE(embedded_test_server()->Start());
const GURL kInitialUrl = embedded_test_server()->GetURL("/empty.html");
const GURL kPrerender1 =
embedded_test_server()->GetURL("/empty.html?prerender1");
const GURL kPrerender2 =
embedded_test_server()->GetURL("/empty.html?prerender2");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
test::PrerenderHostRegistryObserver registry_observer(*web_contents_impl());
// Insert 2 URLs into the speculation rules at the same time.
AddPrerendersAsync({kPrerender1, kPrerender2});
registry_observer.WaitForTrigger(kPrerender2);
test::PrerenderHostObserver prerender2_observer(*web_contents(),
GetHostForUrl(kPrerender2));
// Stop the first prerendering initial navigation.
response.WaitForRequest();
// Activate the page with pending prerender.
NavigatePrimaryPage(kPrerender2);
EXPECT_EQ(web_contents()->GetLastCommittedURL(), kPrerender2);
EXPECT_FALSE(prerender2_observer.was_activated());
// The first prerender was destroyed by SpeculationHostImpl.
histogram_tester().ExpectBucketCount(
"Prerender.Experimental.PrerenderHostFinalStatus.SpeculationRule",
PrerenderFinalStatus::kTriggerDestroyed, 1);
// The second prerender is destroyed since activation navigation is requested
// while it's still pending.
histogram_tester().ExpectBucketCount(
"Prerender.Experimental.PrerenderHostFinalStatus.SpeculationRule",
PrerenderFinalStatus::kActivatedBeforeStarted, 1);
ukm::SourceId ukm_source_id = PrimaryPageSourceId();
ExpectPreloadingAttemptUkm({
attempt_ukm_entry_builder().BuildEntry(
ukm_source_id, PreloadingType::kPrerender,
PreloadingEligibility::kEligible, PreloadingHoldbackStatus::kAllowed,
PreloadingTriggeringOutcome::kRunning,
PreloadingFailureReason::kUnspecified,
/*accurate=*/false,
/*ready_time=*/std::nullopt,
blink::mojom::SpeculationEagerness::kEager),
attempt_ukm_entry_builder().BuildEntry(
ukm_source_id, PreloadingType::kPrerender,
PreloadingEligibility::kEligible, PreloadingHoldbackStatus::kAllowed,
PreloadingTriggeringOutcome::kTriggeredButPending,
PreloadingFailureReason::kUnspecified,
/*accurate=*/true,
/*ready_time=*/std::nullopt,
blink::mojom::SpeculationEagerness::kEager),
});
}
// Test that if the 5 URLs are specified in the speculation rule while only 4
// prerenders are allowed, the 5th prerender should be cancelled.
IN_PROC_BROWSER_TEST_F(PrerenderSequentialPrerenderingBrowserTest,
ExceedTheRequestNumberLimit) {
net::test_server::ControllableHttpResponse response(embedded_test_server(),
"/empty.html?prerender1");
ASSERT_TRUE(embedded_test_server()->Start());
const GURL kInitialUrl = embedded_test_server()->GetURL("/empty.html");
std::vector<GURL> prerender_urls;
ASSERT_EQ(MaxNumOfRunningPrerenders(), 4);
for (int i = 0; i < MaxNumOfRunningPrerenders() + 1; i++) {
prerender_urls.push_back(embedded_test_server()->GetURL(
"/empty.html?prerender" + base::NumberToString(i)));
}
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
test::PrerenderHostRegistryObserver registry_observer(*web_contents_impl());
// Insert 5 URLs into the speculation rules at the same time.
AddPrerendersAsync(prerender_urls);
// Stop the first prerendering initial navigation.
response.WaitForRequest();
// Wait for the last prerender request will be triggered.
registry_observer.WaitForTrigger(prerender_urls.back());
// The last prerender is destroyed since the number of prerender requests
// from speculation rules exceeds its limit of 4.
histogram_tester().ExpectUniqueSample(
"Prerender.Experimental.PrerenderHostFinalStatus.SpeculationRule",
PrerenderFinalStatus::kMaxNumOfRunningEagerPrerendersExceeded, 1);
}
// Test that the requests from embedder are handled immediately regardless of
// the requests from speculation rules.
IN_PROC_BROWSER_TEST_F(PrerenderSequentialPrerenderingBrowserTest,
EmbedderPrerenderHandledImmediately) {
net::test_server::ControllableHttpResponse prerender1_response(
embedded_test_server(), "/empty.html?prerender1");
ASSERT_TRUE(embedded_test_server()->Start());
const GURL kInitialUrl = embedded_test_server()->GetURL("/empty.html");
const GURL kPrerender1 =
embedded_test_server()->GetURL("/empty.html?prerender1");
const GURL kPrerender2 =
embedded_test_server()->GetURL("/empty.html?prerender2");
const GURL kEmbedderPrerender =
embedded_test_server()->GetURL("/empty.html?embedder");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Insert 2 URLs into the speculation rules at the same time.
AddPrerendersAsync({kPrerender1, kPrerender2});
// Stop the first prerender's initial navigation.
prerender1_response.WaitForRequest();
// Start prerendering by embedder triggered prerendering; this should start
// immediately instead of being enqueued.
std::unique_ptr<PrerenderHandle> prerender_handle =
AddEmbedderTriggeredPrerender(kEmbedderPrerender);
EXPECT_TRUE(prerender_handle);
// Confirm that embedder triggered prerender does not affect the pending
// prerender triggered by speculation rules.
PrerenderHost* prerender2_host =
web_contents_impl()->GetPrerenderHostRegistry()->FindHostByUrlForTesting(
kPrerender2);
EXPECT_FALSE(prerender2_host->GetInitialNavigationId());
// Also confirm the remaining request triggered by speculation rules can
// resume if the first prerender finish its navigation, to make sure the
// prioritized embedder request doesn't break conditions of other requests.
prerender1_response.Send(net::HTTP_OK, "");
prerender1_response.Done();
WaitForPrerenderLoadCompletion(kPrerender2);
EXPECT_TRUE(HasHostForUrl(kPrerender2));
// Activate the embedder triggered prerender.
test::PrerenderHostObserver embedder_observer(
*web_contents(), GetHostForUrl(kEmbedderPrerender));
prerender_helper()->NavigatePrimaryPageAsync(
kEmbedderPrerender,
ui::PageTransitionFromInt(ui::PAGE_TRANSITION_TYPED |
ui::PAGE_TRANSITION_FROM_ADDRESS_BAR));
embedder_observer.WaitForActivation();
EXPECT_EQ(web_contents()->GetLastCommittedURL(), kEmbedderPrerender);
EXPECT_TRUE(embedder_observer.was_activated());
}
// Tests that if the running prerender is cancelled by
// PrerenderHostRegistry::CancelHost(), the next pending prerender starts its
// navigation.
IN_PROC_BROWSER_TEST_F(PrerenderSequentialPrerenderingBrowserTest,
RunningHostCancellationStartPendingPrerender) {
net::test_server::ControllableHttpResponse response(embedded_test_server(),
"/empty.html?prerender1");
ASSERT_TRUE(embedded_test_server()->Start());
const GURL kInitialUrl = embedded_test_server()->GetURL("/empty.html");
const GURL kPrerender1 =
embedded_test_server()->GetURL("/empty.html?prerender1");
const GURL kPrerender2 =
embedded_test_server()->GetURL("/empty.html?prerender2");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
test::PrerenderHostRegistryObserver registry_observer(*web_contents_impl());
// Insert 2 URLs into the speculation rules at the same time.
AddPrerendersAsync({kPrerender1, kPrerender2});
registry_observer.WaitForTrigger(kPrerender2);
test::PrerenderHostObserver prerender2_observer(*web_contents(),
GetHostForUrl(kPrerender2));
// Stop the first prerendering initial navigation.
response.WaitForRequest();
// Cancel the running prerender. The next pending prerender should start upon
// this cancellation.
web_contents_impl()->GetPrerenderHostRegistry()->CancelHost(
GetHostForUrl(kPrerender1), PrerenderFinalStatus::kDestroyed);
WaitForPrerenderLoadCompletion(kPrerender2);
// Activate the page with the prerender that was pending.
NavigatePrimaryPage(kPrerender2);
prerender2_observer.WaitForActivation();
EXPECT_EQ(web_contents()->GetLastCommittedURL(), kPrerender2);
EXPECT_TRUE(prerender2_observer.was_activated());
// The first prerender should be manually destroyed.
histogram_tester().ExpectBucketCount(
"Prerender.Experimental.PrerenderHostFinalStatus.SpeculationRule",
PrerenderFinalStatus::kDestroyed, 1);
// The second prerender should be successfully activated.
histogram_tester().ExpectBucketCount(
"Prerender.Experimental.PrerenderHostFinalStatus.SpeculationRule",
PrerenderFinalStatus::kActivated, 1);
}
// Tests that if the running prerender is cancelled by
// PrerenderHostRegistry::CancelHosts(), the next pending prerender
// starts its navigation.
IN_PROC_BROWSER_TEST_F(PrerenderSequentialPrerenderingBrowserTest,
SpeculationRulesUpdateStartPendingPrerender) {
net::test_server::ControllableHttpResponse response(embedded_test_server(),
"/empty.html?prerender1");
ASSERT_TRUE(embedded_test_server()->Start());
const GURL kInitialUrl = embedded_test_server()->GetURL("/empty.html");
const GURL kPrerender1 =
embedded_test_server()->GetURL("/empty.html?prerender1");
const GURL kPrerender2 =
embedded_test_server()->GetURL("/empty.html?prerender2");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
test::PrerenderHostRegistryObserver registry_observer(*web_contents_impl());
// Insert 2 URLs into the speculation rules in order. The prerender for
// `kPrerender1` should start first.
std::string script = R"(
let sc = document.createElement('script');
sc.type = 'speculationrules';
sc.id = $1;
sc.textContent = JSON.stringify({
prerender: [
{source: "list", urls: [$2]}
]
});
document.head.appendChild(sc);
)";
ASSERT_TRUE(ExecJs(web_contents_impl()->GetPrimaryMainFrame(),
JsReplace(script, "prerender1", kPrerender1)));
ASSERT_TRUE(ExecJs(web_contents_impl()->GetPrimaryMainFrame(),
JsReplace(script, "prerender2", kPrerender2)));
registry_observer.WaitForTrigger(kPrerender2);
test::PrerenderHostObserver prerender2_observer(*web_contents(),
GetHostForUrl(kPrerender2));
// Stop the first prerendering initial navigation.
response.WaitForRequest();
// Delete the first speculation rule. This speculation rules removal invokes
// the PrerenderHostRegistry::CancelHosts(), and the next pending
// prerender should start upon the cancellation.
ASSERT_TRUE(ExecJs(web_contents_impl()->GetPrimaryMainFrame(),
"document.querySelector('#prerender1').remove()"));
WaitForPrerenderLoadCompletion(kPrerender2);
// Activate the page with the prerender that was pending.
NavigatePrimaryPage(kPrerender2);
prerender2_observer.WaitForActivation();
EXPECT_EQ(web_contents()->GetLastCommittedURL(), kPrerender2);
EXPECT_TRUE(prerender2_observer.was_activated());
// The first prerender should be cancelled by the trigger.
histogram_tester().ExpectBucketCount(
"Prerender.Experimental.PrerenderHostFinalStatus.SpeculationRule",
PrerenderFinalStatus::kSpeculationRuleRemoved, 1);
// The second prerender should be successfully activated.
histogram_tester().ExpectBucketCount(
"Prerender.Experimental.PrerenderHostFinalStatus.SpeculationRule",
PrerenderFinalStatus::kActivated, 1);
}
// Test that a pending prerender should have the
// `PreloadingTriggeringOutcome::kTriggeredButPending`.
IN_PROC_BROWSER_TEST_F(PrerenderSequentialPrerenderingBrowserTest,
PreloadingTriggeringOutcomeForPendingPrerender) {
net::test_server::ControllableHttpResponse response1(
embedded_test_server(), "/empty.html?prerender1");
ASSERT_TRUE(embedded_test_server()->Start());
const GURL kInitialUrl = embedded_test_server()->GetURL("/empty.html");
const GURL kPrerender1 =
embedded_test_server()->GetURL("/empty.html?prerender1");
const GURL kPrerender2 =
embedded_test_server()->GetURL("/empty.html?prerender2");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
test::PrerenderHostRegistryObserver registry_observer(*web_contents_impl());
// Insert 2 URLs into the speculation rules at the same time.
AddPrerendersAsync({kPrerender1, kPrerender2});
registry_observer.WaitForTrigger(kPrerender2);
// Stop the first prerendering initial navigation.
response1.WaitForRequest();
// The pending host should have
// `PreloadingTriggeringOutcome::kTriggeredButPending`.
PrerenderHost* prerender2_host =
web_contents_impl()->GetPrerenderHostRegistry()->FindHostByUrlForTesting(
kPrerender2);
auto* preloading_attempt_impl = static_cast<PreloadingAttemptImpl*>(
prerender2_host->preloading_attempt().get());
EXPECT_EQ(test::PreloadingAttemptAccessor(preloading_attempt_impl)
.GetTriggeringOutcome(),
PreloadingTriggeringOutcome::kTriggeredButPending);
NavigationHandleObserver activation_observer(web_contents(), kPrerender1);
test::PrerenderHostObserver prerender1_observer(*web_contents(),
GetHostForUrl(kPrerender1));
// Defer the activation until the ongoing initial navigation in prerender
// frame tree commits.
TestActivationManager primary_page_manager(shell()->web_contents(),
kPrerender1);
ASSERT_TRUE(ExecJs(shell()->web_contents()->GetPrimaryMainFrame(),
JsReplace("location = $1", kPrerender1)));
NavigationRequest* request =
web_contents_impl()->GetPrimaryFrameTree().root()->navigation_request();
// Wait until the activation navigation is deferred by
// CommitDeferringCondition.
ASSERT_TRUE(primary_page_manager.WaitForBeforeChecks());
primary_page_manager.ResumeActivation();
// Confirm that the activation navigation is deferred.
EXPECT_TRUE(request->IsCommitDeferringConditionDeferredForTesting());
// Complete the first prerender response and finish its initial navigation.
response1.Send(net::HTTP_OK, "");
response1.Done();
primary_page_manager.WaitForNavigationFinished();
prerender1_observer.WaitForActivation();
// The prerender1 should succeed in activation and have kSuccess outcome. The
// prerender2 should start right after the activation but get destroyed by the
// change of the primary page soon, so it should result in the kRunning
// outcome.
ukm::SourceId ukm_source_id = activation_observer.next_page_ukm_source_id();
ExpectPreloadingAttemptUkm({
attempt_ukm_entry_builder().BuildEntry(
ukm_source_id, PreloadingType::kPrerender,
PreloadingEligibility::kEligible, PreloadingHoldbackStatus::kAllowed,
PreloadingTriggeringOutcome::kSuccess,
PreloadingFailureReason::kUnspecified,
/*accurate=*/true,
/*ready_time=*/kMockElapsedTime,
blink::mojom::SpeculationEagerness::kEager),
attempt_ukm_entry_builder().BuildEntry(
ukm_source_id, PreloadingType::kPrerender,
PreloadingEligibility::kEligible, PreloadingHoldbackStatus::kAllowed,
PreloadingTriggeringOutcome::kTriggeredButPending,
PreloadingFailureReason::kUnspecified,
/*accurate=*/false,
/*ready_time=*/std::nullopt,
blink::mojom::SpeculationEagerness::kEager),
});
}
// Test that when the running prerender is destroyed due to the activation of
// another already prerendered page, other pending prerender's outcome is
// recorded as `kTriggeredButPending`.
IN_PROC_BROWSER_TEST_F(
PrerenderSequentialPrerenderingBrowserTest,
PreloadingTriggeringOutcomeForStartingPrerenderBeforeDestruction) {
net::test_server::ControllableHttpResponse response2(
embedded_test_server(), "/empty.html?prerender2");
ASSERT_TRUE(embedded_test_server()->Start());
const GURL kInitialUrl = embedded_test_server()->GetURL("/empty.html");
const GURL kPrerender1 =
embedded_test_server()->GetURL("/empty.html?prerender1");
const GURL kPrerender2 =
embedded_test_server()->GetURL("/empty.html?prerender2");
const GURL kPrerender3 =
embedded_test_server()->GetURL("/empty.html?prerender3");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
test::PrerenderHostRegistryObserver registry_observer(*web_contents_impl());
// Insert 3 URLs into the speculation rules at the same time.
AddPrerendersAsync({kPrerender1, kPrerender2, kPrerender3});
registry_observer.WaitForTrigger(kPrerender3);
test::PrerenderHostObserver prerender1_observer(*web_contents(),
GetHostForUrl(kPrerender1));
// Stop the second prerendering initial navigation.
response2.WaitForRequest();
NavigationHandleObserver activation_observer(web_contents(), kPrerender1);
// Activate prerender1. The trigger should destroy all the other prerender
// hosts.
NavigatePrimaryPage(kPrerender1);
prerender1_observer.WaitForActivation();
EXPECT_EQ(web_contents()->GetLastCommittedURL(), kPrerender1);
EXPECT_TRUE(prerender1_observer.was_activated());
ukm::SourceId ukm_source_id = activation_observer.next_page_ukm_source_id();
ExpectPreloadingAttemptUkm({
attempt_ukm_entry_builder().BuildEntry(
ukm_source_id, PreloadingType::kPrerender,
PreloadingEligibility::kEligible, PreloadingHoldbackStatus::kAllowed,
PreloadingTriggeringOutcome::kSuccess,
PreloadingFailureReason::kUnspecified,
/*accurate=*/true,
/*ready_time=*/kMockElapsedTime,
blink::mojom::SpeculationEagerness::kEager),
attempt_ukm_entry_builder().BuildEntry(
ukm_source_id, PreloadingType::kPrerender,
PreloadingEligibility::kEligible, PreloadingHoldbackStatus::kAllowed,
PreloadingTriggeringOutcome::kRunning,
PreloadingFailureReason::kUnspecified,
/*accurate=*/false,
/*ready_time=*/std::nullopt,
blink::mojom::SpeculationEagerness::kEager),
attempt_ukm_entry_builder().BuildEntry(
ukm_source_id, PreloadingType::kPrerender,
PreloadingEligibility::kEligible, PreloadingHoldbackStatus::kAllowed,
PreloadingTriggeringOutcome::kTriggeredButPending,
PreloadingFailureReason::kUnspecified,
/*accurate=*/false,
/*ready_time=*/std::nullopt,
blink::mojom::SpeculationEagerness::kEager),
});
}
// Test that all the prerender hosts except the one to be activated are
// cancelled regardless of their status right after the PrerenderHostRegistry
// receives the activation request.
IN_PROC_BROWSER_TEST_F(PrerenderSequentialPrerenderingBrowserTest,
CancelAllPrerenderUponActivationRequestArrival) {
net::test_server::ControllableHttpResponse response3(
embedded_test_server(), "/empty.html?prerender3");
ASSERT_TRUE(embedded_test_server()->Start());
const GURL kInitialUrl = embedded_test_server()->GetURL("/empty.html");
ASSERT_EQ(MaxNumOfRunningPrerenders(), 4);
std::vector<GURL> prerender_urls;
for (int i = 1; i <= MaxNumOfRunningPrerenders(); i++) {
prerender_urls.push_back(embedded_test_server()->GetURL(
"/empty.html?prerender" + base::NumberToString(i)));
}
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
test::PrerenderHostRegistryObserver registry_observer(*web_contents_impl());
// Insert 4 URLs into the speculation rules at the same time.
AddPrerendersAsync(prerender_urls);
registry_observer.WaitForTrigger(prerender_urls[3]);
// Stop the third prerendering initial navigation.
response3.WaitForRequest();
NavigationHandleObserver activation_observer(web_contents(),
prerender_urls[0]);
test::PrerenderHostObserver prerender1_observer(
*web_contents(), GetHostForUrl(prerender_urls[0]));
// Defer the activation of the first prerender.
TestActivationManager primary_page_manager(shell()->web_contents(),
prerender_urls[0]);
ASSERT_TRUE(ExecJs(shell()->web_contents()->GetPrimaryMainFrame(),
JsReplace("location = $1", prerender_urls[0])));
ASSERT_TRUE(primary_page_manager.WaitForBeforeChecks());
NavigationRequest* request =
web_contents_impl()->GetPrimaryFrameTree().root()->navigation_request();
ASSERT_EQ(request->GetURL(), prerender_urls[0]);
// Confirm that all the other prerender hosts are successfully cancelled.
for (auto& url : prerender_urls) {
if (url == prerender_urls[0]) {
continue;
}
EXPECT_TRUE(GetHostForUrl(url).is_null());
}
// Resume the activation.
primary_page_manager.ResumeActivation();
prerender1_observer.WaitForActivation();
// When the PrerenderHostRegistry received the activation request, the status
// of each prerender host is:
// 1. Ready for activation,
// 2. Ready for activation,
// 3. Running,
// 4. Pending.
// We activated the first prerender, so all the other prerender hosts should
// be cancelled with each corresponding status.
ukm::SourceId ukm_source_id = activation_observer.next_page_ukm_source_id();
ExpectPreloadingAttemptUkm({
attempt_ukm_entry_builder().BuildEntry(
ukm_source_id, PreloadingType::kPrerender,
PreloadingEligibility::kEligible, PreloadingHoldbackStatus::kAllowed,
PreloadingTriggeringOutcome::kSuccess,
PreloadingFailureReason::kUnspecified,
/*accurate=*/true,
/*ready_time=*/kMockElapsedTime,
blink::mojom::SpeculationEagerness::kEager),
attempt_ukm_entry_builder().BuildEntry(
ukm_source_id, PreloadingType::kPrerender,
PreloadingEligibility::kEligible, PreloadingHoldbackStatus::kAllowed,
PreloadingTriggeringOutcome::kReady,
PreloadingFailureReason::kUnspecified,
/*accurate=*/false,
/*ready_time=*/kMockElapsedTime,
blink::mojom::SpeculationEagerness::kEager),
attempt_ukm_entry_builder().BuildEntry(
ukm_source_id, PreloadingType::kPrerender,
PreloadingEligibility::kEligible, PreloadingHoldbackStatus::kAllowed,
PreloadingTriggeringOutcome::kRunning,
PreloadingFailureReason::kUnspecified,
/*accurate=*/false,
/*ready_time=*/std::nullopt,
blink::mojom::SpeculationEagerness::kEager),
attempt_ukm_entry_builder().BuildEntry(
ukm_source_id, PreloadingType::kPrerender,
PreloadingEligibility::kEligible, PreloadingHoldbackStatus::kAllowed,
PreloadingTriggeringOutcome::kTriggeredButPending,
PreloadingFailureReason::kUnspecified,
/*accurate=*/false,
/*ready_time=*/std::nullopt,
blink::mojom::SpeculationEagerness::kEager),
});
}
// Tests that prerendering in a new tab multiple times and activating one of
// them succeed.
IN_PROC_BROWSER_TEST_F(PrerenderSequentialPrerenderingBrowserTest,
MultipleNewTabPrerendering) {
GURL initial_url = GetUrl("/simple_links.html");
std::vector<GURL> prerendering_urls = {GetUrl("/title2.html"),
GetUrl("/title2.html?2"),
GetUrl("/title2.html?3")};
// Navigate to an initial page which has a link to `prerendering_urls[0]`.
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
// Start prerendering.
std::vector<FrameTreeNodeId> prerender_host_ids;
std::vector<WebContents*> prerender_web_contents_list;
for (const GURL& prerendering_url : prerendering_urls) {
FrameTreeNodeId host_id = prerender_helper()->AddPrerender(
prerendering_url, /*eagerness=*/std::nullopt, "_blank");
EXPECT_FALSE(base::Contains(prerender_host_ids, host_id));
prerender_host_ids.push_back(host_id);
// Make sure that prerendering in a new tab creates new WebContentsImpl, not
// reuse existing WebContentsImpl.
auto* prerender_web_contents = WebContents::FromFrameTreeNodeId(host_id);
ASSERT_TRUE(prerender_web_contents);
EXPECT_NE(prerender_web_contents, web_contents_impl());
ExpectWebContentsIsForNewTabPrerendering(*prerender_web_contents);
EXPECT_FALSE(
base::Contains(prerender_web_contents_list, prerender_web_contents));
prerender_web_contents_list.push_back(prerender_web_contents);
}
// Click the link to prerendering_urls[0]. This should activate
// prerender_host_ids[0].
test::PrerenderHostObserver prerender_observer(
*prerender_web_contents_list[0], prerender_host_ids[0]);
const std::string kLinkClickScript = R"(
clickSameSiteNewWindowLink();
)";
EXPECT_TRUE(ExecJs(web_contents(), kLinkClickScript));
prerender_observer.WaitForActivation();
EXPECT_EQ(prerender_web_contents_list[0]->GetLastCommittedURL(),
prerendering_urls[0]);
EXPECT_TRUE(prerender_observer.was_activated());
// prerendering_urls[0] was consumed for activation, but others were not.
EXPECT_FALSE(
HasHostForUrl(*prerender_web_contents_list[0], prerendering_urls[0]));
EXPECT_TRUE(
HasHostForUrl(*prerender_web_contents_list[1], prerendering_urls[1]));
EXPECT_TRUE(
HasHostForUrl(*prerender_web_contents_list[2], prerendering_urls[2]));
ExpectFinalStatusForSpeculationRule(PrerenderFinalStatus::kActivated);
// The navigation occurred in a new WebContents, so the original WebContents
// should still be showing the initial trigger page.
EXPECT_EQ(web_contents()->GetLastCommittedURL(), initial_url);
}
// Test that the prerender request is handled and stored regardless of the
// initial visibility of the current tab, and when the current tab goes
// background (in the cases where HIDDEN or OCCLUDED is specified by
// `next_visibility`) then the prerender sequence is terminated, and when
// the current tab gets visible then we start the next prerender if we have some
// pending prerender hosts. Note that if the initial visibility is background,
// there is still one prerender allowed to be running.
void PrerenderSequentialPrerenderingBrowserTest::
TestSequentialPrerenderingVisibilityStateTransition(
Visibility initial_visibility,
Visibility next_visibility) {
net::test_server::ControllableHttpResponse response1(
embedded_test_server(), "/empty.html?prerender1");
ASSERT_TRUE(embedded_test_server()->Start());
const GURL initial_url = embedded_test_server()->GetURL("/empty.html");
const GURL prerender_url1 =
embedded_test_server()->GetURL("/empty.html?prerender1");
const GURL prerender_url2 =
embedded_test_server()->GetURL("/empty.html?prerender2");
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
// Set the initial visibility.
switch (initial_visibility) {
case Visibility::VISIBLE:
web_contents()->WasShown();
break;
case Visibility::HIDDEN:
web_contents()->WasHidden();
break;
case Visibility::OCCLUDED:
web_contents()->WasOccluded();
break;
}
test::PrerenderHostRegistryObserver registry_observer(*web_contents_impl());
// Insert 2 URLs into the speculation rules at the same time.
AddPrerendersAsync({prerender_url1, prerender_url2});
registry_observer.WaitForTrigger(prerender_url2);
test::PrerenderHostObserver prerender2_observer(
*web_contents(), GetHostForUrl(prerender_url2));
// Stop the first prerendering initial navigation.
response1.WaitForRequest();
// Change the visibility status to HIDDEN/OCCLUDED.
switch (next_visibility) {
case Visibility::HIDDEN:
web_contents()->WasHidden();
break;
case Visibility::OCCLUDED:
web_contents()->WasOccluded();
break;
case Visibility::VISIBLE:
// The timing of `next_visibility`=Visibility::VISIBLE is delayed until a
// later point.
break;
}
// Complete the first prerender response and finish its initial navigation.
// This shouldn't start the pending prerender.
response1.Send(net::HTTP_OK, "");
response1.Done();
WaitForPrerenderLoadCompletion(prerender_url1);
// Check the prerender host is already ready.
PrerenderHost* prerender_host =
web_contents_impl()->GetPrerenderHostRegistry()->FindHostByUrlForTesting(
prerender_url1);
auto* preloading_attempt_impl = static_cast<PreloadingAttemptImpl*>(
prerender_host->preloading_attempt().get());
EXPECT_EQ(test::PreloadingAttemptAccessor(preloading_attempt_impl)
.GetTriggeringOutcome(),
PreloadingTriggeringOutcome::kReady);
// Check the next prerender host is still pending.
PrerenderHost* prerender2_host =
web_contents_impl()->GetPrerenderHostRegistry()->FindHostByUrlForTesting(
prerender_url2);
auto* preloading_attempt_impl2 = static_cast<PreloadingAttemptImpl*>(
prerender2_host->preloading_attempt().get());
EXPECT_EQ(test::PreloadingAttemptAccessor(preloading_attempt_impl2)
.GetTriggeringOutcome(),
PreloadingTriggeringOutcome::kTriggeredButPending);
// The hidden/occluded page gets back to the foreground. The next pending
// prerender should start. The case of `next_visibility`=Visibility::VISIBLE
// is delayed until now.
web_contents()->WasShown();
WaitForPrerenderLoadCompletion(prerender_url2);
// Check the next prerender host is already ready.
auto* preloading_attempt_impl2_2 = static_cast<PreloadingAttemptImpl*>(
prerender2_host->preloading_attempt().get());
EXPECT_EQ(test::PreloadingAttemptAccessor(preloading_attempt_impl2_2)
.GetTriggeringOutcome(),
PreloadingTriggeringOutcome::kReady);
// Activate the second prerender.
NavigatePrimaryPage(prerender_url2);
prerender2_observer.WaitForActivation();
EXPECT_EQ(web_contents()->GetLastCommittedURL(), prerender_url2);
EXPECT_TRUE(prerender2_observer.was_activated());
}
IN_PROC_BROWSER_TEST_F(PrerenderSequentialPrerenderingBrowserTest,
PrerenderInBackground_InitialyVisible_Hidden) {
TestSequentialPrerenderingVisibilityStateTransition(Visibility::VISIBLE,
Visibility::HIDDEN);
}
IN_PROC_BROWSER_TEST_F(PrerenderSequentialPrerenderingBrowserTest,
PrerenderInBackground_InitialyVisible_Occluded) {
TestSequentialPrerenderingVisibilityStateTransition(Visibility::VISIBLE,
Visibility::OCCLUDED);
}
IN_PROC_BROWSER_TEST_F(PrerenderSequentialPrerenderingBrowserTest,
PrerenderInBackground_InitialyOccluded_Hidden) {
TestSequentialPrerenderingVisibilityStateTransition(Visibility::OCCLUDED,
Visibility::HIDDEN);
}
IN_PROC_BROWSER_TEST_F(PrerenderSequentialPrerenderingBrowserTest,
PrerenderInBackground_InitialyOccluded_Occluded) {
TestSequentialPrerenderingVisibilityStateTransition(Visibility::OCCLUDED,
Visibility::OCCLUDED);
}
IN_PROC_BROWSER_TEST_F(PrerenderSequentialPrerenderingBrowserTest,
PrerenderInBackground_InitialyHidden_Hidden) {
TestSequentialPrerenderingVisibilityStateTransition(Visibility::HIDDEN,
Visibility::HIDDEN);
}
IN_PROC_BROWSER_TEST_F(PrerenderSequentialPrerenderingBrowserTest,
PrerenderInBackground_InitialyHidden_Occluded) {
TestSequentialPrerenderingVisibilityStateTransition(Visibility::HIDDEN,
Visibility::OCCLUDED);
}
IN_PROC_BROWSER_TEST_F(PrerenderSequentialPrerenderingBrowserTest,
PrerenderInBackground_InitialyHidden_Visible) {
TestSequentialPrerenderingVisibilityStateTransition(Visibility::HIDDEN,
Visibility::VISIBLE);
}
// TODO(b/40234240): Flaky on win.
#if BUILDFLAG(IS_WIN)
#define MAYBE_PrerenderWhenInitiatorInBackground_Queue_Processing \
DISABLED_PrerenderWhenInitiatorInBackground_Queue_Processing
#else
#define MAYBE_PrerenderWhenInitiatorInBackground_Queue_Processing \
PrerenderWhenInitiatorInBackground_Queue_Processing
#endif
IN_PROC_BROWSER_TEST_F(
PrerenderSequentialPrerenderingBrowserTest,
MAYBE_PrerenderWhenInitiatorInBackground_Queue_Processing) {
ASSERT_TRUE(embedded_test_server()->Start());
const GURL initial_url = embedded_test_server()->GetURL("/empty.html");
const GURL prerender_url1 =
embedded_test_server()->GetURL("/empty.html?prerender1");
const GURL prerender_url2 =
embedded_test_server()->GetURL("/empty.html?prerender2");
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
web_contents()->WasHidden();
test::PrerenderHostRegistryObserver registry_observer(*web_contents_impl());
// Insert 2 URLs into the speculation rules at the same time.
AddPrerendersAsync({prerender_url1, prerender_url2});
registry_observer.WaitForTrigger(prerender_url2);
WaitForPrerenderLoadCompletion(prerender_url1);
// Check the prerender host is already ready.
PrerenderHost* prerender_host =
web_contents_impl()->GetPrerenderHostRegistry()->FindHostByUrlForTesting(
prerender_url1);
auto* preloading_attempt_impl = static_cast<PreloadingAttemptImpl*>(
prerender_host->preloading_attempt().get());
EXPECT_EQ(test::PreloadingAttemptAccessor(preloading_attempt_impl)
.GetTriggeringOutcome(),
PreloadingTriggeringOutcome::kReady);
// Check the next prerender host is still pending.
PrerenderHost* prerender2_host =
web_contents_impl()->GetPrerenderHostRegistry()->FindHostByUrlForTesting(
prerender_url2);
auto* preloading_attempt_impl2 = static_cast<PreloadingAttemptImpl*>(
prerender2_host->preloading_attempt().get());
EXPECT_EQ(test::PreloadingAttemptAccessor(preloading_attempt_impl2)
.GetTriggeringOutcome(),
PreloadingTriggeringOutcome::kTriggeredButPending);
// Test if prerender_url1 is cancelled, the prerender host of prerender_url2
// should be processed.
web_contents_impl()->GetPrerenderHostRegistry()->CancelHost(
GetHostForUrl(prerender_url1), PrerenderFinalStatus::kDestroyed);
WaitForPrerenderLoadCompletion(prerender_url2);
// Check the next prerender host is already ready.
test::PrerenderHostObserver prerender2_observer(
*web_contents(), GetHostForUrl(prerender_url2));
auto* preloading_attempt_impl2_2 = static_cast<PreloadingAttemptImpl*>(
prerender2_host->preloading_attempt().get());
EXPECT_EQ(test::PreloadingAttemptAccessor(preloading_attempt_impl2_2)
.GetTriggeringOutcome(),
PreloadingTriggeringOutcome::kReady);
// Activate the second prerender.
web_contents()->WasShown();
NavigatePrimaryPage(prerender_url2);
prerender2_observer.WaitForActivation();
EXPECT_EQ(web_contents()->GetLastCommittedURL(), prerender_url2);
EXPECT_TRUE(prerender2_observer.was_activated());
}
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
IsInactiveAndDisallowActivationCancelsPrerendering) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/empty.html?prerender");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
ASSERT_EQ(web_contents()->GetLastCommittedURL(), kInitialUrl);
// Start prerendering `kPrerenderingUrl`.
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
auto* prerender_render_frame_host = GetPrerenderedMainFrameHost(host_id);
// Invoke IsInactiveAndDisallowActivation for the prerendered document.
EXPECT_EQ(prerender_render_frame_host->lifecycle_state(),
RenderFrameHostImpl::LifecycleStateImpl::kPrerendering);
EXPECT_TRUE(prerender_render_frame_host->IsInactiveAndDisallowActivation(
DisallowActivationReasonId::kForTesting));
// The prerender host for the URL should be destroyed as
// RenderFrameHost::IsInactiveAndDisallowActivation cancels prerendering in
// LifecycleStateImpl::kPrerendering state.
EXPECT_FALSE(HasHostForUrl(kPrerenderingUrl));
// Cancelling the prerendering disables the activation. The navigation
// should issue a request again.
NavigatePrimaryPage(kPrerenderingUrl);
EXPECT_EQ(GetRequestCount(kPrerenderingUrl), 2);
ExpectFinalStatusForSpeculationRule(
PrerenderFinalStatus::kInactivePageRestriction);
histogram_tester().ExpectUniqueSample(
"Prerender.CanceledForInactivePageRestriction.DisallowActivationReason."
"SpeculationRule",
DisallowActivationReasonId::kForTesting, 1);
}
// Make sure input events are routed to the primary FrameTree not the prerender
// one. See https://crbug.com/1197136
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, InputRoutedToPrimaryFrameTree) {
const GURL kInitialUrl = GetUrl("/prerender/simple_prerender.html");
const GURL kPrerenderingUrl = GetUrl("/empty.html");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
WaitForPrerenderLoadCompletion(kPrerenderingUrl);
// Touch / click the link and wait for the navigation to complete.
TestNavigationObserver navigation_observer(web_contents());
SyntheticTapGestureParams params;
params.gesture_source_type = mojom::GestureSourceType::kTouchInput;
params.position = GetCenterCoordinatesOfElementWithId(web_contents(), "link");
web_contents_impl()->GetRenderViewHost()->GetWidget()->QueueSyntheticGesture(
std::make_unique<SyntheticTapGesture>(params), base::DoNothing());
navigation_observer.Wait();
EXPECT_EQ(shell()->web_contents()->GetLastCommittedURL(), kPrerenderingUrl);
}
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, VisibilityWhilePrerendering) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/empty.html?prerender");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
ASSERT_EQ(shell()->web_contents()->GetLastCommittedURL(), kInitialUrl);
// Start prerendering `kPrerenderingUrl`.
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
auto* prerendered_render_frame_host = GetPrerenderedMainFrameHost(host_id);
// The visibility state must be "hidden" while prerendering.
auto* rvh = static_cast<RenderViewHostImpl*>(
prerendered_render_frame_host->GetRenderViewHost());
EXPECT_EQ(rvh->GetPageLifecycleStateManager()
->CalculatePageLifecycleState()
->visibility,
PageVisibilityState::kHidden);
EXPECT_EQ(prerendered_render_frame_host->GetVisibilityState(),
PageVisibilityState::kHidden);
// Activate prerendering page.
NavigatePrimaryPage(kPrerenderingUrl);
// The visibility state should be "visible" after activation.
EXPECT_EQ(rvh->GetPageLifecycleStateManager()
->CalculatePageLifecycleState()
->visibility,
PageVisibilityState::kVisible);
EXPECT_EQ(prerendered_render_frame_host->GetVisibilityState(),
PageVisibilityState::kVisible);
}
// Tests that prerendering doesn't affect WebContents::GetTitle().
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, TitleWhilePrerendering) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/simple_page.html");
const std::u16string kInitialTitle(u"title");
const std::u16string kPrerenderingTitle(u"OK");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
EXPECT_TRUE(ExecJs(shell()->web_contents(),
JsReplace("document.title = $1", kInitialTitle)));
EXPECT_EQ(shell()->web_contents()->GetTitle(), kInitialTitle);
// Start a prerender to `kPrerenderUrl` that has title `kPrerenderingTitle`.
ASSERT_TRUE(AddPrerender(kPrerenderingUrl));
// Make sure that WebContents::GetTitle() returns the current title from the
// primary page.
EXPECT_EQ(shell()->web_contents()->GetTitle(), kInitialTitle);
NavigatePrimaryPage(kPrerenderingUrl);
EXPECT_EQ(shell()->web_contents()->GetLastCommittedURL(), kPrerenderingUrl);
// The title should be updated with the activated page.
EXPECT_EQ(shell()->web_contents()->GetTitle(), kPrerenderingTitle);
}
// Tests that WebContentsObserver::TitleWasSet is not dispatched when title is
// set during prerendering, but is later dispatched after activation.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, TitleWasSetWithPrerendering) {
const GURL kInitialUrl = GetUrl("/title2.html");
const GURL kPrerenderingUrlWithTitle = GetUrl("/simple_page.html");
const GURL kPrerenderingUrlWithoutTitle = GetUrl("/title1.html");
const std::u16string kInitialTitle(u"Title Of Awesomeness");
const std::u16string kPrerenderingTitle(u"OK");
// Navigate to an initial page; TitleWasSet should be called when page sets
// its title.
{
testing::NiceMock<MockWebContentsObserver> mock_observer(
shell()->web_contents());
EXPECT_CALL(mock_observer, TitleWasSet(testing::_));
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
EXPECT_EQ(shell()->web_contents()->GetTitle(), kInitialTitle);
}
// Prerender a page; TitleWasSet should not be called despite the page setting
// a title.
{
testing::NiceMock<MockWebContentsObserver> mock_observer(
shell()->web_contents());
EXPECT_CALL(mock_observer, TitleWasSet(testing::_)).Times(0);
ASSERT_TRUE(AddPrerender(kPrerenderingUrlWithTitle));
}
// Activate prerendered page; TitleWasSet should now be called.
{
testing::NiceMock<MockWebContentsObserver> mock_observer(
shell()->web_contents());
EXPECT_CALL(mock_observer, TitleWasSet(testing::_))
.WillOnce(testing::Invoke([kPrerenderingTitle](NavigationEntry* entry) {
EXPECT_EQ(entry->GetTitleForDisplay(), kPrerenderingTitle);
}));
NavigatePrimaryPage(kPrerenderingUrlWithTitle);
}
// Prerender a page without a title and then activate it; TitleWasSet should
// not be called.
{
testing::NiceMock<MockWebContentsObserver> mock_observer(
shell()->web_contents());
EXPECT_CALL(mock_observer, TitleWasSet(testing::_)).Times(0);
ASSERT_TRUE(AddPrerender(kPrerenderingUrlWithoutTitle));
NavigatePrimaryPage(kPrerenderingUrlWithoutTitle);
}
}
// Test that the prerender request from embedder to non-HTTP(S) scheme URL
// should fail because `PrerenderNavigationThrottle` discards the request. This
// is a regression test for https://crbug.com/1361210.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, EmbedderPrerenderToNonHttpUrl) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderUrl = GURL("file://example.txt");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
ASSERT_EQ(shell()->web_contents()->GetLastCommittedURL(), kInitialUrl);
// Start prerendering by embedder triggered prerendering.
std::unique_ptr<PrerenderHandle> prerender_handle =
AddEmbedderTriggeredPrerenderAsync(kPrerenderUrl);
// Both the creation of PrerenderHandle and PrerenderHost should fail.
EXPECT_FALSE(prerender_handle);
EXPECT_TRUE(GetHostForUrl(kPrerenderUrl).is_null());
histogram_tester().ExpectUniqueSample(
"Prerender.Experimental.PrerenderHostFinalStatus.Embedder_"
"EmbedderSuffixForTest",
PrerenderFinalStatus::kInvalidSchemeNavigation, 1);
}
// Ensures WebContents::OpenURL targeting a frame in a prerendered host will
// successfully navigate that frame.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, OpenURLInPrerenderingFrame) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/page_with_blank_iframe.html");
const GURL kNewIframeUrl = GetUrl("/simple_page.html");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
ASSERT_EQ(shell()->web_contents()->GetLastCommittedURL(), kInitialUrl);
// Start prerendering `kPrerenderingUrl`.
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
auto* prerendered_render_frame_host = GetPrerenderedMainFrameHost(host_id);
auto* child_frame = ChildFrameAt(prerendered_render_frame_host, 0);
ASSERT_TRUE(child_frame);
// Navigate the iframe's FrameTreeNode in the prerendering frame tree. This
// should successfully navigate.
TestNavigationManager iframe_observer(shell()->web_contents(), kNewIframeUrl);
shell()->web_contents()->OpenURL(
OpenURLParams(
kNewIframeUrl, Referrer(), child_frame->GetFrameTreeNodeId(),
WindowOpenDisposition::CURRENT_TAB, ui::PAGE_TRANSITION_AUTO_SUBFRAME,
/*is_renderer_initiated=*/false),
/*navigation_handle_callback=*/{});
ASSERT_TRUE(iframe_observer.WaitForNavigationFinished());
EXPECT_TRUE(iframe_observer.was_committed());
EXPECT_TRUE(iframe_observer.was_successful());
EXPECT_EQ(child_frame->GetLastCommittedURL(), kNewIframeUrl);
}
// Ensure that WebContentsObserver::DidFailLoad is not invoked and cancels
// prerendering when invoked on the prerendering main frame.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, DidFailLoadCancelsPrerendering) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/page_with_iframe.html");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Initialize a MockWebContentsObserver and ensure that DidFailLoad is not
// invoked inside prerender frame tree.
testing::NiceMock<MockWebContentsObserver> observer(shell()->web_contents());
EXPECT_CALL(observer, DidFailLoad(testing::_, testing::_, testing::_))
.Times(0);
// Start a prerender.
FrameTreeNodeId prerender_host_id = AddPrerender(kPrerenderingUrl);
RenderFrameHostImpl* prerender_frame_host =
GetPrerenderedMainFrameHost(prerender_host_id);
// Trigger DidFailLoad, this should cancel prerendering.
prerender_frame_host->DidFailLoadWithError(kPrerenderingUrl, net::ERR_FAILED);
// The prerender host for the URL should be deleted as DidFailLoad cancels
// prerendering.
test::PrerenderHostObserver prerender_observer(*web_contents(),
kPrerenderingUrl);
TestNavigationManager navigation_observer(shell()->web_contents(),
kPrerenderingUrl);
EXPECT_FALSE(HasHostForUrl(kPrerenderingUrl));
// Now navigate the primary page to the prerendered URL. Cancelling the
// prerender disables the activation due to DidFailLoad.
ASSERT_TRUE(ExecJs(web_contents()->GetPrimaryMainFrame(),
JsReplace("location = $1", kPrerenderingUrl)));
ASSERT_TRUE(navigation_observer.WaitForNavigationFinished());
EXPECT_FALSE(prerender_observer.was_activated());
ExpectFinalStatusForSpeculationRule(PrerenderFinalStatus::kDidFailLoad);
}
class DidFailLoadWebContentsObserver : public WebContentsObserver {
public:
explicit DidFailLoadWebContentsObserver(WebContents* web_contents)
: WebContentsObserver(web_contents) {}
bool WasDidFailLoadCalled() { return was_did_fail_load_called_; }
int GetErrorCode() const { return error_code_; }
const GURL& GetUrl() const { return url_; }
private:
void DidFailLoad(RenderFrameHost* rfh,
const GURL& url,
int error_code) override {
was_did_fail_load_called_ = true;
url_ = url;
error_code_ = error_code;
EXPECT_FALSE(rfh->IsErrorDocument());
EXPECT_TRUE(rfh->IsInLifecycleState(
RenderFrameHost::LifecycleState::kPrerendering));
}
bool was_did_fail_load_called_ = false;
int error_code_ = net::OK;
GURL url_;
};
// Ensure that RenderFrameHost::DidFailLoad on subframes don't cancel
// prerendering. This happens when JavaScript calls `window.stop()` in a
// frame, for instance.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
DidFailLoadSubframesDoesNotCancelPrerendering) {
DidFailLoadWebContentsObserver observer(web_contents());
TestHostPrerenderingState(GetUrl("/page_with_stop_iframe.html"));
EXPECT_TRUE(observer.WasDidFailLoadCalled());
EXPECT_EQ(net::ERR_ABORTED, observer.GetErrorCode());
EXPECT_EQ(GetUrl("/stop.html"), observer.GetUrl());
}
// Ensure that RenderFrameHost::DidFailLoad on the main frame cancels
// prerendering. This happens when JavaScript calls `window.stop()` in the
// main frame, for instance.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
DidFailLoadMainFrameCancelsPrerendering) {
DidFailLoadWebContentsObserver observer(web_contents());
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/stop.html");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start a prerender and wait until it is canceled.
test::PrerenderHostObserver host_observer(*web_contents_impl(),
kPrerenderingUrl);
AddPrerenderAsync(kPrerenderingUrl);
host_observer.WaitForDestroyed();
// DidFailLoad callback should not be called.
EXPECT_FALSE(observer.WasDidFailLoadCalled());
// Prerendering should be canceled for kDidFailLoad.
ExpectFinalStatusForSpeculationRule(PrerenderFinalStatus::kDidFailLoad);
}
// Ensures WebContents::OpenURL with a cross-origin URL targeting a frame in a
// prerendered host will successfully navigate that frame, though it should be
// deferred until activation.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
OpenURLCrossOriginInPrerenderingFrame) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/page_with_blank_iframe.html");
const GURL kNewIframeUrl = GetCrossSiteUrl("/simple_page.html");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
ASSERT_EQ(shell()->web_contents()->GetLastCommittedURL(), kInitialUrl);
// Start prerendering `kPrerenderingUrl`.
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
auto* prerendered_render_frame_host = GetPrerenderedMainFrameHost(host_id);
auto* child_frame = ChildFrameAt(prerendered_render_frame_host, 0);
ASSERT_TRUE(child_frame);
TestNavigationManager iframe_observer(shell()->web_contents(), kNewIframeUrl);
// Navigate the iframe's FrameTreeNode in the prerendering frame tree. This
// should successfully navigate but the navigation will be deferred until the
// prerendering page is activated.
{
shell()->web_contents()->OpenURL(
OpenURLParams(kNewIframeUrl, Referrer(),
child_frame->GetFrameTreeNodeId(),
WindowOpenDisposition::CURRENT_TAB,
ui::PAGE_TRANSITION_AUTO_SUBFRAME,
/*is_renderer_initiated=*/false),
/*navigation_handle_callback=*/{});
ASSERT_TRUE(iframe_observer.WaitForFirstYieldAfterDidStartNavigation());
NavigationRequest* request =
static_cast<NavigationRequest*>(iframe_observer.GetNavigationHandle());
EXPECT_EQ(request->state(), NavigationRequest::WILL_START_REQUEST);
EXPECT_TRUE(request->IsDeferredForTesting());
}
// Now navigate the primary page to the prerendered URL so that we activate
// the prerender.
{
test::PrerenderHostObserver prerender_observer(*web_contents(),
kPrerenderingUrl);
ASSERT_TRUE(ExecJs(web_contents()->GetPrimaryMainFrame(),
JsReplace("location = $1", kPrerenderingUrl)));
prerender_observer.WaitForActivation();
}
// Now that we're activated, the iframe navigation should be able to finish.
// Ensure the navigation completes in the iframe.
{
ASSERT_TRUE(iframe_observer.WaitForNavigationFinished());
child_frame = ChildFrameAt(web_contents()->GetPrimaryMainFrame(), 0);
ASSERT_TRUE(child_frame);
EXPECT_EQ(child_frame->GetLastCommittedURL(), kNewIframeUrl);
}
}
// Test that the main frame navigation after the initial prerender navigation
// when the activation has already started doesn't cancel an ongoing
// prerendering.
// Testing steps:
// 1. prerender navigation starts/finishes
// 2. activation starts and suspends on CommitDeferringCondition
// 3. navigation in the prerendered page starts
// 4. navigation in the prerendered page finishes
// 5. activation resumes/finishes
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
MainFrameNavigationDuringActivation) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/empty.html?1");
const GURL kPrerenderingUrl2 = GetUrl("/empty.html?2");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start a prerender.
FrameTreeNodeId prerender_host_id = AddPrerender(kPrerenderingUrl);
RenderFrameHostImpl* prerendered_rfh =
GetPrerenderedMainFrameHost(prerender_host_id);
test::PrerenderHostObserver prerender_observer(*web_contents(),
prerender_host_id);
auto* prerender_ftn = prerendered_rfh->frame_tree_node();
EXPECT_FALSE(prerender_ftn->HasNavigation());
// Start an activation navigation for the prerender and pause it before it
// completes.
TestActivationManager activation_observer(shell()->web_contents(),
kPrerenderingUrl);
{
ASSERT_TRUE(ExecJs(web_contents()->GetPrimaryMainFrame(),
JsReplace("location = $1", kPrerenderingUrl)));
// Pause the activation before it's committed.
EXPECT_TRUE(activation_observer.WaitForBeforeChecks());
EXPECT_TRUE(activation_observer.GetNavigationHandle()
->IsCommitDeferringConditionDeferredForTesting());
EXPECT_EQ(web_contents()->GetLastCommittedURL(), kInitialUrl);
}
// Make a navigation in the prerendered page. This navigation should succeed.
TestNavigationManager navigation_observer(web_contents(), kPrerenderingUrl2);
NavigatePrerenderedPage(prerender_host_id, kPrerenderingUrl2);
ASSERT_TRUE(navigation_observer.WaitForNavigationFinished());
EXPECT_TRUE(navigation_observer.was_successful());
// Verify that all RenderFrameHostImpls are the prerendering state.
EXPECT_TRUE(prerender_helper()->VerifyPrerenderingState(kPrerenderingUrl));
// The activation isn't cancelled because there is no ongoing navigation.
activation_observer.ResumeActivation();
// Wait for the completion of the navigation. This should be the prerendered
// page activation.
activation_observer.WaitForNavigationFinished();
// The prerender host should have been consumed since the activation was
// completed.
EXPECT_FALSE(
web_contents_impl()->GetPrerenderHostRegistry()->FindNonReservedHostById(
prerender_host_id));
EXPECT_FALSE(
web_contents_impl()->GetPrerenderHostRegistry()->HasReservedHost());
EXPECT_TRUE(activation_observer.was_activated());
EXPECT_TRUE(activation_observer.was_successful());
EXPECT_EQ(shell()->web_contents()->GetLastCommittedURL(), kPrerenderingUrl2);
}
// Test that a main frame navigation after the initial prerender navigation
// doesn't cancel an ongoing prerendering. The main frame navigation runs
// concurrent with the activation.
// 1. prerender navigation starts/finishes
// 2. activation starts and suspends on CommitDeferringCondition
// 3. navigation in the prerendered page starts
// 4. activation resumes
// 5. navigation in the prerendered page finishes
// 6. activation finishes
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
MainFrameNavigationConcurrentWithActivation) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/empty.html?1");
const GURL kPrerenderingUrl2 = GetUrl("/empty.html?2");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start a prerender.
FrameTreeNodeId prerender_host_id = AddPrerender(kPrerenderingUrl);
RenderFrameHostImpl* prerendered_rfh =
GetPrerenderedMainFrameHost(prerender_host_id);
test::PrerenderHostObserver prerender_observer(*web_contents(),
prerender_host_id);
auto* prerender_ftn = prerendered_rfh->frame_tree_node();
EXPECT_FALSE(prerender_ftn->HasNavigation());
// Start an activation navigation for the prerender and pause it before it
// completes.
TestActivationManager activation_observer(shell()->web_contents(),
kPrerenderingUrl);
{
ASSERT_TRUE(ExecJs(web_contents()->GetPrimaryMainFrame(),
JsReplace("location = $1", kPrerenderingUrl)));
// Pause the activation before it's committed.
EXPECT_TRUE(activation_observer.WaitForBeforeChecks());
EXPECT_TRUE(activation_observer.GetNavigationHandle()
->IsCommitDeferringConditionDeferredForTesting());
EXPECT_EQ(web_contents()->GetLastCommittedURL(), kInitialUrl);
}
// Make a navigation in the prerendered page. This navigation should succeed.
TestNavigationManager navigation_observer(web_contents(), kPrerenderingUrl2);
NavigatePrerenderedPage(prerender_host_id, kPrerenderingUrl2);
// Resume an activation navigation before completing the navigation in the
// prerendered page. The activation isn't cancelled because
// PrerenderCommitDeferringCondition defers the activation until the ongoing
// main frame navigation is completed.
activation_observer.ResumeActivation();
// Wait for the completion of the navigation in the prerendered page.
ASSERT_TRUE(navigation_observer.WaitForNavigationFinished());
EXPECT_TRUE(navigation_observer.was_successful());
// Verify that all RenderFrameHostImpls are the prerendering state.
EXPECT_TRUE(prerender_helper()->VerifyPrerenderingState(kPrerenderingUrl));
// Wait for the completion of the navigation. This should be the prerendered
// page activation.
activation_observer.WaitForNavigationFinished();
// The prerender host should have been consumed since the activation was
// completed.
EXPECT_FALSE(
web_contents_impl()->GetPrerenderHostRegistry()->FindNonReservedHostById(
prerender_host_id));
EXPECT_FALSE(
web_contents_impl()->GetPrerenderHostRegistry()->HasReservedHost());
EXPECT_EQ(web_contents()->GetLastCommittedURL(), kPrerenderingUrl2);
EXPECT_TRUE(activation_observer.was_activated());
EXPECT_TRUE(activation_observer.was_successful());
EXPECT_EQ(shell()->web_contents()->GetLastCommittedURL(), kPrerenderingUrl2);
}
// Test that a main frame navigation after the initial prerender navigation and
// the activation is resumed cancels prerendering. This is the edge case that
// PrerenderCommitDeferringCondition posts a task to resume activation
// (https://source.chromium.org/chromium/chromium/src/+/main:content/browser/preloading/prerender/prerender_commit_deferring_condition.cc;l=105-106;drc=86ba45ef0be48fc81656da31dd4952857963485c)
// and a main frame navigation starts before activation is completed.
// 1. prerender navigation starts/finishes
// 2. activation starts and suspends on CommitDeferringCondition
// 3. navigation in the prerendered page starts
// 4. activation resumes
// 5. navigation in the prerendered page finishes
// 6. another navigation in the prerendered page starts but the server never
// respond to the navigation
// 7. activation is canceled
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
MainFrameNavigationAfterActivationIsResumed) {
embedded_test_server()->RegisterRequestHandler(base::BindLambdaForTesting(
[&](const net::test_server::HttpRequest& request)
-> std::unique_ptr<net::test_server::HttpResponse> {
if (request.relative_url != "/empty.html?3") {
return nullptr;
}
return std::make_unique<net::test_server::HungResponse>();
}));
ASSERT_TRUE(embedded_test_server()->Start());
const GURL kInitialUrl = embedded_test_server()->GetURL("/empty.html");
const GURL kPrerenderingUrl = embedded_test_server()->GetURL("/empty.html?1");
const GURL kPrerenderingUrl2 =
embedded_test_server()->GetURL("/empty.html?2");
// The server returns a HungResponse to the request to kPrerenderingUrl3,
// which doesn't actually respond until the server is destroyed.
const GURL kPrerenderingUrl3 =
embedded_test_server()->GetURL("/empty.html?3");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start a prerender.
FrameTreeNodeId prerender_host_id = AddPrerender(kPrerenderingUrl);
RenderFrameHostImpl* prerendered_rfh =
GetPrerenderedMainFrameHost(prerender_host_id);
test::PrerenderHostObserver prerender_observer(*web_contents(),
prerender_host_id);
auto* prerender_ftn = prerendered_rfh->frame_tree_node();
EXPECT_FALSE(prerender_ftn->HasNavigation());
TestActivationManager activation_observer(shell()->web_contents(),
kPrerenderingUrl);
// Set a callback that will be called after the last commit deferring
// condition is executed. The callback starts a main frame navigation in a
// prerendered page after activation is resumed.
activation_observer.SetCallbackCalledAfterActivationIsReady(base::BindOnce(
&PrerenderBrowserTest::NavigatePrerenderedPage, base::Unretained(this),
prerender_host_id, kPrerenderingUrl3));
// Start an activation.
{
ASSERT_TRUE(ExecJs(web_contents()->GetPrimaryMainFrame(),
JsReplace("location = $1", kPrerenderingUrl)));
// Pause the activation before it's committed.
EXPECT_TRUE(activation_observer.WaitForBeforeChecks());
EXPECT_TRUE(activation_observer.GetNavigationHandle()
->IsCommitDeferringConditionDeferredForTesting());
EXPECT_EQ(web_contents()->GetLastCommittedURL(), kInitialUrl);
}
// Start a main frame navigation in a prerendered page. It defers the
// activation commit.
TestNavigationManager navigation_observer(web_contents(), kPrerenderingUrl2);
NavigatePrerenderedPage(prerender_host_id, kPrerenderingUrl2);
// Verify that all RenderFrameHostImpls are the prerendering state.
EXPECT_TRUE(prerender_helper()->VerifyPrerenderingState(kPrerenderingUrl));
// Resume an activation navigation before completing the navigation in the
// prerendered page. The activation isn't cancelled because
// PrerenderCommitDeferringCondition defers the activation until the ongoing
// main frame navigation is completed.
activation_observer.ResumeActivation();
// Wait for the completion of the navigation in the prerendered page.
ASSERT_TRUE(navigation_observer.WaitForNavigationFinished());
EXPECT_TRUE(navigation_observer.was_successful());
// Wait for the completion of the navigation. This shouldn't be the
// prerendered page activation.
activation_observer.WaitForNavigationFinished();
// The prerender host should have been abandoned.
EXPECT_FALSE(
web_contents_impl()->GetPrerenderHostRegistry()->FindNonReservedHostById(
prerender_host_id));
EXPECT_FALSE(
web_contents_impl()->GetPrerenderHostRegistry()->HasReservedHost());
EXPECT_FALSE(activation_observer.was_activated());
EXPECT_TRUE(activation_observer.was_successful());
EXPECT_EQ(shell()->web_contents()->GetLastCommittedURL(), kPrerenderingUrl);
ExpectFinalStatusForSpeculationRule(
PrerenderFinalStatus::kActivatedDuringMainFrameNavigation);
}
// Test the following scenario: a prerender initial navigation is pending and an
// activation navigation is deferred due to that, and then if prerender is
// canceled, the activation navigation will fall back to a normal navigation
// with no crash and hang.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
CancelPrerenderWhenDeferringActivationNavigation) {
const char prerendering_url_c[] = "/empty.html?prerender";
net::test_server::ControllableHttpResponse response_for_initial_navigation(
embedded_test_server(), prerendering_url_c);
net::test_server::ControllableHttpResponse response_for_activation_navigation(
embedded_test_server(), prerendering_url_c);
ASSERT_TRUE(embedded_test_server()->Start());
const GURL initial_url = embedded_test_server()->GetURL("/empty.html");
const GURL prerendering_url =
embedded_test_server()->GetURL(prerendering_url_c);
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
// Start prerendering.
content::test::PrerenderHostCreationWaiter host_creation_waiter;
AddPrerenderAsync(prerendering_url);
FrameTreeNodeId host_id = host_creation_waiter.Wait();
response_for_initial_navigation.WaitForRequest();
// Not sending the response so that the prerender initial navigation will be
// pending.
test::PrerenderHostObserver prerender_observer(*web_contents(), host_id);
TestActivationManager activation_observer(web_contents(), prerendering_url);
// Start prerender activation. This will be deferred because initial
// navigation is not finished.
test::PrerenderTestHelper::NavigatePrimaryPageAsync(*web_contents_impl(),
prerendering_url);
NavigationRequest* request =
web_contents_impl()->GetPrimaryFrameTree().root()->navigation_request();
ASSERT_TRUE(activation_observer.WaitForBeforeChecks());
activation_observer.ResumeActivation();
ASSERT_TRUE(request->IsCommitDeferringConditionDeferredForTesting());
ASSERT_EQ(request->state(), NavigationRequest::NOT_STARTED);
// Cancel prerendering.
CancelPrerenderedPage(host_id);
prerender_observer.WaitForDestroyed();
// Activation navigation will fall back to normal navigation.
response_for_activation_navigation.WaitForRequest();
response_for_activation_navigation.Send(net::HTTP_OK, "");
response_for_activation_navigation.Done();
activation_observer.WaitForNavigationFinished();
EXPECT_EQ(shell()->web_contents()->GetLastCommittedURL(), prerendering_url);
EXPECT_FALSE(activation_observer.was_activated());
}
// Test that WebContentsObserver::DidFinishLoad is not invoked when the page
// gets loaded while prerendering but it is deferred and invoked on prerender
// activation.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
DidFinishLoadInvokedAfterActivation) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/simple_page.html");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Initialize a MockWebContentsObserver and ensure that DidFinishLoad is not
// invoked while prerendering.
testing::NiceMock<MockWebContentsObserver> observer(shell()->web_contents());
EXPECT_CALL(observer, DidFinishLoad(testing::_, testing::_)).Times(0);
// Start a prerender.
FrameTreeNodeId prerender_host_id = AddPrerender(kPrerenderingUrl);
RenderFrameHostImpl* prerender_frame_host =
GetPrerenderedMainFrameHost(prerender_host_id);
EXPECT_EQ(0u, prerender_frame_host->child_count());
// Verify and clear all expectations on the mock observer before setting new
// ones.
testing::Mock::VerifyAndClearExpectations(&observer);
testing::InSequence s;
// Activate the prerendered page. This should result in invoking DidFinishLoad
// once for root RenderFrameHost `prerender_frame_host`.
{
// Verify that DidFinishNavigation is invoked before DidFinishLoad on
// activation.
EXPECT_CALL(observer, DidFinishNavigation(testing::_));
EXPECT_CALL(observer,
DidFinishLoad(prerender_frame_host, kPrerenderingUrl));
}
NavigatePrimaryPage(kPrerenderingUrl);
EXPECT_EQ(web_contents()->GetLastCommittedURL(), kPrerenderingUrl);
}
// Test that WebContentsObserver::DidFinishLoad is not invoked when the page
// gets loaded while prerendering but it is deferred and invoked on prerender
// activation for both main and sub-frames.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
DidFinishLoadInvokedAfterActivationWithSubframes) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/page_with_iframe.html");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Initialize a MockWebContentsObserver and ensure that DidFinishLoad is not
// invoked while prerendering.
testing::NiceMock<MockWebContentsObserver> observer(shell()->web_contents());
testing::InSequence s;
EXPECT_CALL(observer, DidFinishLoad(testing::_, testing::_)).Times(0);
// Start a prerender.
FrameTreeNodeId prerender_host_id = AddPrerender(kPrerenderingUrl);
RenderFrameHostImpl* prerender_main_frame_host =
GetPrerenderedMainFrameHost(prerender_host_id);
RenderFrameHost* child_frame = ChildFrameAt(prerender_main_frame_host, 0);
EXPECT_EQ(1u, prerender_main_frame_host->child_count());
// Verify and clear all expectations on the mock observer before setting new
// ones.
testing::Mock::VerifyAndClearExpectations(&observer);
// Activate the prerendered page. This should result in invoking DidFinishLoad
// twice once for root and once for child RenderFrameHosts.
{
// Verify that DidFinishNavigation is invoked before DidFinishLoad.
EXPECT_CALL(observer, DidFinishNavigation(testing::_));
EXPECT_CALL(observer,
DidFinishLoad(prerender_main_frame_host, kPrerenderingUrl));
EXPECT_CALL(observer,
DidFinishLoad(child_frame, child_frame->GetLastCommittedURL()));
}
NavigatePrimaryPage(kPrerenderingUrl);
EXPECT_EQ(web_contents()->GetLastCommittedURL(), kPrerenderingUrl);
}
// Test that WebContentsObserver::DOMContentLoaded is not invoked while
// prerendering but it is deferred and invoked on prerender activation for both
// main and sub-frames.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
DOMContentLoadedInvokedAfterActivationWithSubframes) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/page_with_iframe.html");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Initialize a MockWebContentsObserver and ensure that DOMContentLoaded is
// not invoked while prerendering.
testing::NiceMock<MockWebContentsObserver> observer(shell()->web_contents());
EXPECT_CALL(observer, DOMContentLoaded(testing::_)).Times(0);
// Start a prerender.
FrameTreeNodeId prerender_host_id = AddPrerender(kPrerenderingUrl);
RenderFrameHostImpl* prerender_main_frame_host =
GetPrerenderedMainFrameHost(prerender_host_id);
RenderFrameHost* child_frame = ChildFrameAt(prerender_main_frame_host, 0);
EXPECT_EQ(prerender_main_frame_host->child_count(), 1u);
ASSERT_TRUE(prerender_host_id);
// Verify and clear all expectations on the mock observer before setting new
// ones.
testing::Mock::VerifyAndClearExpectations(&observer);
testing::InSequence s;
// Activate the prerendered page. This should result in invoking
// DOMContentLoaded twice once for root and once for child RenderFrameHost.
{
// Verify that DidFinishNavigation is invoked before DOMContentLoaded on
// activation.
EXPECT_CALL(observer, DidFinishNavigation(testing::_));
EXPECT_CALL(observer, DOMContentLoaded(prerender_main_frame_host)).Times(1);
EXPECT_CALL(observer, DOMContentLoaded(child_frame)).Times(1);
}
NavigatePrimaryPage(kPrerenderingUrl);
EXPECT_EQ(web_contents()->GetLastCommittedURL(), kPrerenderingUrl);
}
// Test that WebContentsObserver::DocumentOnLoadCompletedInPrimaryMainFrame is
// not invoked when the page gets loaded while prerendering but it is deferred
// and invoked on prerender activation.
IN_PROC_BROWSER_TEST_F(
PrerenderBrowserTest,
DocumentOnLoadCompletedInPrimaryMainFrameInvokedAfterActivation) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/page_with_iframe.html");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Initialize a MockWebContentsObserver and ensure that
// DocumentOnLoadCompletedInPrimaryMainFrame is not invoked while
// prerendering.
testing::NiceMock<MockWebContentsObserver> observer(shell()->web_contents());
EXPECT_CALL(observer, DocumentOnLoadCompletedInPrimaryMainFrame()).Times(0);
// Start a prerender.
FrameTreeNodeId prerender_host_id = AddPrerender(kPrerenderingUrl);
RenderFrameHostImpl* prerender_frame_host =
GetPrerenderedMainFrameHost(prerender_host_id);
EXPECT_EQ(prerender_frame_host->child_count(), 1u);
ASSERT_TRUE(prerender_host_id);
// Verify and clear all expectations on the mock observer before setting new
// ones.
testing::Mock::VerifyAndClearExpectations(&observer);
testing::InSequence s;
// Activate the prerendered page. This should result in invoking
// DocumentOnLoadCompletedInPrimaryMainFrame only for main RenderFrameHost.
{
// Verify that DidFinishNavigation is invoked before
// DocumentOnLoadCompletedInPrimaryMainFrame on activation.
EXPECT_CALL(observer, DidFinishNavigation(testing::_));
EXPECT_CALL(observer, DocumentOnLoadCompletedInPrimaryMainFrame()).Times(1);
}
NavigatePrimaryPage(kPrerenderingUrl);
EXPECT_EQ(web_contents()->GetLastCommittedURL(), kPrerenderingUrl);
}
// Test that WebContentsObserver::PrimaryMainDocumentElementAvailable is not
// invoked when the page gets loaded while prerendering but it is deferred and
// invoked on prerender activation.
IN_PROC_BROWSER_TEST_F(
PrerenderBrowserTest,
PrimaryMainDocumentElementAvailableInvokedAfterActivation) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/page_with_iframe.html");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Initialize a MockWebContentsObserver and ensure that
// PrimaryMainDocumentElementAvailable is not invoked while prerendering.
testing::NiceMock<MockWebContentsObserver> observer(shell()->web_contents());
EXPECT_CALL(observer, PrimaryMainDocumentElementAvailable()).Times(0);
// AddPrerender() below waits until WebContentsObserver::DidStopLoading() is
// called and RenderFrameHostImpl::PrimaryMainDocumentElementAvailable() call
// is expected before it returns.
FrameTreeNodeId prerender_host_id = AddPrerender(kPrerenderingUrl);
RenderFrameHostImpl* prerender_frame_host =
GetPrerenderedMainFrameHost(prerender_host_id);
EXPECT_EQ(prerender_frame_host->child_count(), 1u);
ASSERT_TRUE(prerender_host_id);
// Verify and clear all expectations on the mock observer before setting new
// ones.
testing::Mock::VerifyAndClearExpectations(&observer);
testing::InSequence s;
// Activate the prerendered page. This should result in invoking
// PrimaryMainDocumentElementAvailable only for main RenderFrameHost.
// Verify that DidFinishNavigation is invoked before
// PrimaryMainDocumentElementAvailable on activation.
EXPECT_CALL(observer, DidFinishNavigation(testing::_));
EXPECT_CALL(observer, PrimaryMainDocumentElementAvailable()).Times(1);
NavigatePrimaryPage(kPrerenderingUrl);
EXPECT_EQ(web_contents()->GetLastCommittedURL(), kPrerenderingUrl);
}
// Test that WebContentsObserver::LoadProgressChanged is not invoked when the
// page gets loaded while prerendering but is invoked on prerender activation.
// Check that LoadProgressChanged is only called once for
// blink::kFinalLoadProgress if the prerender page completes loading on
// activation.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
LoadProgressChangedInvokedOnActivation) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/simple_page.html");
web_contents_impl()->set_minimum_delay_between_loading_updates_for_testing(
base::Milliseconds(0));
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Initialize a MockWebContentsObserver and ensure that LoadProgressChanged is
// not invoked while prerendering.
testing::NiceMock<MockWebContentsObserver> observer(shell()->web_contents());
testing::InSequence s;
EXPECT_CALL(observer, LoadProgressChanged(testing::_)).Times(0);
// Start a prerender.
FrameTreeNodeId prerender_host_id = AddPrerender(kPrerenderingUrl);
ASSERT_TRUE(prerender_host_id);
RenderFrameHostImpl* prerender_frame_host =
GetPrerenderedMainFrameHost(prerender_host_id);
// Verify and clear all expectations on the mock observer before setting new
// ones.
testing::Mock::VerifyAndClearExpectations(&observer);
// Activate the prerendered page. This should result in invoking
// LoadProgressChanged for the following cases:
{
// 1) During DidStartLoading LoadProgressChanged is invoked with
// kInitialLoadProgress value.
EXPECT_CALL(observer, LoadProgressChanged(blink::kInitialLoadProgress));
// Verify that DidFinishNavigation is invoked before final load progress
// notification.
EXPECT_CALL(observer, DidFinishNavigation(testing::_));
// 2) During DidStopLoading LoadProgressChanged is invoked with
// kFinalLoadProgress.
EXPECT_CALL(observer, LoadProgressChanged(blink::kFinalLoadProgress))
.Times(1);
}
// Set the prerender load progress value to blink::kFinalLoadProgress, this
// should result in invoking LoadProgressChanged(blink::kFinalLoadProgress)
// only once on activation during call to DidStopLoading.
prerender_frame_host->GetPage().set_load_progress(blink::kFinalLoadProgress);
NavigatePrimaryPage(kPrerenderingUrl);
EXPECT_EQ(web_contents()->GetLastCommittedURL(), kPrerenderingUrl);
}
// Test that WebContentsObserver::DidStopLoading is not invoked when the page
// gets loaded while prerendering but is invoked on prerender activation.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
DidStopLoadingInvokedOnActivation) {
const GURL initial_url = GetUrl("/empty.html");
const GURL prerendering_url = GetUrl("/simple_page.html");
web_contents_impl()->set_minimum_delay_between_loading_updates_for_testing(
base::Milliseconds(0));
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
// Initialize a MockWebContentsObserver and ensure that DidStopLoading is
// not invoked while prerendering.
testing::NiceMock<MockWebContentsObserver> observer(shell()->web_contents());
EXPECT_CALL(observer, DidStopLoading()).Times(0);
// Start a prerender.
FrameTreeNodeId prerender_host_id = AddPrerender(prerendering_url);
ASSERT_TRUE(prerender_host_id);
// Verify and clear all expectations on the mock observer before setting new
// ones.
testing::Mock::VerifyAndClearExpectations(&observer);
// Activate the prerendered page. This should result in invoking
// DidStopLoading.
EXPECT_CALL(observer, DidStopLoading()).Times(1);
test::PrerenderHostObserver host_observer(*web_contents(), prerender_host_id);
NavigatePrimaryPage(prerendering_url);
EXPECT_TRUE(host_observer.was_activated());
EXPECT_EQ(web_contents()->GetLastCommittedURL(), prerendering_url);
}
// Test that WebContentsObserver::DidStopLoading is invoked when the page gets
// loaded after activation.
//
// This is a regression test for https://crbug.com/40256454. Previously,
// DidStopLoading was invoked regardless of the current loading state on
// activation, which was obviously wrong. This test makes sure that
// DidStopLoading is invoked after the page actually gets loaded.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
DidStopLoadingInvokedAfterActivation) {
// Use ControllableHttpResponse to control the timing to serve for delaying
// page loading.
net::test_server::ControllableHttpResponse response(embedded_test_server(),
"/simple_page.html");
ASSERT_TRUE(embedded_test_server()->Start());
const GURL initial_url = embedded_test_server()->GetURL("/empty.html");
const GURL prerendering_url =
embedded_test_server()->GetURL("/simple_page.html");
web_contents_impl()->set_minimum_delay_between_loading_updates_for_testing(
base::Milliseconds(0));
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
// Initialize a MockWebContentsObserver and ensure that DidStopLoading is
// not invoked while prerendering.
testing::NiceMock<MockWebContentsObserver> observer(shell()->web_contents());
EXPECT_CALL(observer, DidStopLoading()).Times(0);
// Start a prerender.
AddPrerenderAsync(prerendering_url);
// Send only a header. This prevents the prerendered page from being fully
// loaded.
const char kHttpResponseHeader[] =
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/html; charset=utf-8\r\n"
"\r\n";
response.WaitForRequest();
response.Send(kHttpResponseHeader);
// Activate the prerendered page. The response for the prerendered page is not
// finalized yet, so this should not invoke DidStopLoading.
EXPECT_CALL(observer, DidStopLoading()).Times(0);
test::PrerenderHostObserver host_observer(*web_contents(), prerendering_url);
prerender_helper()->NavigatePrimaryPageAsync(prerendering_url);
host_observer.WaitForActivation();
EXPECT_TRUE(host_observer.was_activated());
EXPECT_EQ(web_contents()->GetLastCommittedURL(), prerendering_url);
// Verify and clear all expectations on the mock observer before setting new
// ones. The activated page is not loaded yet, so DidStopLoading should not be
// invoked yet.
testing::Mock::VerifyAndClearExpectations(&observer);
// Finalize the response for the activated page. This should result in
// invoking DidStopLoading.
base::RunLoop run_loop;
EXPECT_CALL(observer, DidStopLoading()).WillOnce(testing::Invoke([&]() {
run_loop.Quit();
}));
response.Send("0\r\n");
response.Send("\r\n");
response.Done();
run_loop.Run();
}
// Test the dispatch order of various load events on prerender activation.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, OrderingOfDifferentLoadEvents) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/simple_page.html");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Initialize a MockWebContentsObserver to check order of different load
// events.
testing::NiceMock<MockWebContentsObserver> observer(shell()->web_contents());
// Start a prerender.
FrameTreeNodeId prerender_host_id = AddPrerender(kPrerenderingUrl);
ASSERT_TRUE(prerender_host_id);
// Verify and clear all expectations on the mock observer before setting new
// ones.
testing::Mock::VerifyAndClearExpectations(&observer);
testing::InSequence s;
// Activate the prerendered page. This should result in invoking various
// WebContentsObserver events in the following order.
{
EXPECT_CALL(observer, DidStartLoading()).Times(1);
// Verify that DidFinishNavigation is invoked before any finish load events
// are dispatched.
EXPECT_CALL(observer, DidFinishNavigation(testing::_)).Times(1);
EXPECT_CALL(observer, DOMContentLoaded(testing::_)).Times(1);
EXPECT_CALL(observer, DocumentOnLoadCompletedInPrimaryMainFrame()).Times(1);
EXPECT_CALL(observer, DidFinishLoad(testing::_, testing::_)).Times(1);
EXPECT_CALL(observer, DidStopLoading()).Times(1);
}
NavigatePrimaryPage(kPrerenderingUrl);
EXPECT_EQ(web_contents()->GetLastCommittedURL(), kPrerenderingUrl);
}
// Tests that cross-origin subframe navigations in a prerendered page are
// deferred even if they start after the a navigation starts that will
// attempt to activate the prerendered page.
//
// Regression test for https://crbug.com/1190262.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
CrossOriginSubframeNavigationDuringActivation) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/page_with_blank_iframe.html");
const GURL kCrossOriginUrl = GetCrossSiteUrl("/simple_page.html");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
ASSERT_EQ(shell()->web_contents()->GetLastCommittedURL(), kInitialUrl);
// Start prerendering `kPrerenderingUrl`.
FrameTreeNodeId prerender_host_id;
RenderFrameHost* prerender_main_frame = nullptr;
{
prerender_host_id = AddPrerender(kPrerenderingUrl);
prerender_main_frame = GetPrerenderedMainFrameHost(prerender_host_id);
RenderFrameHost* child_frame = ChildFrameAt(prerender_main_frame, 0);
ASSERT_TRUE(child_frame);
}
// Start an activation navigation for the prerender. Pause activation before
// it completes.
test::PrerenderHostObserver prerender_observer(*web_contents(),
kPrerenderingUrl);
TestActivationManager activation_observer(shell()->web_contents(),
kPrerenderingUrl);
{
ASSERT_TRUE(ExecJs(web_contents()->GetPrimaryMainFrame(),
JsReplace("location = $1", kPrerenderingUrl)));
EXPECT_TRUE(activation_observer.WaitForBeforeChecks());
EXPECT_TRUE(activation_observer.GetNavigationHandle()
->IsCommitDeferringConditionDeferredForTesting());
EXPECT_EQ(web_contents()->GetLastCommittedURL(), kInitialUrl);
}
// Start a cross-origin subframe navigation in the prerendered page. It
// should be deferred.
std::string kNavigateScript = R"(
document.querySelector('iframe').src = $1;
)";
TestNavigationManager iframe_nav_observer(shell()->web_contents(),
kCrossOriginUrl);
ASSERT_TRUE(ExecJs(prerender_main_frame,
JsReplace(kNavigateScript, kCrossOriginUrl)));
ASSERT_TRUE(iframe_nav_observer.WaitForFirstYieldAfterDidStartNavigation());
// The PrerenderSubframeNavigationThrottle should defer it until activation.
auto* child_ftn =
FrameTreeNode::GloballyFindByID(prerender_host_id)->child_at(0);
auto* child_navigation = child_ftn->navigation_request();
ASSERT_NE(child_navigation, nullptr);
EXPECT_TRUE(child_navigation->IsDeferredForTesting());
// Allow the activation navigation to complete.
activation_observer.WaitForNavigationFinished();
EXPECT_TRUE(activation_observer.was_activated());
// The iframe navigation should finish.
ASSERT_TRUE(iframe_nav_observer.WaitForNavigationFinished());
EXPECT_EQ(ChildFrameAt(prerender_main_frame, 0)->GetLastCommittedURL(),
kCrossOriginUrl);
}
// Tests WebContents::OpenURL to a frame in a prerendered page when a
// navigation that will attempt to activate the page has already started. The
// subframe navigation should succeed.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
OpenURLInSubframeDuringActivation) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/page_with_blank_iframe.html");
const GURL kNewIframeUrl = GetUrl("/simple_page.html");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
ASSERT_EQ(shell()->web_contents()->GetLastCommittedURL(), kInitialUrl);
// Start prerendering `kPrerenderingUrl`.
FrameTreeNodeId prerender_host_id;
RenderFrameHost* child_frame = nullptr;
{
prerender_host_id = AddPrerender(kPrerenderingUrl);
auto* prerendered_render_frame_host =
GetPrerenderedMainFrameHost(prerender_host_id);
child_frame = ChildFrameAt(prerendered_render_frame_host, 0);
ASSERT_TRUE(child_frame);
}
// Start an activation navigation for the prerender and pause before it
// completes.
test::PrerenderHostObserver prerender_observer(*web_contents(),
kPrerenderingUrl);
TestActivationManager activation_observer(shell()->web_contents(),
kPrerenderingUrl);
{
ASSERT_TRUE(ExecJs(web_contents()->GetPrimaryMainFrame(),
JsReplace("location = $1", kPrerenderingUrl)));
EXPECT_TRUE(activation_observer.WaitForBeforeChecks());
EXPECT_TRUE(activation_observer.GetNavigationHandle()
->IsCommitDeferringConditionDeferredForTesting());
EXPECT_EQ(web_contents()->GetLastCommittedURL(), kInitialUrl);
}
// Use the OpenURL API to navigate the iframe in the prerendering frame tree.
// This navigation should succeed.
{
TestNavigationManager iframe_observer(shell()->web_contents(),
kNewIframeUrl);
shell()->web_contents()->OpenURL(
OpenURLParams(kNewIframeUrl, Referrer(),
child_frame->GetFrameTreeNodeId(),
WindowOpenDisposition::CURRENT_TAB,
ui::PAGE_TRANSITION_AUTO_SUBFRAME,
/*is_renderer_initiated=*/false),
/*navigation_handle_callback=*/{});
ASSERT_TRUE(iframe_observer.WaitForNavigationFinished());
EXPECT_EQ(child_frame->GetLastCommittedURL(), kNewIframeUrl);
}
// Allow the activation navigation to complete.
activation_observer.WaitForNavigationFinished();
EXPECT_TRUE(activation_observer.was_activated());
}
class InvisiblePageLazyLoadingImageBrowserTest
: public PrerenderBrowserTest,
public testing::WithParamInterface<
blink::features::EnableLazyLoadImageForInvisiblePageType> {
public:
static std::string GetFieldTrialParamName(
blink::features::EnableLazyLoadImageForInvisiblePageType
target_page_type) {
switch (target_page_type) {
case blink::features::EnableLazyLoadImageForInvisiblePageType::
kAllInvisiblePage:
return "all_invisible_page";
case blink::features::EnableLazyLoadImageForInvisiblePageType::
kPrerenderPage:
return "prerender_page";
}
}
InvisiblePageLazyLoadingImageBrowserTest() {
feature_list_.InitWithFeaturesAndParameters(
{{blink::features::kEnableLazyLoadImageForInvisiblePage,
{
{"enabled_page_type", GetFieldTrialParamName(GetParam())},
}}},
{});
}
private:
base::test::ScopedFeatureList feature_list_;
};
INSTANTIATE_TEST_SUITE_P(
All,
InvisiblePageLazyLoadingImageBrowserTest,
testing::Values(blink::features::EnableLazyLoadImageForInvisiblePageType::
kAllInvisiblePage,
blink::features::EnableLazyLoadImageForInvisiblePageType::
kPrerenderPage),
[](const testing::TestParamInfo<
blink::features::EnableLazyLoadImageForInvisiblePageType>& info) {
return InvisiblePageLazyLoadingImageBrowserTest::GetFieldTrialParamName(
info.param);
});
// Tests that loading=lazy can prevent image load in a prerendered page.
// TODO(https://crbug.com/381110833): The image, positioned in the top-left
// corner of the page, should be visible in the initial viewport after the page
// gets activated. Ideally it should be loaded during prerendering, and we need
// to figure out how to make that happen.
IN_PROC_BROWSER_TEST_P(InvisiblePageLazyLoadingImageBrowserTest, LazyLoading) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/prerender/image_loading_lazy.html");
const GURL kImageUrl = GetUrl("/blank.jpg");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
ASSERT_EQ(shell()->web_contents()->GetLastCommittedURL(), kInitialUrl);
// Start prerendering `kPrerenderingUrl`.
ASSERT_EQ(GetRequestCount(kPrerenderingUrl), 0);
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
RenderFrameHost* prerender_frame_host = GetPrerenderedMainFrameHost(host_id);
EXPECT_EQ(GetRequestCount(kPrerenderingUrl), 1);
// A request for the image in the prerendered page should be prevented by
// loading=lazy.
EXPECT_EQ(GetRequestCount(kImageUrl), 0);
EXPECT_TRUE(ExecJs(prerender_frame_host, "runLoop()"));
EXPECT_EQ(EvalJs(prerender_frame_host, "image_loaded"), false);
test::PrerenderHostObserver host_observer(*web_contents(), kPrerenderingUrl);
NavigatePrimaryPage(kPrerenderingUrl);
EXPECT_TRUE(host_observer.was_activated());
EXPECT_EQ(web_contents()->GetLastCommittedURL(), kPrerenderingUrl);
EXPECT_TRUE(ExecJs(prerender_frame_host, "promise_with_resolvers.promise"));
EXPECT_EQ(EvalJs(prerender_frame_host, "image_loaded"), true);
}
class DisabledInvisiblePageLazyLoadingImageBrowserTest
: public PrerenderBrowserTest {
public:
DisabledInvisiblePageLazyLoadingImageBrowserTest() {
feature_list_.InitAndDisableFeature(
blink::features::kEnableLazyLoadImageForInvisiblePage);
}
private:
base::test::ScopedFeatureList feature_list_;
};
// Tests that loading=lazy doesn't prevent image load in a prerendered page.
// This test is tested under the condition that
// blink::features::kEnableLazyLoadImageForInvisiblePage is disabled.
IN_PROC_BROWSER_TEST_F(DisabledInvisiblePageLazyLoadingImageBrowserTest,
LazyLoading) {
ASSERT_FALSE(base::FeatureList::IsEnabled(
blink::features::kEnableLazyLoadImageForInvisiblePage));
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/prerender/image_loading_lazy.html");
const GURL kImageUrl = GetUrl("/blank.jpg");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
ASSERT_EQ(shell()->web_contents()->GetLastCommittedURL(), kInitialUrl);
// Start prerendering `kPrerenderingUrl`.
ASSERT_EQ(GetRequestCount(kPrerenderingUrl), 0);
AddPrerender(kPrerenderingUrl);
EXPECT_EQ(GetRequestCount(kPrerenderingUrl), 1);
// A request for the image in the prerendered page shouldn't be prevented by
// loading=lazy.
EXPECT_EQ(GetRequestCount(kImageUrl), 1);
}
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
SessionStorageAfterBackNavigation_NoProcessReuse) {
// When BackForwardCache feature is enabled, this test doesn't work, because
// this test is checking the behavior of a new renderer process which is
// created for a back forward navigation from a prerendered page.
DisableBackForwardCacheForTesting(shell()->web_contents(),
BackForwardCache::TEST_REQUIRES_NO_CACHING);
const GURL kInitialUrl = GetUrl("/prerender/session_storage.html");
const GURL kPrerenderingUrl =
GetUrl("/prerender/session_storage.html?prerendering=");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
std::unique_ptr<RenderProcessHostWatcher> process_host_watcher =
std::make_unique<RenderProcessHostWatcher>(
current_frame_host()->GetProcess(),
RenderProcessHostWatcher::WATCH_FOR_HOST_DESTRUCTION);
AddPrerender(kPrerenderingUrl);
NavigatePrimaryPage(kPrerenderingUrl);
EXPECT_EQ("initial", EvalJs(current_frame_host(),
"window.sessionKeysInPrerenderingchange")
.ExtractString());
EXPECT_EQ(
"activated, initial",
EvalJs(current_frame_host(), "getSessionStorageKeys()").ExtractString());
// Speculative fix for the test flakiness (crbug.com/1216038), which may be
// caused by the delayed async IPC of Session Storage (StorageArea.Put()).
EXPECT_TRUE(ExecJs(shell()->web_contents(),
"new Promise(resolve => requestIdleCallback(resolve));"));
// Make sure that the initial renderer process is destroyed. So that the
// initial renderer process will not be reused after the back forward
// navigation below.
process_host_watcher->Wait();
// Navigate back to the initial page.
TestNavigationObserver observer(shell()->web_contents());
shell()->GoBackOrForward(-1);
observer.Wait();
EXPECT_EQ(shell()->web_contents()->GetLastCommittedURL(), kInitialUrl);
EXPECT_EQ(
"activated, initial",
EvalJs(current_frame_host(), "getSessionStorageKeys()").ExtractString());
}
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
SessionStorageAfterBackNavigation_KeepInitialProcess) {
const GURL kInitialUrl = GetUrl("/prerender/session_storage.html");
const GURL kPrerenderingUrl =
GetUrl("/prerender/session_storage.html?prerendering=");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
RenderProcessHostImpl* initial_process_host =
static_cast<RenderProcessHostImpl*>(current_frame_host()->GetProcess());
// Increment the worker ref count of the renderer process to keep it alive
// so it is reused on the back navigation below. The test checks that the
// session storage state changed in the activated page is correctly propagated
// after a back navigation that uses an existing renderer process.
initial_process_host->IncrementWorkerRefCount();
AddPrerender(kPrerenderingUrl);
NavigatePrimaryPage(kPrerenderingUrl);
EXPECT_EQ("initial", EvalJs(current_frame_host(),
"window.sessionKeysInPrerenderingchange")
.ExtractString());
EXPECT_EQ(
"activated, initial",
EvalJs(current_frame_host(), "getSessionStorageKeys()").ExtractString());
// Speculative fix for the test flakiness (crbug.com/1216038), which may be
// caused by the delayed async IPC of Session Storage (StorageArea.Put()).
EXPECT_TRUE(ExecJs(shell()->web_contents(),
"new Promise(resolve => requestIdleCallback(resolve));"));
// Navigate back to the initial page.
TestNavigationObserver observer(shell()->web_contents());
shell()->GoBackOrForward(-1);
observer.Wait();
EXPECT_EQ(shell()->web_contents()->GetLastCommittedURL(), kInitialUrl);
EXPECT_EQ(
"activated, initial",
EvalJs(current_frame_host(), "getSessionStorageKeys()").ExtractString());
}
// Tests that prerender whose target_hint is "_blank" is using the same session
// storage across prerender navigations, and the initiator doesn't share the
// same storage.
IN_PROC_BROWSER_TEST_F(PrerenderTargetHintEnabledBrowserTest,
SessionStorage_TargetBlank_WithTargetHintBlank) {
const GURL kInitialUrl = GetUrl("/prerender/session_storage.html");
const GURL kPrerenderingUrl =
GetUrl("/prerender/session_storage.html?prerendering=");
// Navigate to an initial page which has a link to `kPrerenderingUrl`.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start prerendering `kPrerenderingUrl`.
FrameTreeNodeId host_id = prerender_helper()->AddPrerender(
kPrerenderingUrl, /*eagerness=*/std::nullopt, "_blank");
auto* prerender_web_contents =
static_cast<WebContentsImpl*>(WebContents::FromFrameTreeNodeId(host_id));
ExpectWebContentsIsForNewTabPrerendering(*prerender_web_contents);
auto* initiator_web_contents = web_contents_impl();
ASSERT_NE(prerender_web_contents, initiator_web_contents);
std::string prerender_session_storage_id_before_activation =
FrameTreeNode::GloballyFindByID(host_id)
->frame_tree()
.controller()
.GetSessionStorageNamespace(prerender_web_contents->GetSiteInstance()
->GetStoragePartitionConfig())
->id();
EXPECT_EQ(
"prerendering",
EvalJs(content::test::PrerenderTestHelper::GetPrerenderedMainFrameHost(
*prerender_web_contents, host_id),
"getSessionStorageKeys()")
.ExtractString());
// Click the link annotated with "target=_blank". This should activate the
// prerendered page.
TestNavigationObserver activation_observer(kPrerenderingUrl);
activation_observer.WatchExistingWebContents();
test::PrerenderHostObserver prerender_observer(*prerender_web_contents,
host_id);
const std::string kLinkClickScript = R"(
clickSameSiteNewWindowLink();
)";
EXPECT_TRUE(ExecJs(web_contents(), kLinkClickScript));
activation_observer.WaitForNavigationFinished();
EXPECT_EQ(prerender_web_contents->GetLastCommittedURL(), kPrerenderingUrl);
EXPECT_EQ(activation_observer.last_navigation_url(), kPrerenderingUrl);
EXPECT_TRUE(prerender_observer.was_activated());
EXPECT_FALSE(HasHostForUrl(kPrerenderingUrl));
// The initiator's session storage is expected to be different from the
// prerender's.
EXPECT_EQ("initial", EvalJs(initiator_web_contents->GetPrimaryMainFrame(),
"getSessionStorageKeys()")
.ExtractString());
EXPECT_EQ("activated", EvalJs(prerender_web_contents->GetPrimaryMainFrame(),
"getSessionStorageKeys()")
.ExtractString());
// The prerender session storage is expected to be the same across prerender
// activation.
EXPECT_EQ(
prerender_session_storage_id_before_activation,
prerender_web_contents->GetPrimaryFrameTree()
.controller()
.GetSessionStorageNamespace(prerender_web_contents->GetSiteInstance()
->GetStoragePartitionConfig())
->id());
EXPECT_NE(
prerender_session_storage_id_before_activation,
initiator_web_contents->GetPrimaryFrameTree()
.controller()
.GetSessionStorageNamespace(prerender_web_contents->GetSiteInstance()
->GetStoragePartitionConfig())
->id());
// The navigation occurred in a new WebContents, so the original WebContents
// should still be showing the initial trigger page.
EXPECT_EQ(web_contents()->GetLastCommittedURL(), kInitialUrl);
}
// Test if the host is abandoned when the renderer page crashes.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, AbandonIfRendererProcessCrashes) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/empty.html?prerender");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start a prerender.
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
// Crash the relevant renderer.
{
test::PrerenderHostObserver host_observer(*web_contents_impl(), host_id);
RenderProcessHost* process =
GetPrerenderedMainFrameHost(host_id)->GetProcess();
ScopedAllowRendererCrashes allow_renderer_crashes(process);
process->ForceCrash();
host_observer.WaitForDestroyed();
}
ExpectFinalStatusForSpeculationRule(
#if BUILDFLAG(IS_ANDROID)
PrerenderFinalStatus::kRendererProcessKilled);
#else
PrerenderFinalStatus::kRendererProcessCrashed);
#endif // BUILDFLAG(IS_ANDROID)
}
// Test if the host is abandoned when the renderer page is killed.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, AbandonIfRendererProcessIsKilled) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/empty.html?prerender");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start a prerender.
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
// Shut down the relevant renderer.
{
test::PrerenderHostObserver host_observer(*web_contents_impl(), host_id);
RenderProcessHost* process =
GetPrerenderedMainFrameHost(host_id)->GetProcess();
ScopedAllowRendererCrashes allow_renderer_crashes(process);
EXPECT_TRUE(process->Shutdown(0));
host_observer.WaitForDestroyed();
}
ExpectFinalStatusForSpeculationRule(
PrerenderFinalStatus::kRendererProcessKilled);
}
// Test if the host is abandoned when the primary main page that triggers a
// prerendering is killed.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
AbandonIfPrimaryMainFrameRendererProcessIsKilled) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/empty.html?prerender");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start a prerender.
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
// Shut down the current renderer.
{
test::PrerenderHostObserver host_observer(*web_contents_impl(), host_id);
RenderProcessHost* process = current_frame_host()->GetProcess();
ScopedAllowRendererCrashes allow_renderer_crashes(process);
EXPECT_TRUE(process->Shutdown(0));
host_observer.WaitForDestroyed();
}
ExpectFinalStatusForSpeculationRule(
PrerenderFinalStatus::kPrimaryMainFrameRendererProcessKilled);
}
class PrerenderBackForwardCacheBrowserTest : public PrerenderBrowserTest {
public:
PrerenderBackForwardCacheBrowserTest() {
feature_list_.InitWithFeaturesAndParameters(
{{::features::kBackForwardCache, {}},
{kBackForwardCacheNoTimeEviction, {}}},
// Allow BackForwardCache for all devices regardless of their memory.
{::features::kBackForwardCacheMemoryControls});
}
private:
base::test::ScopedFeatureList feature_list_;
};
IN_PROC_BROWSER_TEST_F(PrerenderBackForwardCacheBrowserTest,
SessionStorageAfterBackNavigation) {
const GURL kInitialUrl = GetUrl("/prerender/session_storage.html");
const GURL kPrerenderingUrl =
GetUrl("/prerender/session_storage.html?prerendering=");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
RenderFrameHostWrapper main_frame(
shell()->web_contents()->GetPrimaryMainFrame());
AddPrerender(kPrerenderingUrl);
NavigatePrimaryPage(kPrerenderingUrl);
EXPECT_EQ("initial", EvalJs(current_frame_host(),
"window.sessionKeysInPrerenderingchange")
.ExtractString());
EXPECT_EQ(
"activated, initial",
EvalJs(current_frame_host(), "getSessionStorageKeys()").ExtractString());
// Speculative fix for the test flakiness (crbug.com/1216038), which may be
// caused by the delayed async IPC of Session Storage (StorageArea.Put()).
EXPECT_TRUE(ExecJs(shell()->web_contents(),
"new Promise(resolve => requestIdleCallback(resolve));"));
// Navigate back to the initial page.
shell()->GoBackOrForward(-1);
WaitForLoadStop(shell()->web_contents());
// Expect the navigation to be served from the back-forward cache to verify
// the test is testing what is intended.
ASSERT_EQ(shell()->web_contents()->GetPrimaryMainFrame(), main_frame.get());
EXPECT_EQ(
"activated, initial",
EvalJs(current_frame_host(), "getSessionStorageKeys()").ExtractString());
}
#if !BUILDFLAG(IS_ANDROID)
// The out-of-process StorageService is not implemented on Android. Also as
// commented below, test_api->CrashNow() won't work on x86 and x86_64 Android.
class PrerenderRestartStorageServiceBrowserTest : public PrerenderBrowserTest {
public:
PrerenderRestartStorageServiceBrowserTest() = default;
protected:
void CrashStorageServiceAndWaitForRestart() {
mojo::Remote<storage::mojom::StorageService>& service =
StoragePartitionImpl::GetStorageServiceForTesting();
base::RunLoop loop;
service.set_disconnect_handler(base::BindLambdaForTesting([&] {
loop.Quit();
service.reset();
}));
mojo::Remote<storage::mojom::TestApi> test_api;
StoragePartitionImpl::GetStorageServiceForTesting()->BindTestApi(
test_api.BindNewPipeAndPassReceiver().PassPipe());
// On x86 and x86_64 Android, base::ImmediateCrash() macro used in
// CrashNow() does not seem to work as expected. (See
// https://crbug.com/1211655)
test_api->CrashNow();
loop.Run();
}
};
IN_PROC_BROWSER_TEST_F(PrerenderRestartStorageServiceBrowserTest,
RestartStorageServiceBeforePrerendering) {
const GURL kInitialUrl = GetUrl("/prerender/session_storage.html");
const GURL kPrerenderingUrl =
GetUrl("/prerender/session_storage.html?prerendering=");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
CrashStorageServiceAndWaitForRestart();
EXPECT_EQ(
"initial",
EvalJs(current_frame_host(), "getSessionStorageKeys()").ExtractString());
AddPrerender(kPrerenderingUrl);
NavigatePrimaryPage(kPrerenderingUrl);
EXPECT_EQ("initial", EvalJs(current_frame_host(),
"window.sessionKeysInPrerenderingchange")
.ExtractString());
EXPECT_EQ(
"activated, initial",
EvalJs(current_frame_host(), "getSessionStorageKeys()").ExtractString());
}
IN_PROC_BROWSER_TEST_F(PrerenderRestartStorageServiceBrowserTest,
RestartStorageServiceWhilePrerendering) {
const GURL kInitialUrl = GetUrl("/prerender/session_storage.html");
const GURL kPrerenderingUrl =
GetUrl("/prerender/session_storage.html?prerendering=");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
CrashStorageServiceAndWaitForRestart();
EXPECT_EQ(
"initial",
EvalJs(current_frame_host(), "getSessionStorageKeys()").ExtractString());
EXPECT_EQ(
"initial, prerendering",
EvalJs(GetPrerenderedMainFrameHost(host_id), "getSessionStorageKeys()")
.ExtractString());
NavigatePrimaryPage(kPrerenderingUrl);
EXPECT_EQ("initial", EvalJs(current_frame_host(),
"window.sessionKeysInPrerenderingchange")
.ExtractString());
EXPECT_EQ(
"activated, initial",
EvalJs(current_frame_host(), "getSessionStorageKeys()").ExtractString());
}
#endif
// Make sure that we can deal with the speculative RFH that is created during
// the activation navigation.
// TODO(crbug.com/40174053): We should try to avoid creating the
// speculative RFH (redirects allowing). Once that is done we should either
// change this test (if redirects allowed) or remove it completely.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, SpeculationRulesScript) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/empty.html?prerender");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
ASSERT_EQ(web_contents()->GetLastCommittedURL(), kInitialUrl);
ASSERT_EQ(GetRequestCount(kPrerenderingUrl), 0);
AddPrerender(kPrerenderingUrl);
EXPECT_EQ(GetRequestCount(kPrerenderingUrl), 1);
// A prerender host for the URL should be registered.
EXPECT_TRUE(HasHostForUrl(kPrerenderingUrl));
// Activate the prerendered page.
// The test passes if we don't crash while cleaning up speculative render
// frame host.
NavigatePrimaryPage(kPrerenderingUrl);
EXPECT_EQ(web_contents()->GetLastCommittedURL(), kPrerenderingUrl);
// The prerender host should be consumed.
EXPECT_FALSE(HasHostForUrl(kPrerenderingUrl));
// Activating the prerendered page should not issue a request.
EXPECT_EQ(GetRequestCount(kPrerenderingUrl), 1);
}
class PrerenderEagernessBrowserTest : public PrerenderBrowserTest {
public:
void SetUp() override {
#if !BUILDFLAG(IS_ANDROID)
PrerenderBrowserTest::SetUp();
#else
// TODO(crbug.com/40269669): Add the implementation of pointer interaction
// on Android to the function below.
GTEST_SKIP();
#endif // BUILDFLAG(IS_ANDROID)
}
};
namespace {
class PreloadingDeciderObserverForPrerenderTesting
: public PreloadingDeciderObserverForTesting {
public:
explicit PreloadingDeciderObserverForPrerenderTesting(
RenderFrameHostImpl* rfh)
: rfh_(rfh) {
auto* preloading_decider =
PreloadingDecider::GetOrCreateForCurrentDocument(rfh_);
old_observer_ = preloading_decider->SetObserverForTesting(this);
events_called_.fill(false);
}
~PreloadingDeciderObserverForPrerenderTesting() override {
auto* preloading_decider =
PreloadingDecider::GetOrCreateForCurrentDocument(rfh_);
EXPECT_EQ(this, preloading_decider->SetObserverForTesting(old_observer_));
}
void UpdateSpeculationCandidates(
const std::vector<blink::mojom::SpeculationCandidatePtr>& candidates)
override {
OnEventCalled(Events::kUpdateSpeculationCandidates);
}
void OnPointerHover(const GURL& url) override {
OnEventCalled(Events::kOnPointerHover);
}
void OnPointerDown(const GURL& url) override {
OnEventCalled(Events::kOnPointerDown);
}
void WaitUpdateSpeculationCandidates() {
WaitEvent(Events::kUpdateSpeculationCandidates);
}
void WaitOnPointerHover() { WaitEvent(Events::kOnPointerHover); }
void WaitOnPointerDown() { WaitEvent(Events::kOnPointerDown); }
private:
enum Events {
kUpdateSpeculationCandidates = 0,
kOnPointerHover,
kOnPointerDown,
kMaxValue = kOnPointerDown,
};
void WaitEvent(Events event) {
if (events_called_[event]) {
return;
}
ASSERT_FALSE(quit_closures_[event]);
base::RunLoop loop;
quit_closures_[event] = loop.QuitClosure();
loop.Run();
}
void OnEventCalled(Events event) {
events_called_[event] = true;
if (quit_closures_[event]) {
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, std::move(quit_closures_[event]));
}
}
raw_ptr<RenderFrameHostImpl> rfh_;
raw_ptr<PreloadingDeciderObserverForTesting> old_observer_;
std::array<base::OnceClosure, Events::kMaxValue + 1> quit_closures_;
std::array<bool, Events::kMaxValue + 1> events_called_;
};
} // namespace
// Tests speculation rules prerendering where the eagerness is "eager".
// The default eagerness of list rules is "eager", so its behavior should be
// same to normal speculation rules prerendering.
IN_PROC_BROWSER_TEST_F(PrerenderEagernessBrowserTest, kEager) {
const GURL initial_url = GetUrl("/empty.html");
const GURL prerendering_url = GetUrl("/empty.html?prerender");
// Navigate to an initial page, insert an anchor to the prerender page.
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
InsertAnchor(prerendering_url);
RenderFrameHostImpl* rfh = current_frame_host();
auto* preloading_decider =
PreloadingDecider::GetOrCreateForCurrentDocument(rfh);
// Add speculation rules with the eagerness.
// When the eagerness is "eager", speculation candidates will never be kept in
// the |on_standby_candidates_| on |PreloadingDecider|, and |PrerenderHost|
// will be created immediately.
AddPrerenderWithEagernessAsync(prerendering_url,
blink::mojom::SpeculationEagerness::kEager);
WaitForPrerenderLoadCompletion(prerendering_url);
EXPECT_TRUE(HasHostForUrl(prerendering_url));
EXPECT_FALSE(preloading_decider->IsOnStandByForTesting(
prerendering_url, blink::mojom::SpeculationAction::kPrerender));
// Activate the prerendered page by clicking the anchor.
FrameTreeNodeId host_id = GetHostForUrl(prerendering_url);
test::PrerenderHostObserver prerender_observer(*web_contents(), host_id);
PointerDownToAnchor(prerendering_url);
PointerUpToAnchor(prerendering_url);
prerender_observer.WaitForActivation();
EXPECT_EQ(web_contents()->GetLastCommittedURL(), prerendering_url);
EXPECT_TRUE(prerender_observer.was_activated());
}
// Tests speculation rules prerendering where the eagerness is "moderate".
IN_PROC_BROWSER_TEST_F(PrerenderEagernessBrowserTest, kModerate) {
const GURL initial_url = GetUrl("/empty.html");
const GURL prerendering_url = GetUrl("/empty.html?prerender");
// Navigate to an initial page, insert an anchor to the prerender page.
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
InsertAnchor(prerendering_url);
RenderFrameHostImpl* rfh = current_frame_host();
PreloadingDeciderObserverForPrerenderTesting preloading_decider_observer(rfh);
auto* preloading_decider =
PreloadingDecider::GetOrCreateForCurrentDocument(rfh);
// Add speculation rules with the eagerness.
// When the eagerness is not "eager", speculation candidates will be kept in
// the |on_standby_candidates_| on |PreloadingDecider|. |PrerenderHost| will
// not be created at this time, waiting for user interaction(pointer hovering
// for the "moderate").
AddPrerenderWithEagernessAsync(prerendering_url,
blink::mojom::SpeculationEagerness::kModerate);
preloading_decider_observer.WaitUpdateSpeculationCandidates();
EXPECT_FALSE(HasHostForUrl(prerendering_url));
EXPECT_TRUE(preloading_decider->IsOnStandByForTesting(
prerendering_url, blink::mojom::SpeculationAction::kPrerender));
// Hover the anchor of the prerendering page. When eagerness is "moderate",
// this interaction invokes the creation of |PrerenderHost|.
PointerHoverToAnchor(prerendering_url);
preloading_decider_observer.WaitOnPointerHover();
WaitForPrerenderLoadCompletion(prerendering_url);
EXPECT_TRUE(HasHostForUrl(prerendering_url));
EXPECT_FALSE(preloading_decider->IsOnStandByForTesting(
prerendering_url, blink::mojom::SpeculationAction::kPrerender));
// Activate the prerendered page by clicking the anchor.
FrameTreeNodeId host_id = GetHostForUrl(prerendering_url);
test::PrerenderHostObserver prerender_observer(*web_contents(), host_id);
PointerDownToAnchor(prerendering_url);
PointerUpToAnchor(prerendering_url);
prerender_observer.WaitForActivation();
EXPECT_EQ(web_contents()->GetLastCommittedURL(), prerendering_url);
EXPECT_TRUE(prerender_observer.was_activated());
}
// Tests speculation rules prerendering where the eagerness is "conservative".
IN_PROC_BROWSER_TEST_F(PrerenderEagernessBrowserTest, kConservative) {
const GURL initial_url = GetUrl("/empty.html");
const GURL prerendering_url = GetUrl("/empty.html?prerender");
// Navigate to an initial page, insert an anchor to the prerender page.
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
InsertAnchor(prerendering_url);
RenderFrameHostImpl* rfh = current_frame_host();
PreloadingDeciderObserverForPrerenderTesting preloading_decider_observer(rfh);
auto* preloading_decider =
PreloadingDecider::GetOrCreateForCurrentDocument(rfh);
// Add speculation rules with the eagerness.
// When the eagerness is not "eager", speculation candidates will be kept in
// the |on_standby_candidates_| on |PreloadingDecider|. |PrerenderHost| will
// not be created at this time, waiting for user interaction(pointer clicking
// for the "conservative").
AddPrerenderWithEagernessAsync(
prerendering_url, blink::mojom::SpeculationEagerness::kConservative);
preloading_decider_observer.WaitUpdateSpeculationCandidates();
EXPECT_FALSE(HasHostForUrl(prerendering_url));
EXPECT_TRUE(preloading_decider->IsOnStandByForTesting(
prerendering_url, blink::mojom::SpeculationAction::kPrerender));
// Click the anchor of the prerendering page. When eagerness is
// "conservative", PointerDown interaction invokes the creation of
// |PrerenderHost| and this host will be activated on the navigation triggered
// by the series of actions(PointerDown, PointerUp) on clicking.
PointerDownToAnchor(prerendering_url);
preloading_decider_observer.WaitOnPointerDown();
WaitForPrerenderLoadCompletion(prerendering_url);
EXPECT_TRUE(HasHostForUrl(prerendering_url));
EXPECT_FALSE(preloading_decider->IsOnStandByForTesting(
prerendering_url, blink::mojom::SpeculationAction::kPrerender));
FrameTreeNodeId host_id = GetHostForUrl(prerendering_url);
test::PrerenderHostObserver prerender_observer(*web_contents(), host_id);
PointerUpToAnchor(prerendering_url);
prerender_observer.WaitForActivation();
EXPECT_EQ(web_contents()->GetLastCommittedURL(), prerendering_url);
EXPECT_TRUE(prerender_observer.was_activated());
}
// TODO(crbug.com/40275452): These tests are turned off on Fuchsia and iOS
// tentatively because pointer simulation on them doesn't work properly on this
// test.
#if !BUILDFLAG(IS_FUCHSIA) && !BUILDFLAG(IS_IOS)
// Tests the metrics
// Prerender.Experimental.ReceivedPrerendersPerPrimaryPageChangedCount2
// correctly records the number of prerenders by each category per primary page
// changed.
IN_PROC_BROWSER_TEST_F(PrerenderEagernessBrowserTest,
ReceivedPrerendersPerPrimaryPageChangedCount) {
auto GetAllSamples = [&](const std::string& eagerness_category) {
return histogram_tester().GetAllSamples(
"Prerender.Experimental.ReceivedPrerendersPerPrimaryPageChangedCount2."
"SpeculationRule." +
eagerness_category);
};
// Navigate to an initial page,
const GURL initial_url = GetUrl("/empty.html");
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
// Nothing should have been recoreded yet.
EXPECT_THAT(GetAllSamples("Total"), testing::IsEmpty());
// Start one eager prerender.
const GURL prerendering_url = GetUrl("/empty.html?prerender");
AddPrerender(prerendering_url);
// Navigate to the another url.
// Expect that the categories "Total" and "Egaer" record 1 and others record
// 0, as there was one eager prerender of the previous page.
const GURL next_url = GetUrl("/empty.html?next");
ASSERT_TRUE(NavigateToURL(shell(), next_url));
EXPECT_THAT(GetAllSamples("Conservative"),
base::BucketsAre(base::Bucket(0, 1)));
EXPECT_THAT(GetAllSamples("Moderate"), base::BucketsAre(base::Bucket(0, 1)));
EXPECT_THAT(GetAllSamples("NonEager"), base::BucketsAre(base::Bucket(0, 1)));
EXPECT_THAT(GetAllSamples("Eager"), base::BucketsAre(base::Bucket(1, 1)));
EXPECT_THAT(GetAllSamples("Total"), base::BucketsAre(base::Bucket(1, 1)));
// Next, try to trigger followings:
// a) 4 prerenders whose eagerness is eager
// b) 2 prerenders whose eagerness is moderate
// c) 1 prerenders whose eagerness is conservative
// Then, try to activate the one of the URL(choosing conservative one).
// a)
for (int i = 0; i < 4; ++i) {
GURL prerendering_url_eager =
GetUrl("/empty.html?prerender_eager_" + base::NumberToString(i));
AddPrerender(prerendering_url_eager);
}
// b)
for (int i = 0; i < 2; ++i) {
GURL prerendering_url_moderate =
GetUrl("/empty.html?prerender_moderate_" + base::NumberToString(i));
InsertAnchor(prerendering_url_moderate);
AddPrerenderWithEagernessAsync(
prerendering_url_moderate,
blink::mojom::SpeculationEagerness::kModerate);
PointerHoverToAnchor(prerendering_url_moderate);
WaitForPrerenderLoadCompletion(prerendering_url_moderate);
}
// c)
const GURL prerendering_url_conservative =
GetUrl("/empty.html?prerender_conservative");
InsertAnchor(prerendering_url_conservative);
AddPrerenderWithEagernessAsync(
prerendering_url_conservative,
blink::mojom::SpeculationEagerness::kConservative);
// Try to trigger and activate.
TestActivationManager activation_manager(web_contents(),
prerendering_url_conservative);
ClickAnchor(prerendering_url_conservative);
activation_manager.WaitForNavigationFinished();
ASSERT_EQ(web_contents()->GetLastCommittedURL(),
prerendering_url_conservative);
ASSERT_TRUE(activation_manager.was_activated());
// Expect following results:
// - For each eagerness category, the number of prerenders triggered with that
// eagerness is recorded.
// - The sum of moderate and conservative prerenders is recorded to
// "NonEager" (2 + 1 = 3).
// - Total eligible numbers of prerenders is recorded to "Total" (4 + 2 + 1 =
// 7).
EXPECT_THAT(GetAllSamples("Eager"),
base::BucketsAre(base::Bucket(1, 1), base::Bucket(4, 1)));
EXPECT_THAT(GetAllSamples("Moderate"),
base::BucketsAre(base::Bucket(0, 1), base::Bucket(2, 1)));
EXPECT_THAT(GetAllSamples("Conservative"),
base::BucketsAre(base::Bucket(0, 1), base::Bucket(1, 1)));
EXPECT_THAT(GetAllSamples("NonEager"),
base::BucketsAre(base::Bucket(0, 1), base::Bucket(3, 1)));
EXPECT_THAT(GetAllSamples("Total"),
base::BucketsAre(base::Bucket(1, 1), base::Bucket(7, 1)));
}
IN_PROC_BROWSER_TEST_F(PrerenderEagernessBrowserTest,
NonEagerPrerendersCanBeRetriggeredAfterTimeout) {
// Navigate to an initial page.
const GURL initial_url = GetUrl("/empty.html");
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
// Add a non-eager speculation rule.
const GURL prerendering_url = GetUrl("/empty.html?prerender");
InsertAnchor(prerendering_url);
AddPrerenderWithEagernessAsync(prerendering_url,
blink::mojom::SpeculationEagerness::kModerate);
// Start prerendering.
test::PrerenderHostCreationWaiter host_creation_waiter_a;
PointerHoverToAnchor(prerendering_url);
FrameTreeNodeId host_id_a = host_creation_waiter_a.Wait();
test::PrerenderHostObserver prerender_observer_a(*web_contents_impl(),
host_id_a);
PrerenderHostRegistry* prerender_host_registry =
web_contents_impl()->GetPrerenderHostRegistry();
ASSERT_FALSE(prerender_host_registry->GetSpeculationRulesTimerForTesting()
->IsRunning());
// Inject mock time task runner.
auto task_runner = base::MakeRefCounted<base::TestMockTimeTaskRunner>();
prerender_host_registry->SetTaskRunnerForTesting(task_runner);
// Change the visibility to hidden and advance the timer. Prerendered page is
// cancelced by timeout.
web_contents()->WasHidden();
ASSERT_TRUE(prerender_host_registry->GetSpeculationRulesTimerForTesting()
->IsRunning());
task_runner->FastForwardBy(
PrerenderHostRegistry::kTimeToLiveInBackgroundForSpeculationRules);
ASSERT_FALSE(prerender_host_registry->GetSpeculationRulesTimerForTesting()
->IsRunning());
prerender_observer_a.WaitForDestroyed();
histogram_tester().ExpectUniqueSample(
"Prerender.Experimental.PrerenderHostFinalStatus.SpeculationRule",
PrerenderFinalStatus::kTimeoutBackgrounded, 1);
// Changing the visibility to shown.
web_contents()->WasShown();
// Start prerendering again.
test::PrerenderHostCreationWaiter host_creation_waiter_b;
PointerHoverToAnchor(prerendering_url);
FrameTreeNodeId host_id_b = host_creation_waiter_b.Wait();
test::PrerenderHostObserver prerender_observer_b(*web_contents(), host_id_b);
NavigatePrimaryPage(prerendering_url);
EXPECT_EQ(web_contents()->GetLastCommittedURL(), prerendering_url);
EXPECT_TRUE(prerender_observer_b.was_activated());
}
class PrerenderNewLimitAndSchedulerBrowserTest
: public PrerenderEagernessBrowserTest,
public testing::WithParamInterface<std::string> {
public:
PrerenderNewLimitAndSchedulerBrowserTest() {
feature_list_.InitWithFeaturesAndParameters(
{{features::kPrerender2NewLimitAndScheduler,
{{"max_num_of_running_speculation_rules_eager_prerenders",
base::NumberToString(
MaxNumOfRunningSpeculationRulesEagerPrerenders())},
{"max_num_of_running_speculation_rules_non_eager_prerenders",
base::NumberToString(
MaxNumOfRunningSpeculationRulesNonEagerPrerenders())},
{"max_num_of_running_embedder_prerenders",
base::NumberToString(MaxNumOfRunningEmbedderPrerenders())}}}},
{});
}
int MaxNumOfRunningSpeculationRulesEagerPrerenders() { return 2; }
int MaxNumOfRunningSpeculationRulesNonEagerPrerenders() { return 1; }
int MaxNumOfRunningEmbedderPrerenders() { return 2; }
private:
base::test::ScopedFeatureList feature_list_;
};
INSTANTIATE_TEST_SUITE_P(All,
PrerenderNewLimitAndSchedulerBrowserTest,
testing::Values("_self", "_blank"),
[](const testing::TestParamInfo<std::string>& info) {
return info.param;
});
IN_PROC_BROWSER_TEST_P(PrerenderNewLimitAndSchedulerBrowserTest,
ResetForNonEagerPrerener) {
const GURL initial_url = GetUrl("/empty.html");
std::vector<GURL> prerendering_urls;
std::vector<base::WeakPtr<WebContents>> prerender_web_contents_list;
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
// Add moderate prerenders as many times as limit + 1 and trigger all of them
// by hovering their links. All prerenders should be started at the time of
// hovering, and the oldest started prerender should be canceled and removed
// from the registry for the limit after the last prerender is started.
int num_of_attempts = MaxNumOfRunningSpeculationRulesNonEagerPrerenders() + 1;
for (int i = 0; i < num_of_attempts; i++) {
PreloadingDeciderObserverForPrerenderTesting preloading_decider_observer(
current_frame_host());
const GURL prerendering_url =
GetUrl("/empty.html?prerender" + base::ToString(i));
prerendering_urls.push_back(prerendering_url);
InsertAnchor(prerendering_url);
AddPrerendersAsync({prerendering_url},
blink::mojom::SpeculationEagerness::kModerate,
GetParam());
preloading_decider_observer.WaitUpdateSpeculationCandidates();
test::PrerenderHostCreationWaiter host_creation_waiter;
PointerHoverToAnchor(prerendering_url);
FrameTreeNodeId host_id = host_creation_waiter.Wait();
auto* prerender_web_contents = WebContents::FromFrameTreeNodeId(host_id);
prerender_web_contents_list.push_back(prerender_web_contents->GetWeakPtr());
test::PrerenderTestHelper::WaitForPrerenderLoadCompletion(
*prerender_web_contents, prerendering_url);
}
for (int i = 0; i < num_of_attempts; i++) {
bool host_existing_in_registry =
prerender_web_contents_list[i] &&
HasHostForUrl(*prerender_web_contents_list[i], prerendering_urls[i]);
if (i == 0) {
// The first (= oldest) prerender is removed since the (limit + 1)-th
// prerender was started.
ASSERT_FALSE(host_existing_in_registry);
} else {
ASSERT_TRUE(host_existing_in_registry);
}
}
// Hover the first link again. This should be retriggered.
const auto& prerendering_url_first = prerendering_urls[0];
test::PrerenderHostCreationWaiter host_creation_waiter;
PointerHoverToAnchor(prerendering_url_first);
FrameTreeNodeId host_id = host_creation_waiter.Wait();
auto* prerender_web_contents = WebContents::FromFrameTreeNodeId(host_id);
prerender_web_contents_list[0] = prerender_web_contents->GetWeakPtr();
test::PrerenderTestHelper::WaitForPrerenderLoadCompletion(
*prerender_web_contents, prerendering_url_first);
// The oldest prerender in registry at this point should be removed due to the
// limit.
for (int i = 0; i < num_of_attempts; i++) {
bool host_existing_in_registry =
prerender_web_contents_list[i] &&
HasHostForUrl(*prerender_web_contents_list[i], prerendering_urls[i]);
if (i == 1) {
EXPECT_FALSE(host_existing_in_registry);
} else {
EXPECT_TRUE(host_existing_in_registry);
}
}
}
#endif // !BUILDFLAG(IS_FUCHSIA) && !BUILDFLAG(IS_IOS)
class PrerenderWithBackForwardCacheBrowserTest
: public PrerenderBrowserTest,
public testing::WithParamInterface<BackForwardCacheType> {
public:
PrerenderWithBackForwardCacheBrowserTest() {
switch (GetParam()) {
case BackForwardCacheType::kDisabled:
feature_list_.InitAndDisableFeature(::features::kBackForwardCache);
break;
case BackForwardCacheType::kEnabled:
feature_list_.InitWithFeaturesAndParameters(
GetDefaultEnabledBackForwardCacheFeaturesForTesting(
/*ignore_outstanding_network_request=*/false),
GetDefaultDisabledBackForwardCacheFeaturesForTesting());
break;
}
}
private:
base::test::ScopedFeatureList feature_list_;
};
INSTANTIATE_TEST_SUITE_P(All,
PrerenderWithBackForwardCacheBrowserTest,
testing::Values(BackForwardCacheType::kDisabled,
BackForwardCacheType::kEnabled),
ToString);
// Tests that history navigation works after activation. This runs with variaous
// BFCache configurations that may modify behavior of history navigation.
// This is a regression test for https://crbug.com/1201914.
IN_PROC_BROWSER_TEST_P(PrerenderWithBackForwardCacheBrowserTest,
HistoryNavigationAfterActivation) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/empty.html?prerender");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
RenderFrameHostImpl* initial_frame_host = current_frame_host();
blink::LocalFrameToken initial_frame_token =
initial_frame_host->GetFrameToken();
// When the BFCache is disabled, activation will destroy the initial frame
// host. This observer will be used for confirming it.
RenderFrameDeletedObserver delete_observer(initial_frame_host);
// Make and activate a prerendered page.
AddPrerender(kPrerenderingUrl);
NavigatePrimaryPage(kPrerenderingUrl);
EXPECT_EQ(web_contents()->GetLastCommittedURL(), kPrerenderingUrl);
// Check if the initial page is in the BFCache.
switch (GetParam()) {
case BackForwardCacheType::kDisabled:
EXPECT_NE(current_frame_host(), initial_frame_host);
// The initial frame host should be deleted after activation because it is
// not cached in the BFCache.
delete_observer.WaitUntilDeleted();
break;
case BackForwardCacheType::kEnabled:
// Same-origin prerender activation should allow the initial page to be
// cached in the BFCache.
ASSERT_TRUE(IsBackForwardCacheEnabled());
EXPECT_TRUE(initial_frame_host->IsInBackForwardCache());
break;
}
// Navigate back to the initial page.
TestNavigationObserver observer(web_contents());
shell()->GoBackOrForward(-1);
observer.Wait();
EXPECT_EQ(web_contents()->GetLastCommittedURL(), kInitialUrl);
// Check if the back navigation is served from the BFCache.
switch (GetParam()) {
case BackForwardCacheType::kDisabled:
// The frame host should be created again.
EXPECT_NE(current_frame_host()->GetFrameToken(), initial_frame_token);
break;
case BackForwardCacheType::kEnabled:
// The frame host should be restored.
EXPECT_EQ(current_frame_host()->GetFrameToken(), initial_frame_token);
EXPECT_FALSE(initial_frame_host->IsInBackForwardCache());
break;
}
}
// Tests that a trigger page destroys a prerendered page when it navigates
// forward and goes into the back/forward cache.
IN_PROC_BROWSER_TEST_P(PrerenderWithBackForwardCacheBrowserTest,
CancelOnAfterTriggerIsStoredInBackForwardCache_Forward) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kNextUrl = GetUrl("/empty.html?next");
const GURL kPrerenderingUrl = GetUrl("/empty.html?prerender");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
RenderFrameHostImplWrapper initial_frame_host(current_frame_host());
// Make a prerendered page from the initial page.
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
test::PrerenderHostObserver prerender_observer(*web_contents_impl(), host_id);
// Navigate the initial page to a non-prerendered page.
ASSERT_TRUE(NavigateToURL(shell(), kNextUrl));
// Check if the initial page is in the back/forward cache.
switch (GetParam()) {
case BackForwardCacheType::kDisabled:
// The BFCache is disabled, so the initial page is not in the
// back/forward cache.
if (ShouldCreateNewHostForAllFrames()) {
ASSERT_TRUE(initial_frame_host.WaitUntilRenderFrameDeleted());
} else {
ASSERT_FALSE(initial_frame_host->IsInBackForwardCache());
}
break;
case BackForwardCacheType::kEnabled:
// The back/forward cache is enabled, so the initial page is in the
// back/forward cache after the same-origin navigation.
ASSERT_TRUE(IsBackForwardCacheEnabled());
ASSERT_TRUE(initial_frame_host->IsInBackForwardCache());
break;
}
// The navigation should destroy the prerendered page regardless of if the
// initial page was in the back/forward cache.
prerender_observer.WaitForDestroyed();
EXPECT_FALSE(HasHostForUrl(kPrerenderingUrl));
ExpectFinalStatusForSpeculationRule(PrerenderFinalStatus::kTriggerDestroyed);
}
// Tests that a trigger page destroys a prerendered page when it navigates back
// and goes into the BFCache.
IN_PROC_BROWSER_TEST_P(PrerenderWithBackForwardCacheBrowserTest,
CancelOnAfterTriggerIsStoredInBackForwardCache_Back) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kNextUrl = GetUrl("/empty.html?next");
const GURL kPrerenderingUrl = GetUrl("/empty.html?prerender");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Navigate to a next page.
ASSERT_TRUE(NavigateToURL(shell(), kNextUrl));
RenderFrameHostImplWrapper next_frame_host(current_frame_host());
// Make a prerendered page from the next page.
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
test::PrerenderHostObserver prerender_observer(*web_contents_impl(), host_id);
// Navigate back to the initial page.
TestNavigationObserver navigation_observer(web_contents());
shell()->GoBackOrForward(-1);
navigation_observer.Wait();
EXPECT_EQ(web_contents()->GetLastCommittedURL(), kInitialUrl);
// Check if the next page is in the back/forward cache.
switch (GetParam()) {
case BackForwardCacheType::kDisabled:
// The back/forward cache is disabled, so the next page is not in the
// back/forward cache.
if (ShouldCreateNewHostForAllFrames()) {
ASSERT_TRUE(next_frame_host.WaitUntilRenderFrameDeleted());
} else {
ASSERT_FALSE(next_frame_host->IsInBackForwardCache());
}
break;
case BackForwardCacheType::kEnabled:
// The back/forward cache is enabled, so the next page is in the
// back/forward cache after the same-origin back navigation.
ASSERT_TRUE(IsBackForwardCacheEnabled());
ASSERT_TRUE(next_frame_host->IsInBackForwardCache());
break;
}
// The navigation should destroy the prerendered page regardless of if the
// next page was in the back/forward cache.
prerender_observer.WaitForDestroyed();
EXPECT_FALSE(HasHostForUrl(kPrerenderingUrl));
ExpectFinalStatusForSpeculationRule(PrerenderFinalStatus::kTriggerDestroyed);
}
class PrerenderBackForwardCacheRestorationBrowserTest
: public PrerenderEagernessBrowserTest,
public BackForwardCacheMetricsTestMatcher,
public testing::WithParamInterface<blink::mojom::SpeculationEagerness> {
public:
PrerenderBackForwardCacheRestorationBrowserTest() {
feature_list_.InitWithFeaturesAndParameters(
GetDefaultEnabledBackForwardCacheFeaturesForTesting(
/*ignore_outstanding_network_request=*/false),
GetDefaultDisabledBackForwardCacheFeaturesForTesting());
}
protected:
blink::mojom::SpeculationEagerness GetSpeculationEagerness() const {
return GetParam();
}
// implementation for `BackForwardCacheMetricsTestMatcher`
const ukm::TestAutoSetUkmRecorder& ukm_recorder() override {
return *PrerenderBrowserTest::test_ukm_recorder();
}
// implementation for `BackForwardCacheMetricsTestMatcher`
const base::HistogramTester& histogram_tester() override {
return PrerenderBrowserTest::histogram_tester();
}
private:
base::test::ScopedFeatureList feature_list_;
};
INSTANTIATE_TEST_SUITE_P(
All,
PrerenderBackForwardCacheRestorationBrowserTest,
testing::Values(blink::mojom::SpeculationEagerness::kEager,
blink::mojom::SpeculationEagerness::kModerate,
blink::mojom::SpeculationEagerness::kConservative),
[](const testing::TestParamInfo<blink::mojom::SpeculationEagerness>& info) {
return base::ToString(info.param);
});
// Test whether speculation rules prerendering is processed again on pages
// restored from BFCache via forward navigation.
// When the eagerness is kEager(default), speculation rules prerendering will no
// longer be processed after restoration.
// For non-eager cases (kModerate, kConservative), candidates are stored between
// restoration unless they were triggered by user action (This test scenario
// reproduces only this case). However, once after processed by user action,
// then they will not be processed again until they are retriggered
// (crbug.com/1449163 for more information).
IN_PROC_BROWSER_TEST_P(PrerenderBackForwardCacheRestorationBrowserTest,
RestoredViaForwardNavigation) {
const GURL initial_url = GetUrl("/empty.html");
const GURL next_url = GetUrl("/empty.html?next");
const GURL prerendering_url = GetUrl("/empty.html?prerender");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
// Navigate to a next page.
ASSERT_TRUE(NavigateToURL(shell(), next_url));
RenderFrameHostImpl* rfh_next = current_frame_host();
InsertAnchor(prerendering_url);
PreloadingDeciderObserverForPrerenderTesting preloading_decider_observer(
rfh_next);
auto* preloading_decider =
PreloadingDecider::GetOrCreateForCurrentDocument(rfh_next);
// Add speculation rules and wait to be loaded.
AddPrerenderWithEagernessAsync(prerendering_url, GetSpeculationEagerness());
if (GetSpeculationEagerness() == blink::mojom::SpeculationEagerness::kEager) {
WaitForPrerenderLoadCompletion(prerendering_url);
ASSERT_TRUE(HasHostForUrl(prerendering_url));
} else {
preloading_decider_observer.WaitUpdateSpeculationCandidates();
ASSERT_TRUE(preloading_decider->IsOnStandByForTesting(
prerendering_url, blink::mojom::SpeculationAction::kPrerender));
}
// Navigate backward to the initial page. The next page should be stored to
// the BFCache.
GoBack();
ASSERT_EQ(web_contents()->GetLastCommittedURL(), initial_url);
ExpectRestored(FROM_HERE);
ASSERT_TRUE(rfh_next->IsInBackForwardCache());
// Navigate forward. The next page should be restored from the BFCache.
GoForward();
ASSERT_EQ(web_contents()->GetLastCommittedURL(), next_url);
ExpectRestored(FROM_HERE);
if (GetSpeculationEagerness() == blink::mojom::SpeculationEagerness::kEager) {
// Prerendering will be processed by retriggering.
WaitForPrerenderLoadCompletion(prerendering_url);
FrameTreeNodeId host_id_retriggered = GetHostForUrl(prerendering_url);
test::PrerenderHostObserver prerender_observer(*web_contents(),
host_id_retriggered);
// Activate the prerendered page.
NavigatePrimaryPage(prerendering_url);
prerender_observer.WaitForActivation();
ASSERT_EQ(web_contents()->GetLastCommittedURL(), prerendering_url);
EXPECT_TRUE(prerender_observer.was_activated());
} else {
ASSERT_FALSE(HasHostForUrl(prerendering_url));
// |on_standby_candidates_| holds the non-eager candidates if the candidates
// were not processed by user interaction.
EXPECT_TRUE(preloading_decider->IsOnStandByForTesting(
prerendering_url, blink::mojom::SpeculationAction::kPrerender));
// Trigger and activate the non-eager prerender.
{
TestActivationManager activation_manager(web_contents(),
prerendering_url);
ClickAnchor(prerendering_url);
activation_manager.WaitForNavigationFinished();
ASSERT_EQ(web_contents()->GetLastCommittedURL(), prerendering_url);
ASSERT_TRUE(activation_manager.was_activated());
}
}
}
// Test whether speculation rules prerendering is processed again on pages
// restored from BFCache via backward navigation.
// When the eagerness is kEager(default), speculation rules prerendering will no
// longer be processed after restoration.
// For non-eager cases (kModerate, kConservative), candidates are stored between
// restoration unless they were triggered by user action. However, once after
// processed by user action, then they will not be processed again until they
// are retriggered (crbug.com/1449163 for more information).
IN_PROC_BROWSER_TEST_P(PrerenderBackForwardCacheRestorationBrowserTest,
RestoredViaBackwardNavigation) {
const GURL initial_url = GetUrl("/empty.html");
const GURL prerendering_url_a = GetUrl("/empty.html?prerender_a");
const GURL prerendering_url_b = GetUrl("/empty.html?prerender_b");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
RenderFrameHostImpl* rfh_initial = current_frame_host();
InsertAnchor(prerendering_url_a);
InsertAnchor(prerendering_url_b);
if (GetSpeculationEagerness() == blink::mojom::SpeculationEagerness::kEager) {
// Add speculation rules and wait to be loaded.
AddPrerenderWithEagernessAsync(prerendering_url_a,
GetSpeculationEagerness());
AddPrerenderWithEagernessAsync(prerendering_url_b,
GetSpeculationEagerness());
WaitForPrerenderLoadCompletion(prerendering_url_a);
WaitForPrerenderLoadCompletion(prerendering_url_b);
FrameTreeNodeId host_id_a = GetHostForUrl(prerendering_url_a);
test::PrerenderHostObserver prerender_observer_a(*web_contents(),
host_id_a);
// Activate the page A. The initial page should be stored to the BFCache.
NavigatePrimaryPage(prerendering_url_a);
prerender_observer_a.WaitForActivation();
ASSERT_EQ(web_contents()->GetLastCommittedURL(), prerendering_url_a);
ASSERT_TRUE(prerender_observer_a.was_activated());
ASSERT_TRUE(rfh_initial->IsInBackForwardCache());
// Navigate backward. The initial page should be restored from the BFCache.
GoBack();
ASSERT_EQ(web_contents()->GetLastCommittedURL(), initial_url);
ExpectRestored(FROM_HERE);
// Prerendering for both the page A and the page B will be processed by
// retriggering.
WaitForPrerenderLoadCompletion(prerendering_url_a);
WaitForPrerenderLoadCompletion(prerendering_url_b);
FrameTreeNodeId host_id_a_retriggered = GetHostForUrl(prerendering_url_a);
test::PrerenderHostObserver prerender_observer_a_retriggered(
*web_contents(), host_id_a_retriggered);
// Activate the page A again.
NavigatePrimaryPage(prerendering_url_a);
prerender_observer_a_retriggered.WaitForActivation();
ASSERT_EQ(web_contents()->GetLastCommittedURL(), prerendering_url_a);
EXPECT_TRUE(prerender_observer_a_retriggered.was_activated());
} else {
auto* preloading_decider =
PreloadingDecider::GetOrCreateForCurrentDocument(rfh_initial);
// Add speculation rules and wait to be loaded.
// TODO(taiyo): modify |PreloadingDeciderObserverForPrerenderTesting| to
// enable observing for URLs.
{
PreloadingDeciderObserverForPrerenderTesting preloading_decider_observer(
rfh_initial);
AddPrerenderWithEagernessAsync(prerendering_url_a,
GetSpeculationEagerness());
preloading_decider_observer.WaitUpdateSpeculationCandidates();
}
{
PreloadingDeciderObserverForPrerenderTesting preloading_decider_observer(
rfh_initial);
AddPrerenderWithEagernessAsync(prerendering_url_b,
GetSpeculationEagerness());
preloading_decider_observer.WaitUpdateSpeculationCandidates();
}
ASSERT_TRUE(preloading_decider->IsOnStandByForTesting(
prerendering_url_a, blink::mojom::SpeculationAction::kPrerender));
ASSERT_TRUE(preloading_decider->IsOnStandByForTesting(
prerendering_url_b, blink::mojom::SpeculationAction::kPrerender));
// Activate the page A. The initial page should be stored to the BFCache.
{
TestActivationManager activation_manager(web_contents(),
prerendering_url_a);
ClickAnchor(prerendering_url_a);
activation_manager.WaitForNavigationFinished();
ASSERT_EQ(web_contents()->GetLastCommittedURL(), prerendering_url_a);
ASSERT_TRUE(activation_manager.was_activated());
ASSERT_TRUE(rfh_initial->IsInBackForwardCache());
}
// Navigate backward. The initial page should be restored from the BFCache.
GoBack();
ASSERT_EQ(web_contents()->GetLastCommittedURL(), initial_url);
ExpectRestored(FROM_HERE);
// |on_standby_candidates_| holds the non-eager candidates if the candidates
// were not processed by user interaction so that the the Page B's candidate
// should be in the |on_standby_candidates_|.
EXPECT_TRUE(preloading_decider->IsOnStandByForTesting(
prerendering_url_b, blink::mojom::SpeculationAction::kPrerender));
// TODO(crbug.com/40273826): In the current implementation, non-eager
// candidates that are once processed by user interaction will no
// longer be stored in |on_standby_candidates_| when retriggered (more
// specifically, |UpdateSpeculationCandidates| is (re)invoked) and instead
// |PrerenderHost| will be created immediately, as with eager candidates.
// See crbug description for more details.
{
WaitForPrerenderLoadCompletion(prerendering_url_a);
EXPECT_TRUE(HasHostForUrl(prerendering_url_a));
EXPECT_FALSE(preloading_decider->IsOnStandByForTesting(
prerendering_url_a, blink::mojom::SpeculationAction::kPrerender));
}
ASSERT_FALSE(HasHostForUrl(prerendering_url_b));
// Trigger and activate the Page A again.
{
TestActivationManager activation_manager(web_contents(),
prerendering_url_a);
ClickAnchor(prerendering_url_a);
activation_manager.WaitForNavigationFinished();
ASSERT_EQ(web_contents()->GetLastCommittedURL(), prerendering_url_a);
ASSERT_TRUE(activation_manager.was_activated());
}
}
}
// Tests that PrerenderHostRegistry can hold up to two prerendering for the
// prerender embedders it receives.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, StartByEmbeddersMultipleTimes) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kFirstPrerenderingUrl = GetUrl("/empty.html?prerender1");
const GURL kSecondPrerenderingUrl = GetUrl("/empty.html?prerender2");
const GURL kThirdPrerenderingUrl = GetUrl("/empty.html?prerender3");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start prerendering by embedder triggered prerendering; this should be
// trigger successfully.
std::unique_ptr<PrerenderHandle> prerender_handle1 =
AddEmbedderTriggeredPrerenderAsync(kFirstPrerenderingUrl);
EXPECT_TRUE(prerender_handle1);
histogram_tester().ExpectBucketCount(
"Prerender.Experimental.PrerenderHostFinalStatus.Embedder_"
"EmbedderSuffixForTest",
PrerenderFinalStatus::kMaxNumOfRunningEagerPrerendersExceeded, 0);
// Start prerendering by embedder triggered prerendering; this should be
// trigger successfully.
std::unique_ptr<PrerenderHandle> prerender_handle2 =
AddEmbedderTriggeredPrerenderAsync(kSecondPrerenderingUrl);
EXPECT_TRUE(prerender_handle2);
histogram_tester().ExpectBucketCount(
"Prerender.Experimental.PrerenderHostFinalStatus.Embedder_"
"EmbedderSuffixForTest",
PrerenderFinalStatus::kMaxNumOfRunningEmbedderPrerendersExceeded, 0);
// Start prerendering by embedder triggered prerendering; this should hit the
// limit.
std::unique_ptr<PrerenderHandle> prerender_handle3 =
AddEmbedderTriggeredPrerenderAsync(kThirdPrerenderingUrl);
EXPECT_FALSE(prerender_handle3);
histogram_tester().ExpectBucketCount(
"Prerender.Experimental.PrerenderHostFinalStatus.Embedder_"
"EmbedderSuffixForTest",
PrerenderFinalStatus::kMaxNumOfRunningEmbedderPrerendersExceeded, 1);
}
// Tests that PrerenderHostRegistry can hold up to two prerendering for the
// prerender speculation rule and prerender embedders in total.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
StartByEmbeddersAndSpeculationRulesMultipleTimes) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kSpeculationRulesPrerenderingUrl =
GetUrl("/empty.html?prerender1");
const GURL kEmbedderPrerenderingUrl1 = GetUrl("/empty.html?prerender2");
const GURL kEmbedderPrerenderingUrl2 = GetUrl("/empty.html?prerender3");
const GURL kEmbedderPrerenderingUrl3 = GetUrl("/empty.html?prerender4");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Add a prerender speculation rule; this should be triggered successfully.
AddPrerender(kSpeculationRulesPrerenderingUrl);
// Add the first prerender speculation rule; it should trigger prerendering
// successfully.
histogram_tester().ExpectBucketCount(
"Prerender.Experimental.PrerenderHostFinalStatus.SpeculationRule",
PrerenderFinalStatus::kMaxNumOfRunningEagerPrerendersExceeded, 0);
histogram_tester().ExpectBucketCount(
"Prerender.Experimental.PrerenderHostFinalStatus.Embedder_"
"EmbedderSuffixForTest",
PrerenderFinalStatus::kMaxNumOfRunningEmbedderPrerendersExceeded, 0);
// Start the first embedder triggered prerendering; this should be triggered
// successfully.
std::unique_ptr<PrerenderHandle> prerender_handle1 =
AddEmbedderTriggeredPrerenderAsync(kEmbedderPrerenderingUrl1);
EXPECT_TRUE(prerender_handle1);
// Start the second embedder triggered prerendering; this should be triggered
// successfully.
std::unique_ptr<PrerenderHandle> prerender_handle2 =
AddEmbedderTriggeredPrerenderAsync(kEmbedderPrerenderingUrl2);
EXPECT_TRUE(prerender_handle2);
histogram_tester().ExpectBucketCount(
"Prerender.Experimental.PrerenderHostFinalStatus.Embedder_"
"EmbedderSuffixForTest",
PrerenderFinalStatus::kMaxNumOfRunningEmbedderPrerendersExceeded, 0);
// Start the third embedder triggered prerendering; this should hit the limit.
std::unique_ptr<PrerenderHandle> prerender_handle3 =
AddEmbedderTriggeredPrerenderAsync(kEmbedderPrerenderingUrl3);
EXPECT_FALSE(prerender_handle3);
histogram_tester().ExpectBucketCount(
"Prerender.Experimental.PrerenderHostFinalStatus.Embedder_"
"EmbedderSuffixForTest",
PrerenderFinalStatus::kMaxNumOfRunningEmbedderPrerendersExceeded, 1);
// Cancel the second embedder triggered prerendering and start a new one;
// this should succeed as one of the prerenders is freed.
prerender_handle2.reset();
prerender_handle3 =
AddEmbedderTriggeredPrerenderAsync(kEmbedderPrerenderingUrl3);
EXPECT_TRUE(prerender_handle3);
}
class MultiplePrerendersBrowserTest : public PrerenderBrowserTest {
public:
MultiplePrerendersBrowserTest() {
base::test::FeatureRefAndParams memory_controls{
blink::features::kPrerender2MemoryControls,
// A value 100 allows prerenderings regardless of the current memory
// usage.
{{"acceptable_percent_of_system_memory", "100"},
// Allow prerendering on low-end trybot devices so that prerendering
// can run on any bots.
{"memory_threshold_in_mb", "0"}}};
feature_list_.InitWithFeaturesAndParameters(
{{features::kPrerender2NewLimitAndScheduler,
{{"max_num_of_running_speculation_rules_eager_prerenders",
base::NumberToString(MaxNumOfRunningPrerenders())}}},
memory_controls},
{});
}
int MaxNumOfRunningPrerenders() const { return 4; }
private:
base::test::ScopedFeatureList feature_list_;
};
class MultiplePrerendersWithLimitedMemoryBrowserTest
: public MultiplePrerendersBrowserTest {
public:
MultiplePrerendersWithLimitedMemoryBrowserTest() {
base::test::FeatureRefAndParams memory_controls{
blink::features::kPrerender2MemoryControls,
// A value 0 doesn't allow any prerendering.
{{"acceptable_percent_of_system_memory", "0"},
// Allow prerendering on low-end trybot devices so that prerendering
// can run on any bots.
{"memory_threshold_in_mb", "0"}}};
feature_list_.InitWithFeaturesAndParameters(
{{features::kPrerender2NewLimitAndScheduler,
{{"max_num_of_running_speculation_rules_eager_prerenders",
base::NumberToString(MaxNumOfRunningPrerenders())}}},
memory_controls},
{});
}
private:
base::test::ScopedFeatureList feature_list_;
};
// Tests that moderate-level memory pressure doesn't cancel prerendering on
// trigger.
IN_PROC_BROWSER_TEST_F(MultiplePrerendersBrowserTest,
MemoryPressureOnTrigger_Moderate) {
GURL initial_url = GetUrl("/empty.html");
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
// Emulate moderate-level memory pressure state.
FakeMemoryPressureMonitor memory_pressure_monitor(
base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_MODERATE);
ASSERT_EQ(base::MemoryPressureMonitor::Get()->GetCurrentPressureLevel(),
base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_MODERATE);
// Triggering prerendering should not be canceled due to the moderate level
// memory pressure.
GURL prerender_url = GetUrl("/empty.html?prerender");
AddPrerender(prerender_url);
EXPECT_TRUE(HasHostForUrl(prerender_url));
histogram_tester().ExpectUniqueSample(
"Prerender.Experimental.PrerenderHostFinalStatus.SpeculationRule",
PrerenderFinalStatus::kMemoryPressureOnTrigger, 0);
}
// Tests that critical-level memory pressure cancels prerendering on trigger.
IN_PROC_BROWSER_TEST_F(MultiplePrerendersBrowserTest,
MemoryPressureOnTrigger_Critical) {
GURL initial_url = GetUrl("/empty.html");
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
// Emulate critical-level memory pressure state.
FakeMemoryPressureMonitor memory_pressure_monitor(
base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL);
ASSERT_EQ(base::MemoryPressureMonitor::Get()->GetCurrentPressureLevel(),
base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL);
// Triggering prerendering should be canceled due to the critical level memory
// pressure.
GURL prerender_url = GetUrl("/empty.html?prerender");
test::PrerenderHostRegistryObserver registry_observer(*web_contents_impl());
AddPrerenderAsync(prerender_url);
registry_observer.WaitForTrigger(prerender_url);
EXPECT_FALSE(HasHostForUrl(prerender_url));
histogram_tester().ExpectUniqueSample(
"Prerender.Experimental.PrerenderHostFinalStatus.SpeculationRule",
PrerenderFinalStatus::kMemoryPressureOnTrigger, 1);
}
// Tests that moderate-level memory pressure doesn't cancel prerendering after
// triggered.
IN_PROC_BROWSER_TEST_F(MultiplePrerendersBrowserTest,
MemoryPressureAfterTriggered_Moderate) {
GURL initial_url = GetUrl("/empty.html");
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
std::vector<GURL> prerender_urls = {
GetUrl("/empty.html?prerender0"),
GetUrl("/empty.html?prerender1"),
GetUrl("/empty.html?prerender2"),
};
for (const GURL& prerender_url : prerender_urls) {
AddPrerender(prerender_url);
}
// Emulate moderate-level memory pressure event. This shouldn't cancel
// prerendering.
base::MemoryPressureListener::NotifyMemoryPressure(
base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_MODERATE);
// Run the message loop to give a chance to unexpectedly cancel prerendering
// due to some bug.
base::RunLoop().RunUntilIdle();
histogram_tester().ExpectUniqueSample(
"Prerender.Experimental.PrerenderHostFinalStatus.SpeculationRule",
PrerenderFinalStatus::kMemoryPressureAfterTriggered, 0);
}
// Tests that critical-level memory pressure cancels prerendering after
// triggered.
IN_PROC_BROWSER_TEST_F(MultiplePrerendersBrowserTest,
MemoryPressureAfterTriggered_Critical) {
GURL initial_url = GetUrl("/empty.html");
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
std::vector<GURL> prerender_urls = {
GetUrl("/empty.html?prerender0"),
GetUrl("/empty.html?prerender1"),
GetUrl("/empty.html?prerender2"),
};
std::vector<std::unique_ptr<test::PrerenderHostObserver>> observers;
for (const GURL& prerender_url : prerender_urls) {
FrameTreeNodeId host_id = AddPrerender(prerender_url);
observers.push_back(std::make_unique<test::PrerenderHostObserver>(
*web_contents(), host_id));
}
// Emulate critical-level memory pressure event. This should cancel
// prerendering.
base::MemoryPressureListener::NotifyMemoryPressure(
base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL);
for (auto& observer : observers) {
observer->WaitForDestroyed();
}
histogram_tester().ExpectUniqueSample(
"Prerender.Experimental.PrerenderHostFinalStatus.SpeculationRule",
PrerenderFinalStatus::kMemoryPressureAfterTriggered,
prerender_urls.size());
}
// Tests that PrerenderHostRegistry only starts prerender speculation rules
// up to `max_num_of_running_speculation_rules` defined by a Finch param.
IN_PROC_BROWSER_TEST_F(MultiplePrerendersBrowserTest,
AddSpeculationRulesMultipleTimes) {
const GURL kInitialUrl = GetUrl("/empty.html");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
for (int i = 0; i < MaxNumOfRunningPrerenders(); i++) {
GURL prerendering_url =
GetUrl("/empty.html?prerender" + base::NumberToString(i));
// Add a prerender speculation rule; it should trigger prerendering
// successfully.
AddPrerender(prerendering_url);
}
test::PrerenderHostRegistryObserver registry_observer(*web_contents_impl());
const GURL kExceededPrerenderingUrl =
GetUrl("/empty.html?exceeded-prerender");
// Add a new prerender speculation rule. Since PrerenderHostRegistry limits
// the number of running prerenders to `max_num_of_running_speculation_rules`
// defined by a Finch param, this rule should not be applied.
AddPrerenderAsync(kExceededPrerenderingUrl);
registry_observer.WaitForTrigger(kExceededPrerenderingUrl);
EXPECT_FALSE(HasHostForUrl(kExceededPrerenderingUrl));
ExpectFinalStatusForSpeculationRule(
PrerenderFinalStatus::kMaxNumOfRunningEagerPrerendersExceeded);
const GURL kEmbedderTriggeredPrerenderingUrl =
GetUrl("/empty.html?embedder-triggered-prerender");
// Start an embedder triggered prerendering; this should be triggered
// successfully because its limitation is independent from speculation rules.
std::unique_ptr<PrerenderHandle> prerender_handle =
AddEmbedderTriggeredPrerenderAsync(kEmbedderTriggeredPrerenderingUrl);
EXPECT_TRUE(prerender_handle);
}
// Tests that PrerenderHostRegistry can start prerendering when the DevTools is
// open even if the acceptable percent of the system memory is set to 0.
IN_PROC_BROWSER_TEST_F(MultiplePrerendersWithLimitedMemoryBrowserTest,
DevToolsOverride) {
GURL initial_url = GetUrl("/empty.html");
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
// Emulating Devtools attached to test the memory restriction override. Retain
// the returned host until the test finishes to avoid DevTools termination.
scoped_refptr<DevToolsAgentHost> dev_tools_agent_host =
content::DevToolsAgentHost::GetOrCreateFor(web_contents());
ASSERT_TRUE(dev_tools_agent_host);
std::vector<GURL> urls = {
GetUrl("/empty.html?prerender0"),
GetUrl("/empty.html?prerender1"),
GetUrl("/empty.html?prerender2"),
};
for (const GURL& url : urls) {
AddPrerender(url);
}
// Prerender attempts shouldn't be cancelled for the memory limit.
histogram_tester().ExpectUniqueSample(
"Prerender.Experimental.PrerenderHostFinalStatus.SpeculationRule",
PrerenderFinalStatus::kMemoryLimitExceeded, 0);
// Activate one of the prerendered pages. This should cancel the other
// prerendered as kTriggerDestroyed.
NavigatePrimaryPage(urls[0]);
ASSERT_EQ(web_contents()->GetLastCommittedURL(), urls[0]);
histogram_tester().ExpectBucketCount(
"Prerender.Experimental.PrerenderHostFinalStatus.SpeculationRule",
PrerenderFinalStatus::kActivated, 1);
histogram_tester().ExpectBucketCount(
"Prerender.Experimental.PrerenderHostFinalStatus.SpeculationRule",
PrerenderFinalStatus::kOtherPrerenderedPageActivated, 2);
}
// Tests that cross-site urls cannot be prerendered.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, SkipCrossSitePrerender) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetCrossSiteUrl("/empty.html?crossorigin");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
test::PrerenderHostRegistryObserver registry_observer(*web_contents_impl());
url::Origin initiator_origin = url::Origin::Create(kInitialUrl);
url::Origin prerender_origin = url::Origin::Create(kPrerenderingUrl);
// Add a cross-origin prerender rule.
AddPrerenderAsync(kPrerenderingUrl);
// Wait for PrerenderHostRegistry to receive the cross-origin prerender
// request, and it should be ignored.
registry_observer.WaitForTrigger(kPrerenderingUrl);
EXPECT_FALSE(HasHostForUrl(kPrerenderingUrl));
ExpectFinalStatusForSpeculationRule(
PrerenderFinalStatus::kCrossSiteNavigationInInitialNavigation);
// Cross-check that in case of cross-origin navigation the eligibility
// reason points to kCrossOrigin.
ASSERT_TRUE(NavigateToURL(shell(), kPrerenderingUrl));
ExpectPreloadingAttemptUkm({attempt_ukm_entry_builder().BuildEntry(
PrimaryPageSourceId(), PreloadingType::kPrerender,
PreloadingEligibility::kCrossOrigin,
PreloadingHoldbackStatus::kUnspecified,
PreloadingTriggeringOutcome::kUnspecified,
PreloadingFailureReason::kUnspecified,
/*accurate=*/true,
/*ready_time=*/std::nullopt,
blink::mojom::SpeculationEagerness::kEager)});
}
// Tests that same-site cross-origin navigation by speculation rules is not
// allowed with the feature enabled but without opt-in.
IN_PROC_BROWSER_TEST_F(
PrerenderBrowserTest,
SameSiteCrossOriginNavigationSpeculationRulesWithoutOptInHeader) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl =
GetSameSiteCrossOriginUrl("/empty.html?samesitecrossorigin");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Add a same-site cross-origin prerender rule.
test::PrerenderHostRegistryObserver registry_observer(*web_contents_impl());
AddPrerenderAsync(kPrerenderingUrl);
// Wait for PrerenderHostRegistry to receive the same-site cross-origin
// prerender request, but it will be ignored because the opt-in header is
// missing.
registry_observer.WaitForTrigger(kPrerenderingUrl);
// Navigate to the prerendering URL. This should result in regular navigation,
// not prerender activation.
NavigatePrimaryPage(kPrerenderingUrl);
ExpectFinalStatusForSpeculationRule(
PrerenderFinalStatus::
kSameSiteCrossOriginNavigationNotOptInInInitialNavigation);
}
// Tests that same-site cross-origin redirection by speculation rules with the
// feature enabled but without opt-in.
IN_PROC_BROWSER_TEST_F(
PrerenderBrowserTest,
SameSiteCrossOriginRedirectionSpeculationRulesWithoutOptInHeader) {
// Navigate to an initial page.
const GURL kInitialUrl = GetUrl("/empty.html");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start prerendering a URL that causes cross-origin redirection. The
// cross-origin redirection should fail prerendering without an opt-in header.
const GURL kRedirectedUrl =
GetSameSiteCrossOriginUrl("/empty.html?samesitecrossorigin");
const GURL kPrerenderingUrl =
GetUrl("/server-redirect?" + kRedirectedUrl.spec());
test::PrerenderHostObserver host_observer(*web_contents_impl(),
kPrerenderingUrl);
AddPrerenderAsync(kPrerenderingUrl);
host_observer.WaitForDestroyed();
EXPECT_EQ(GetRequestCount(kPrerenderingUrl), 1);
EXPECT_EQ(GetRequestCount(kRedirectedUrl), 1);
EXPECT_FALSE(HasHostForUrl(kPrerenderingUrl));
EXPECT_FALSE(HasHostForUrl(kRedirectedUrl));
ExpectFinalStatusForSpeculationRule(
PrerenderFinalStatus::
kSameSiteCrossOriginRedirectNotOptInInInitialNavigation);
}
// Tests that same-site cross-origin redirection with credentialed prerender by
// speculation rules with the feature enabled but the redirected page without
// opt-in. This test verifies a case which is a.test -> a.test (credentialed
// prerender) -> b.a.test (no credentialed prerender).
IN_PROC_BROWSER_TEST_F(
PrerenderBrowserTest,
SameSiteCrossOriginCredentialedPrerenderRedirectionSpeculationRulesWithoutOptInHeader) {
// Navigate to an initial page.
const GURL kInitialUrl = GetUrl("/empty.html");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start prerendering a URL that causes cross-origin redirection. The
// cross-origin redirection should fail prerendering without an opt-in header.
const GURL kRedirectedUrl =
GetSameSiteCrossOriginUrl("/empty.html?samesitecrossorigin");
const GURL kPrerenderingUrl = GetUrl(
"/server-redirect-credentialed-prerender?" + kRedirectedUrl.spec());
test::PrerenderHostObserver host_observer(*web_contents_impl(),
kPrerenderingUrl);
AddPrerenderAsync(kPrerenderingUrl);
host_observer.WaitForDestroyed();
EXPECT_EQ(GetRequestCount(kPrerenderingUrl), 1);
EXPECT_EQ(GetRequestCount(kRedirectedUrl), 1);
EXPECT_FALSE(HasHostForUrl(kPrerenderingUrl));
EXPECT_FALSE(HasHostForUrl(kRedirectedUrl));
ExpectFinalStatusForSpeculationRule(
PrerenderFinalStatus::
kSameSiteCrossOriginRedirectNotOptInInInitialNavigation);
}
// Tests that same-site cross-origin redirection with credentialed prerender by
// speculation rules with the feature enabled but the redirected page without
// opt-in. This test verifies a case which is a.test -> b.a.test (credentialed
// prerender) -> b.a.test (no credentialed prerender)
IN_PROC_BROWSER_TEST_F(
PrerenderBrowserTest,
SameSiteCrossOriginCredentialedPrerenderRedirectionSpeculationRulesWithoutOptInHeader2) {
// Navigate to an initial page.
const GURL kInitialUrl = GetUrl("/empty.html");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start prerendering a URL that causes cross-origin redirection. The
// cross-origin redirection should fail prerendering without an opt-in header.
const GURL kRedirectedUrl =
GetSameSiteCrossOriginUrl("/empty.html?samesitecrossorigin");
const GURL kPrerenderingUrl = GetSameSiteCrossOriginUrl(
"/server-redirect-credentialed-prerender?" + kRedirectedUrl.spec());
test::PrerenderHostObserver host_observer(*web_contents_impl(),
kPrerenderingUrl);
AddPrerenderAsync(kPrerenderingUrl);
host_observer.WaitForDestroyed();
EXPECT_EQ(GetRequestCount(kPrerenderingUrl), 1);
EXPECT_EQ(GetRequestCount(kRedirectedUrl), 1);
EXPECT_FALSE(HasHostForUrl(kPrerenderingUrl));
EXPECT_FALSE(HasHostForUrl(kRedirectedUrl));
ExpectFinalStatusForSpeculationRule(
PrerenderFinalStatus::
kSameSiteCrossOriginRedirectNotOptInInInitialNavigation);
}
// Tests that same-site cross-origin navigation redirecting back to same-origin
// without opt-in.
IN_PROC_BROWSER_TEST_F(
PrerenderBrowserTest,
SameSiteCrossOriginNavigationBackToSameOriginWithoutOptInHeader) {
// Navigate to an initial page.
const GURL kInitialUrl = GetUrl("/empty.html");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start prerendering a URL that causes same-site cross-origin navigation and
// redirects back to the same-origin. This should not fail even without
// same-site cross-origin opt-in header.
const GURL kRedirectedUrl = GetUrl("/empty.html?samesitecrossorigin");
const GURL kPrerenderingUrl =
GetSameSiteCrossOriginUrl("/server-redirect?" + kRedirectedUrl.spec());
test::PrerenderHostObserver host_observer(*web_contents_impl(),
kPrerenderingUrl);
RedirectChainObserver redirect_chain_observer(*shell()->web_contents(),
kRedirectedUrl);
ASSERT_EQ(GetRequestCount(kPrerenderingUrl), 0);
ASSERT_EQ(GetRequestCount(kPrerenderingUrl), 0);
AddPrerender(kPrerenderingUrl);
EXPECT_EQ(GetRequestCount(kPrerenderingUrl), 1);
ASSERT_EQ(GetRequestCount(kPrerenderingUrl), 1);
ASSERT_EQ(2u, redirect_chain_observer.redirect_chain().size());
EXPECT_EQ(kPrerenderingUrl, redirect_chain_observer.redirect_chain()[0]);
EXPECT_EQ(kRedirectedUrl, redirect_chain_observer.redirect_chain()[1]);
NavigatePrimaryPage(kPrerenderingUrl);
ASSERT_EQ(web_contents()->GetLastCommittedURL(), kRedirectedUrl);
// Activating the prerendered page should not issue a request.
EXPECT_EQ(GetRequestCount(kRedirectedUrl), 1);
EXPECT_EQ(GetRequestCount(kPrerenderingUrl), 1);
ExpectFinalStatusForSpeculationRule(PrerenderFinalStatus::kActivated);
}
// Tests that cross-origin redirection in multiple redirections by speculation
// rules should be canceled.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
CrossSiteMultipleRedirectionSpeculationRules) {
// Navigate to an initial page.
const GURL kInitialUrl = GetUrl("/empty.html");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start prerendering a URL that causes cross-origin redirection. The
// cross-origin redirection should fail prerendering without an opt-in header.
const GURL kRedirectedUrl = GetSameSiteCrossOriginUrl(
"/prerender/prerender_with_opt_in_header.html?prerender");
const GURL kRedirectedUrl2 =
GetCrossSiteUrl("/server-redirect?" + kRedirectedUrl.spec());
const GURL kPrerenderingUrl =
GetUrl("/server-redirect?" + kRedirectedUrl2.spec());
test::PrerenderHostObserver host_observer(*web_contents_impl(),
kPrerenderingUrl);
AddPrerenderAsync(kPrerenderingUrl);
host_observer.WaitForDestroyed();
EXPECT_EQ(GetRequestCount(kPrerenderingUrl), 1);
EXPECT_EQ(GetRequestCount(kRedirectedUrl), 0);
EXPECT_EQ(GetRequestCount(kRedirectedUrl2), 0);
EXPECT_FALSE(HasHostForUrl(kPrerenderingUrl));
EXPECT_FALSE(HasHostForUrl(kRedirectedUrl));
EXPECT_FALSE(HasHostForUrl(kRedirectedUrl2));
ExpectFinalStatusForSpeculationRule(
PrerenderFinalStatus::kCrossSiteRedirectInInitialNavigation);
}
// Tests that same-site cross-origin navigation by speculation rules can be
// prerendered with the feature enabled.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
CheckSameSiteCrossOriginSpeculationRulesPrerender) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl =
GetSameSiteCrossOriginUrl("/prerender/prerender_with_opt_in_header.html");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Add a same-site cross-origin prerender rule.
ASSERT_EQ(GetRequestCount(kPrerenderingUrl), 0);
AddPrerender(kPrerenderingUrl);
EXPECT_EQ(GetRequestCount(kPrerenderingUrl), 1);
NavigatePrimaryPage(kPrerenderingUrl);
ASSERT_EQ(web_contents()->GetLastCommittedURL(), kPrerenderingUrl);
// Activating the prerendered page should not issue a request.
EXPECT_EQ(GetRequestCount(kPrerenderingUrl), 1);
ExpectFinalStatusForSpeculationRule(PrerenderFinalStatus::kActivated);
}
// Tests that same-site cross-origin redirection by speculation rules is
// allowed.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
SameSiteCrossOriginSpeculationRulesRedirection) {
// Navigate to an initial page.
const GURL kInitialUrl = GetUrl("/empty.html");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start prerendering a URL that causes same-origin redirection.
const GURL kRedirectedUrl = GetSameSiteCrossOriginUrl(
"/prerender/prerender_with_opt_in_header.html?prerender");
const GURL kPrerenderingUrl =
GetSameSiteCrossOriginUrl("/server-redirect?" + kRedirectedUrl.spec());
RedirectChainObserver redirect_chain_observer(*shell()->web_contents(),
kRedirectedUrl);
ASSERT_EQ(GetRequestCount(kPrerenderingUrl), 0);
ASSERT_EQ(GetRequestCount(kRedirectedUrl), 0);
AddPrerender(kPrerenderingUrl);
EXPECT_EQ(GetRequestCount(kPrerenderingUrl), 1);
EXPECT_EQ(GetRequestCount(kRedirectedUrl), 1);
ASSERT_EQ(2u, redirect_chain_observer.redirect_chain().size());
EXPECT_EQ(kPrerenderingUrl, redirect_chain_observer.redirect_chain()[0]);
EXPECT_EQ(kRedirectedUrl, redirect_chain_observer.redirect_chain()[1]);
// The prerender host should be registered for the initial request URL, not
// the redirected URL.
EXPECT_TRUE(HasHostForUrl(kPrerenderingUrl));
EXPECT_FALSE(HasHostForUrl(kRedirectedUrl));
RedirectChainObserver activation_redirect_chain_observer(
*shell()->web_contents(), kRedirectedUrl);
NavigationHandleObserver activation_observer(web_contents(),
kPrerenderingUrl);
NavigatePrimaryPage(kPrerenderingUrl);
ASSERT_EQ(1u, activation_redirect_chain_observer.redirect_chain().size());
EXPECT_EQ(kRedirectedUrl,
activation_redirect_chain_observer.redirect_chain()[0]);
ASSERT_EQ(web_contents()->GetLastCommittedURL(), kRedirectedUrl);
ExpectFinalStatusForSpeculationRule(PrerenderFinalStatus::kActivated);
// Activating the prerendered page should not issue a request.
EXPECT_EQ(GetRequestCount(kPrerenderingUrl), 1);
EXPECT_EQ(GetRequestCount(kRedirectedUrl), 1);
// Cross-check that in case redirection when the prerender navigates and
// user ends up navigating to the redirected URL. accurate_triggering is
// true.
ukm::SourceId ukm_source_id = activation_observer.next_page_ukm_source_id();
ExpectPreloadingAttemptUkm({attempt_ukm_entry_builder().BuildEntry(
ukm_source_id, PreloadingType::kPrerender,
PreloadingEligibility::kEligible, PreloadingHoldbackStatus::kAllowed,
PreloadingTriggeringOutcome::kSuccess,
PreloadingFailureReason::kUnspecified,
/*accurate=*/true,
/*ready_time=*/kMockElapsedTime,
blink::mojom::SpeculationEagerness::kEager)});
}
// Tests that multiple same-site cross-origin redirections by speculation rules
// is allowed, and only the terminal one is checked for the opt in header.
IN_PROC_BROWSER_TEST_F(
PrerenderBrowserTest,
SameSiteCrossOriginSpeculationRulesMultipleRedirections) {
// Navigate to an initial page.
const GURL kInitialUrl = GetUrl("/empty.html");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start prerendering a URL that causes same-origin redirection.
const GURL kRedirectedUrl = GetSameSiteCrossOriginUrl(
"/prerender/prerender_with_opt_in_header.html?prerender");
const GURL kRedirectedUrl2 =
GetSameSiteCrossOriginUrl("/server-redirect?" + kRedirectedUrl.spec());
const GURL kPrerenderingUrl =
GetSameSiteCrossOriginUrl("/server-redirect?" + kRedirectedUrl2.spec());
RedirectChainObserver redirect_chain_observer(*shell()->web_contents(),
kRedirectedUrl);
ASSERT_EQ(GetRequestCount(kPrerenderingUrl), 0);
ASSERT_EQ(GetRequestCount(kRedirectedUrl), 0);
ASSERT_EQ(GetRequestCount(kRedirectedUrl2), 0);
AddPrerender(kPrerenderingUrl);
EXPECT_EQ(GetRequestCount(kPrerenderingUrl), 1);
EXPECT_EQ(GetRequestCount(kRedirectedUrl), 1);
EXPECT_EQ(GetRequestCount(kRedirectedUrl2), 1);
ASSERT_EQ(3u, redirect_chain_observer.redirect_chain().size());
EXPECT_EQ(kPrerenderingUrl, redirect_chain_observer.redirect_chain()[0]);
EXPECT_EQ(kRedirectedUrl2, redirect_chain_observer.redirect_chain()[1]);
EXPECT_EQ(kRedirectedUrl, redirect_chain_observer.redirect_chain()[2]);
// The prerender host should be registered for the initial request URL, not
// the redirected URL.
EXPECT_TRUE(HasHostForUrl(kPrerenderingUrl));
EXPECT_FALSE(HasHostForUrl(kRedirectedUrl));
EXPECT_FALSE(HasHostForUrl(kRedirectedUrl2));
RedirectChainObserver activation_redirect_chain_observer(
*shell()->web_contents(), kRedirectedUrl);
NavigationHandleObserver activation_observer(web_contents(),
kPrerenderingUrl);
NavigatePrimaryPage(kPrerenderingUrl);
ASSERT_EQ(1u, activation_redirect_chain_observer.redirect_chain().size());
EXPECT_EQ(kRedirectedUrl,
activation_redirect_chain_observer.redirect_chain()[0]);
ASSERT_EQ(web_contents()->GetLastCommittedURL(), kRedirectedUrl);
ExpectFinalStatusForSpeculationRule(PrerenderFinalStatus::kActivated);
// Activating the prerendered page should not issue a request.
EXPECT_EQ(GetRequestCount(kPrerenderingUrl), 1);
EXPECT_EQ(GetRequestCount(kRedirectedUrl), 1);
EXPECT_EQ(GetRequestCount(kRedirectedUrl2), 1);
// Cross-check that in case redirection when the prerender navigates and user
// ends up navigating to the redirected URL. accurate_triggering is true.
ukm::SourceId ukm_source_id = activation_observer.next_page_ukm_source_id();
ExpectPreloadingAttemptUkm({attempt_ukm_entry_builder().BuildEntry(
ukm_source_id, PreloadingType::kPrerender,
PreloadingEligibility::kEligible, PreloadingHoldbackStatus::kAllowed,
PreloadingTriggeringOutcome::kSuccess,
PreloadingFailureReason::kUnspecified,
/*accurate=*/true,
/*ready_time=*/kMockElapsedTime,
blink::mojom::SpeculationEagerness::kEager)});
}
void PrerenderBrowserTest::TestEmbedderTriggerWithUnsupportedScheme(
const GURL& prerendering_url) {
const GURL initial_url = GetUrl("/empty.html");
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
ASSERT_FALSE(prerendering_url.SchemeIsHTTPOrHTTPS());
auto* preloading_data =
PreloadingData::GetOrCreateForWebContents(web_contents_impl());
PreloadingPredictor preloading_predictor(100, "Embedder");
PreloadingURLMatchCallback same_url_matcher =
PreloadingData::GetSameURLMatcher(prerendering_url);
PreloadingAttempt* preloading_attempt = preloading_data->AddPreloadingAttempt(
preloading_predictor, PreloadingType::kPrerender,
std::move(same_url_matcher),
web_contents_impl()->GetPrimaryMainFrame()->GetPageUkmSourceId());
// Start prerendering by embedder triggered prerendering.
std::unique_ptr<PrerenderHandle> prerender_handle =
AddEmbedderTriggeredPrerenderAsync(prerendering_url, preloading_attempt);
EXPECT_FALSE(prerender_handle);
histogram_tester().ExpectUniqueSample(
"Prerender.Experimental.PrerenderHostFinalStatus.Embedder_"
"EmbedderSuffixForTest",
PrerenderFinalStatus::kInvalidSchemeNavigation, 1);
// Navigate primary page to flush the metrics.
const GURL navigated_url = GetUrl("/empty.html?navigated");
ASSERT_TRUE(NavigateToURL(shell(), navigated_url));
auto attempt_ukm_entry_builder =
std::make_unique<test::PreloadingAttemptUkmEntryBuilder>(
preloading_predictor);
ExpectPreloadingAttemptUkm({attempt_ukm_entry_builder->BuildEntry(
PrimaryPageSourceId(), PreloadingType::kPrerender,
PreloadingEligibility::kHttpOrHttpsOnly,
PreloadingHoldbackStatus::kUnspecified,
PreloadingTriggeringOutcome::kUnspecified,
PreloadingFailureReason::kUnspecified,
/*accurate=*/false,
/*ready_time=*/std::nullopt,
/*eagerness=*/std::nullopt)});
}
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
EmbedderTrigger_UnsupportedScheme_ViewSource) {
const GURL prerendering_url =
GURL("view-source:" + GetUrl("/empty.html?prerender").spec());
TestEmbedderTriggerWithUnsupportedScheme(prerendering_url);
}
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
EmbedderTrigger_UnsupportedScheme_DataUrl) {
// The content is "<h1>Hello, World!</h1>".
const GURL prerendering_url(
"data:text/html,%3Ch1%3EHello%2C%20World%21%3C%2Fh1%3E");
TestEmbedderTriggerWithUnsupportedScheme(prerendering_url);
}
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
EmbedderTrigger_SameOriginRedirection) {
const GURL initial_url = GetUrl("/empty.html");
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
const GURL redirected_url_node_2 = GetUrl("/empty.html?prerender");
const GURL redirected_url_node_1 =
GetUrl("/server-redirect?" + redirected_url_node_2.spec());
const GURL prerender_initial_url =
GetUrl("/server-redirect?" + redirected_url_node_1.spec());
RedirectChainObserver redirect_chain_observer(*shell()->web_contents(),
redirected_url_node_2);
// Start prerendering by embedder triggered prerendering.
std::unique_ptr<PrerenderHandle> prerender_handle =
AddEmbedderTriggeredPrerender(prerender_initial_url);
ASSERT_EQ(3u, redirect_chain_observer.redirect_chain().size());
// Prerender is not canceled.
EXPECT_TRUE(HasHostForUrl(prerender_initial_url));
// Regression test for https://crbug.com/1211274. Make sure that we don't
// crash when activating a prerendered page which performed a same-origin
// redirect.
RedirectChainObserver activation_redirect_chain_observer(
*shell()->web_contents(), redirected_url_node_2);
test::PrerenderHostObserver prerender_observer(*web_contents_impl(),
prerender_initial_url);
prerender_helper()->NavigatePrimaryPageAsync(
prerender_initial_url,
ui::PageTransitionFromInt(ui::PAGE_TRANSITION_TYPED |
ui::PAGE_TRANSITION_FROM_ADDRESS_BAR));
prerender_observer.WaitForActivation();
ASSERT_EQ(1u, activation_redirect_chain_observer.redirect_chain().size());
EXPECT_EQ(redirected_url_node_2,
activation_redirect_chain_observer.redirect_chain()[0]);
}
// If there is a cross-origin url in the redirection chain, tests prerender
// should be canceled.
IN_PROC_BROWSER_TEST_F(
PrerenderBrowserTest,
EmbedderTrigger_CancelIfCrossOriginUrlInRedirectionChain) {
GURL initial_url = GetUrl("/empty.html");
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
// Prerendering a url that will be redirected to same_origin_redirected_url
// and then cross_origin_redirected_url.
GURL cross_origin_redirected_url = GetCrossSiteUrl("/empty.html");
GURL same_origin_redirected_url =
GetUrl("/server-redirect?" + cross_origin_redirected_url.spec());
GURL prerendering_initial_url =
GetUrl("/server-redirect?" + same_origin_redirected_url.spec());
RedirectChainObserver redirect_chain_observer(*shell()->web_contents(),
cross_origin_redirected_url);
// Start prerendering by embedder triggered prerendering.
std::unique_ptr<PrerenderHandle> prerender_handle =
AddEmbedderTriggeredPrerender(prerendering_initial_url);
histogram_tester().ExpectUniqueSample(
"Prerender.Experimental.PrerenderHostFinalStatus.Embedder_"
"EmbedderSuffixForTest",
PrerenderFinalStatus::kCrossSiteRedirectInInitialNavigation, 1);
EXPECT_FALSE(HasHostForUrl(prerendering_initial_url));
}
std::unique_ptr<PrerenderHandle>
PrerenderEmbedderTriggeredCrossOriginRedirectionPage(
WebContentsImpl& web_contents,
const GURL& prerendering_url,
const GURL& cross_origin_url) {
EXPECT_FALSE(url::IsSameOriginWith(prerendering_url, cross_origin_url));
RedirectChainObserver redirect_chain_observer{web_contents, cross_origin_url};
// Start prerendering by embedder triggered prerendering.
std::unique_ptr<PrerenderHandle> prerender_handle =
web_contents.StartPrerendering(
prerendering_url, PreloadingTriggerType::kEmbedder,
"EmbedderSuffixForTest",
/*additional_headers=*/net::HttpRequestHeaders(),
/*no_vary_search_hint=*/std::nullopt,
ui::PageTransitionFromInt(ui::PAGE_TRANSITION_TYPED |
ui::PAGE_TRANSITION_FROM_ADDRESS_BAR),
/*should_warm_up_compositor=*/false,
/*should_prepare_paint_tree=*/true,
PreloadingHoldbackStatus::kUnspecified,
PreloadPipelineInfo::Create(
/*planned_max_preloading_type=*/PreloadingType::kPrerender),
/*preloading_attempt=*/nullptr, /*url_match_predicate=*/{},
/*prerender_navigation_handle_callback=*/{});
EXPECT_TRUE(prerender_handle);
test::PrerenderTestHelper::WaitForPrerenderLoadCompletion(web_contents,
prerendering_url);
EXPECT_EQ(2u, redirect_chain_observer.redirect_chain().size());
return prerender_handle;
}
namespace {
class FrameDisplayStateChangedObserver : public WebContentsObserver {
public:
explicit FrameDisplayStateChangedObserver(RenderFrameHost& host)
: WebContentsObserver(WebContents::FromRenderFrameHost(&host)),
target_host_(&host) {}
void WaitForFrameDisplayStateChanged() {
if (changed_count_ > 0) {
changed_count_--;
} else {
base::RunLoop loop;
callback_ = loop.QuitClosure();
loop.Run();
}
}
void FrameDisplayStateChanged(RenderFrameHost* host,
bool is_display_none) override {
if (host == target_host_) {
if (callback_) {
std::move(callback_).Run();
} else {
changed_count_++;
}
}
}
int changed_count_ = 0;
const raw_ptr<RenderFrameHost> target_host_;
base::OnceClosure callback_;
};
} // namespace
// Tests that FrameOwnerProperties are in sync after activation.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, FrameOwnerPropertiesDisplayNone) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl =
GetUrl("/prerender/doc-with-display-none-iframe.html");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
EXPECT_TRUE(AddTestUtilJS(current_frame_host()));
// Start prerendering a document with a display:none iframe.
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
RenderFrameHost* prerender_frame_host = GetPrerenderedMainFrameHost(host_id);
EXPECT_TRUE(ExecJs(prerender_frame_host, "loaded;"));
// The iframe is at "/empty.html". It should be display none.
RenderFrameHost* iframe_host = FindRenderFrameHost(
prerender_frame_host->GetPage(), GetUrl("/empty.html"));
EXPECT_FALSE(prerender_frame_host->IsFrameDisplayNone());
EXPECT_TRUE(iframe_host->IsFrameDisplayNone());
// Activate.
NavigatePrimaryPage(kPrerenderingUrl);
ASSERT_EQ(web_contents()->GetLastCommittedURL(), kPrerenderingUrl);
// The frames should still have the same display properties.
EXPECT_FALSE(prerender_frame_host->IsFrameDisplayNone());
EXPECT_TRUE(iframe_host->IsFrameDisplayNone());
// Change the display properties.
FrameDisplayStateChangedObserver obs(*iframe_host);
EXPECT_TRUE(
ExecJs(prerender_frame_host,
"document.querySelector('iframe').style = 'display: block;'"));
obs.WaitForFrameDisplayStateChanged();
EXPECT_FALSE(prerender_frame_host->IsFrameDisplayNone());
EXPECT_FALSE(iframe_host->IsFrameDisplayNone());
}
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, TriggeredPrerenderUkm) {
ukm::TestAutoSetUkmRecorder ukm_recorder;
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/empty.html?prerender");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
ASSERT_EQ(web_contents()->GetLastCommittedURL(), kInitialUrl);
// PrerenderPageLoad metric should not be recorded yet.
EXPECT_EQ(0u,
ukm_recorder
.GetEntriesByName(ukm::builders::PrerenderPageLoad::kEntryName)
.size());
// Start a prerender.
ASSERT_TRUE(AddPrerender(kPrerenderingUrl));
// PrerenderPageLoad:TriggeredPrerender is recorded for the initiator page
// load.
const std::vector<raw_ptr<const ukm::mojom::UkmEntry, VectorExperimental>>
entries = ukm_recorder.GetEntriesByName(
ukm::builders::PrerenderPageLoad::kEntryName);
ASSERT_EQ(1u, entries.size());
EXPECT_EQ(web_contents()->GetPrimaryMainFrame()->GetPageUkmSourceId(),
entries.front()->source_id);
ukm_recorder.ExpectEntryMetric(
entries.front(),
ukm::builders::PrerenderPageLoad::kTriggeredPrerenderName, 1);
}
// Tests that background color in a prerendered page does not affect
// the primary page.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, ColorSchemeDarkInNonPrimaryPage) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/color-scheme-dark.html");
// Expect initial page background color to be white.
BackgroundColorChangeWaiter empty_page_background_waiter(web_contents());
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Wait for the page background to change to white.
empty_page_background_waiter.Wait();
{
// Now set up a mock observer for BackgroundColorChanged, to test if the
// mocked observer executes BackgroundColorChanged for the prerendered page.
testing::NiceMock<MockWebContentsObserver> background_color_observer(
web_contents());
EXPECT_CALL(background_color_observer, OnBackgroundColorChanged())
.Times(Exactly(0));
AddPrerender(kPrerenderingUrl);
}
BackgroundColorChangeWaiter prerendered_page_background_waiter(
web_contents());
// Now set up a mock observer for BackgroundColorChanged, to test if the
// mocked observer executes BackgroundColorChanged when activating the
// prerendered page.
testing::NiceMock<MockWebContentsObserver> background_color_observer(
web_contents());
EXPECT_CALL(background_color_observer, OnBackgroundColorChanged())
.Times(Exactly(1));
NavigatePrimaryPage(kPrerenderingUrl);
ASSERT_EQ(web_contents()->GetLastCommittedURL(), kPrerenderingUrl);
// Wait for the page background to change.
prerendered_page_background_waiter.Wait();
}
// TODO(b/335786567): Flaky on win-asan.
#if (BUILDFLAG(IS_WIN) && defined(ADDRESS_SANITIZER))
#define MAYBE_ThemeColorSchemeChangeInNonPrimaryPage \
DISABLED_ThemeColorSchemeChangeInNonPrimaryPage
#else
#define MAYBE_ThemeColorSchemeChangeInNonPrimaryPage \
ThemeColorSchemeChangeInNonPrimaryPage
#endif
// Tests that theme color in a prerendered page does not affect
// the primary page.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
MAYBE_ThemeColorSchemeChangeInNonPrimaryPage) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/theme_color.html");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
{
// Now set up a mock observer for DidChangeThemeColor, to test if the
// mocked observer executes DidChangeThemeColor for the prerendered page.
testing::NiceMock<MockWebContentsObserver> theme_color_observer(
web_contents());
EXPECT_CALL(theme_color_observer, DidChangeThemeColor()).Times(Exactly(0));
AddPrerender(kPrerenderingUrl);
}
ThemeChangeWaiter theme_change_waiter(web_contents());
testing::NiceMock<MockWebContentsObserver> theme_color_observer(
web_contents());
EXPECT_CALL(theme_color_observer, DidChangeThemeColor()).Times(Exactly(1));
NavigatePrimaryPage(kPrerenderingUrl);
ASSERT_EQ(web_contents()->GetLastCommittedURL(), kPrerenderingUrl);
theme_change_waiter.Wait();
}
// Tests that text autosizer works per page.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
TextAutosizerInfoChangeInNonPrimaryPage) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/title1.html");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
RenderFrameHostImpl* primary_frame_host = current_frame_host();
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
RenderFrameHostImpl* prerender_frame_host =
GetPrerenderedMainFrameHost(host_id);
// Update the autosizer page info in the prerendering page.
blink::mojom::TextAutosizerPageInfo prerender_page_info(
/*main_frame_width=*/320,
/*main_frame_layout_width=*/480,
/*device_scale_adjustment=*/1.f);
prerender_frame_host->TextAutosizerPageInfoChanged(
prerender_page_info.Clone());
// Only the prerendering page's autosizer info should be updated.
EXPECT_TRUE(prerender_page_info.Equals(
prerender_frame_host->GetPage().text_autosizer_page_info()));
EXPECT_FALSE(prerender_page_info.Equals(
primary_frame_host->GetPage().text_autosizer_page_info()));
// After being activated, the prerendered page becomes the primary page, so
// the page info of the primary page should equal `prerender_page_info`.
NavigatePrimaryPage(kPrerenderingUrl);
EXPECT_TRUE(prerender_page_info.Equals(
current_frame_host()->GetPage().text_autosizer_page_info()));
}
// Check that the prerendered page window.name is maintained after activation.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
VerifyFrameNameMaintainedAfterActivation) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/title1.html");
// 1. Load initiator page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// 2. Load prerender.
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
RenderFrameHostImpl* prerendered_render_frame_host =
GetPrerenderedMainFrameHost(host_id);
// 3. Set window.name.
ASSERT_TRUE(
ExecJs(prerendered_render_frame_host, "window.name = 'prerender_page'"));
EXPECT_EQ(prerendered_render_frame_host->GetFrameName(), "prerender_page");
EXPECT_EQ(current_frame_host()->GetFrameName(), "");
// 4. Activate prerender.
test::PrerenderHostObserver host_observer(*web_contents(), kPrerenderingUrl);
NavigatePrimaryPage(kPrerenderingUrl);
EXPECT_TRUE(host_observer.was_activated());
EXPECT_EQ(web_contents()->GetLastCommittedURL(), kPrerenderingUrl);
// 5. Ensure that the window.name is preserved.
EXPECT_EQ(current_frame_host()->GetFrameName(), "prerender_page");
}
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, ActivateWhileReloadingSubframe) {
const char kSubframePath[] = "/title1.html";
net::test_server::ControllableHttpResponse first_response(
embedded_test_server(), kSubframePath);
net::test_server::ControllableHttpResponse second_response(
embedded_test_server(), kSubframePath);
ASSERT_TRUE(embedded_test_server()->Start());
const GURL kInitialUrl = embedded_test_server()->GetURL("/empty.html");
const GURL kPrerenderingUrl =
embedded_test_server()->GetURL("/page_with_iframe.html");
const GURL kSubframeUrl = embedded_test_server()->GetURL(kSubframePath);
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start a prerender.
test::PrerenderHostRegistryObserver registry_observer(*web_contents_impl());
AddPrerenderAsync(kPrerenderingUrl);
// Handle a response for the subframe main resource.
first_response.WaitForRequest();
first_response.Send(net::HTTP_OK, "");
first_response.Done();
// Now we can wait for the prerendering navigation finishes.
registry_observer.WaitForTrigger(kPrerenderingUrl);
FrameTreeNodeId host_id = GetHostForUrl(kPrerenderingUrl);
WaitForPrerenderLoadCompletion(host_id);
RenderFrameHostImpl* prerender_rfh = GetPrerenderedMainFrameHost(host_id);
RenderFrameHostImpl* child_rfh =
prerender_rfh->child_at(0)->current_frame_host();
EXPECT_EQ(child_rfh->GetLastCommittedURL(), kSubframeUrl);
// Reload the iframe.
EXPECT_TRUE(ExecJs(child_rfh, "window.location.reload();"));
second_response.WaitForRequest();
// Do not finish the second response to execute activation during the reload.
// Ensure that activation works even while the iframe is under the reload.
TestNavigationObserver nav_observer(web_contents());
EXPECT_TRUE(
ExecJs(web_contents(), JsReplace("location = $1", kPrerenderingUrl)));
second_response.Send(net::HTTP_OK, "");
second_response.Done();
nav_observer.WaitForNavigationFinished();
}
// Check that the inactive RFH shouldn't update UserActivation.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, DoNotUpdateUserActivationState) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/title1.html");
// 1. Load initiator page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// 2. Load prerender.
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
RenderFrameHostImpl* prerendered_rfh = GetPrerenderedMainFrameHost(host_id);
EXPECT_FALSE(
current_frame_host()->frame_tree_node()->HasStickyUserActivation());
EXPECT_FALSE(prerendered_rfh->frame_tree_node()->HasStickyUserActivation());
// 3. Try to set the user activation bits to the prerendered RFH.
prerendered_rfh->UpdateUserActivationState(
blink::mojom::UserActivationUpdateType::kNotifyActivation,
blink::mojom::UserActivationNotificationType::kTest);
EXPECT_FALSE(prerendered_rfh->frame_tree_node()->HasStickyUserActivation());
EXPECT_FALSE(prerendered_rfh->HasTransientUserActivation());
EXPECT_FALSE(
current_frame_host()->frame_tree_node()->HasStickyUserActivation());
EXPECT_FALSE(
current_frame_host()->frame_tree_node()->HasTransientUserActivation());
// 4. Set the user activation bits to the primary RFH.
current_frame_host()->UpdateUserActivationState(
blink::mojom::UserActivationUpdateType::kNotifyActivation,
blink::mojom::UserActivationNotificationType::kTest);
EXPECT_TRUE(
current_frame_host()->frame_tree_node()->HasStickyUserActivation());
EXPECT_FALSE(prerendered_rfh->frame_tree_node()->HasStickyUserActivation());
}
// Tests that prerendering is cancelled when a mixed content subframe is
// detected.
IN_PROC_BROWSER_TEST_P(PrerenderTargetAgnosticBrowserTest, MixedContent) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/empty.html?prerendering");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Make a prerendered page.
FrameTreeNodeId host_id = prerender_helper()->AddPrerender(
kPrerenderingUrl, /*eagerness=*/std::nullopt, GetTargetHint());
auto* prerender_web_contents = WebContents::FromFrameTreeNodeId(host_id);
auto* prerendered_rfh =
test::PrerenderTestHelper::GetPrerenderedMainFrameHost(
*prerender_web_contents, host_id);
CHECK(prerendered_rfh);
EXPECT_TRUE(AddTestUtilJS(prerendered_rfh));
test::PrerenderHostObserver host_observer(*prerender_web_contents, host_id);
// Make a mixed content iframe.
std::ignore =
ExecJs(prerendered_rfh,
"add_iframe_async('http://a.test/empty.html?prerendering')",
EvalJsOptions::EXECUTE_SCRIPT_NO_RESOLVE_PROMISES);
host_observer.WaitForDestroyed();
if (GetTargetHint() == "_blank") {
EXPECT_FALSE(prerender_helper()->HasNewTabHandle(host_id));
} else {
EXPECT_TRUE(prerender_helper()
->GetHostForUrl(*prerender_web_contents, kPrerenderingUrl)
.is_null());
}
ExpectFinalStatusForSpeculationRule(PrerenderFinalStatus::kMixedContent);
}
// Check that the Content-Security-Policy set via HTTP header applies after the
// activation. This test verifies that that the web sandbox flags value is none.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
ActivatePageWithCspHeaderFrameSrc) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl =
GetUrl("/set-header?Content-Security-Policy: frame-src 'none'");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
RenderFrameHostImpl* prerendered_render_frame_host =
GetPrerenderedMainFrameHost(host_id);
// Check that CSP was set on the prerendered page prior to activation.
{
const std::vector<network::mojom::ContentSecurityPolicyPtr>& root_csp_pre =
prerendered_render_frame_host->policy_container_host()
->policies()
.content_security_policies;
EXPECT_EQ(1u, root_csp_pre.size());
EXPECT_EQ("frame-src 'none'", root_csp_pre[0]->header->header_value);
EXPECT_EQ(prerendered_render_frame_host->active_sandbox_flags(),
network::mojom::WebSandboxFlags::kNone);
}
test::PrerenderHostObserver host_observer(*web_contents(), kPrerenderingUrl);
NavigatePrimaryPage(kPrerenderingUrl);
EXPECT_TRUE(host_observer.was_activated());
EXPECT_EQ(web_contents()->GetLastCommittedURL(), kPrerenderingUrl);
// Check that CSP was set on the prerendered page after activation.
{
const std::vector<network::mojom::ContentSecurityPolicyPtr>& root_csp_post =
current_frame_host()
->policy_container_host()
->policies()
.content_security_policies;
EXPECT_EQ(1u, root_csp_post.size());
EXPECT_EQ("frame-src 'none'", root_csp_post[0]->header->header_value);
EXPECT_EQ(current_frame_host()->active_sandbox_flags(),
network::mojom::WebSandboxFlags::kNone);
EXPECT_EQ(static_cast<WebContentsImpl*>(web_contents())
->GetPrimaryFrameTree()
.root()
->active_sandbox_flags(),
network::mojom::WebSandboxFlags::kNone);
}
}
// Check that the Content-Security-Policy set via HTTP header applies after the
// activation. This test verifies that that the web sandbox flags value is set
// to allow scripts.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
ActivatePageWithCspHeaderSandboxFlags) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl =
GetUrl("/set-header?Content-Security-Policy: sandbox allow-scripts");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
RenderFrameHostImpl* prerendered_render_frame_host =
GetPrerenderedMainFrameHost(host_id);
// Check that CSP was set on the prerendered page prior to activation.
{
const std::vector<network::mojom::ContentSecurityPolicyPtr>& root_csp_pre =
prerendered_render_frame_host->policy_container_host()
->policies()
.content_security_policies;
EXPECT_EQ(1u, root_csp_pre.size());
EXPECT_EQ("sandbox allow-scripts", root_csp_pre[0]->header->header_value);
EXPECT_EQ(prerendered_render_frame_host->active_sandbox_flags(),
network::mojom::WebSandboxFlags::kAll &
~network::mojom::WebSandboxFlags::kScripts &
~network::mojom::WebSandboxFlags::kAutomaticFeatures);
}
test::PrerenderHostObserver host_observer(*web_contents(), kPrerenderingUrl);
NavigatePrimaryPage(kPrerenderingUrl);
EXPECT_TRUE(host_observer.was_activated());
EXPECT_EQ(web_contents()->GetLastCommittedURL(), kPrerenderingUrl);
// Check that CSP was set on the prerendered page after activation.
{
const std::vector<network::mojom::ContentSecurityPolicyPtr>& root_csp_post =
current_frame_host()
->policy_container_host()
->policies()
.content_security_policies;
EXPECT_EQ(1u, root_csp_post.size());
EXPECT_EQ("sandbox allow-scripts", root_csp_post[0]->header->header_value);
EXPECT_EQ(current_frame_host()->active_sandbox_flags(),
network::mojom::WebSandboxFlags::kAll &
~network::mojom::WebSandboxFlags::kScripts &
~network::mojom::WebSandboxFlags::kAutomaticFeatures);
EXPECT_EQ(static_cast<WebContentsImpl*>(web_contents())
->GetPrimaryFrameTree()
.root()
->active_sandbox_flags(),
network::mojom::WebSandboxFlags::kAll &
~network::mojom::WebSandboxFlags::kScripts &
~network::mojom::WebSandboxFlags::kAutomaticFeatures);
}
}
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, VerifyPrerenderProcessVisibility) {
// Navigate the primary main frame to an initial page.
const GURL kInitialUrl = GetUrl("/empty.html?initial");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start a prerender.
const GURL kPrerenderingUrl = GetUrl("/empty.html?prerender");
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
RenderFrameHost* prerender_frame_host = GetPrerenderedMainFrameHost(host_id);
RenderProcessHost* prerender_process_host =
prerender_frame_host->GetProcess();
ASSERT_NE(prerender_frame_host, nullptr);
// Ensure that a prerender process is backgrounded. This will put prerender
// processes in lower priority compared to other active processes. (See
// https://crbug.com/1211665)
EXPECT_TRUE(prerender_process_host->GetPriority() ==
base::Process::Priority::kBestEffort);
// Activate the prerendered page.
test::PrerenderHostObserver host_observer(*web_contents(), kPrerenderingUrl);
NavigatePrimaryPage(kPrerenderingUrl);
EXPECT_TRUE(host_observer.was_activated());
// Expect the change in the ChildProcessLauncherPriority to increase priority.
EXPECT_NE(prerender_process_host->GetPriority(),
base::Process::Priority::kBestEffort);
}
class PrerenderRequestHeadersBrowserTest : public PrerenderBrowserTest {
public:
PrerenderRequestHeadersBrowserTest() = default;
~PrerenderRequestHeadersBrowserTest() override = default;
void SetUp() override {
ssl_server().RegisterRequestHandler(
base::BindRepeating(&HandleCorsRequest));
PrerenderBrowserTest::SetUp();
}
static std::unique_ptr<net::test_server::HttpResponse> HandleCorsRequest(
const net::test_server::HttpRequest& request) {
// The "Purpose: prefetch" header shouldn't cause CORS preflights.
EXPECT_NE(request.method_string, "OPTIONS");
// Ignore if the request is not cross origin.
//
// Note: Checking the origin of `request.GetURL()` doesn't work here because
// the host part of the URL is translated (e.g., "a.test" to "127.0.0.1")
// based on the host resolver rule before this point.
if (request.relative_url.find("cors") == std::string::npos) {
return nullptr;
}
// Serves a fake response with the ACAO header.
auto response = std::make_unique<net::test_server::BasicHttpResponse>();
response->AddCustomHeader("Access-Control-Allow-Origin", "*");
response->set_code(net::HTTP_OK);
response->set_content("");
response->set_content_type("text/plain");
return response;
}
bool TestPurposePrefetchHeader(const GURL& url) {
net::test_server::HttpRequest::HeaderMap headers = GetRequestHeaders(url);
auto it = headers.find(blink::kPurposeHeaderName);
if (it == headers.end()) {
return false;
}
EXPECT_EQ(blink::kSecPurposePrefetchHeaderValue, it->second);
it = headers.find(blink::kSecPurposeHeaderName);
if (it == headers.end()) {
return false;
}
EXPECT_EQ(blink::kSecPurposePrefetchPrerenderHeaderValue, it->second);
return true;
}
bool HasSecSpeculationTagsHeader(const GURL& url) {
net::test_server::HttpRequest::HeaderMap headers = GetRequestHeaders(url);
return headers.contains(blink::kSecSpeculationTagsHeaderName);
}
std::string GetSecSpeculationTagsHeader(const GURL& url) {
net::test_server::HttpRequest::HeaderMap headers = GetRequestHeaders(url);
EXPECT_TRUE(headers.contains(blink::kSecSpeculationTagsHeaderName));
return headers[blink::kSecSpeculationTagsHeaderName];
}
};
// Tests that a request for the initial prerender navigation has the
// Purpose, Sec-Purpose, and Sec-Speculation-Tags headers.
// TODO(nhiroki): Move this test to WPT.
IN_PROC_BROWSER_TEST_F(PrerenderRequestHeadersBrowserTest, InitialNavigation) {
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), GetUrl("/empty.html")));
// Start prerendering.
const GURL kPrerenderingUrl = GetUrl("/empty.html?prerender");
AddPrerender(kPrerenderingUrl);
// The prerender request should have the headers.
EXPECT_TRUE(TestPurposePrefetchHeader(kPrerenderingUrl));
EXPECT_TRUE(HasSecSpeculationTagsHeader(kPrerenderingUrl));
EXPECT_EQ(GetSecSpeculationTagsHeader(kPrerenderingUrl), "null");
}
// Tests that a request for the initial prerender navigation has the
// Purpose and Sec-Purpose headers, but not the Sec-Speculation-Tags header.
IN_PROC_BROWSER_TEST_F(PrerenderRequestHeadersBrowserTest,
InitialNavigation_Embedder) {
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), GetUrl("/empty.html")));
// Start prerendering.
const GURL prerender_url = GetUrl("/empty.html?prerender");
std::unique_ptr<PrerenderHandle> prerender_handle =
AddEmbedderTriggeredPrerender(prerender_url);
EXPECT_TRUE(prerender_handle);
// The embedder-triggered prerender request should have the purpose headers,
// but not the Sec-Speculation-Tags header.
EXPECT_TRUE(TestPurposePrefetchHeader(prerender_url));
EXPECT_FALSE(HasSecSpeculationTagsHeader(prerender_url));
}
// Tests that a redirected request for the initial prerender navigation has the
// Purpose, Sec-Purpose, and Sec-Speculation-Tags headers.
// TODO(nhiroki): Move this test to WPT.
IN_PROC_BROWSER_TEST_F(PrerenderRequestHeadersBrowserTest,
RedirectionOnInitialNavigation) {
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), GetUrl("/empty.html")));
// Start prerendering a URL that causes same-origin redirection.
const GURL kRedirectedUrl = GetUrl("/empty.html?prerender");
const GURL kPrerenderingUrl =
GetUrl("/server-redirect?" + kRedirectedUrl.spec());
RedirectChainObserver redirect_chain_observer(*shell()->web_contents(),
kRedirectedUrl);
AddPrerender(kPrerenderingUrl);
ASSERT_EQ(2u, redirect_chain_observer.redirect_chain().size());
EXPECT_EQ(kPrerenderingUrl, redirect_chain_observer.redirect_chain()[0]);
EXPECT_EQ(kRedirectedUrl, redirect_chain_observer.redirect_chain()[1]);
// Both the initial request and the redirected request should have the
// headers.
EXPECT_TRUE(TestPurposePrefetchHeader(kPrerenderingUrl));
EXPECT_TRUE(HasSecSpeculationTagsHeader(kPrerenderingUrl));
EXPECT_EQ(GetSecSpeculationTagsHeader(kPrerenderingUrl), "null");
EXPECT_TRUE(TestPurposePrefetchHeader(kRedirectedUrl));
EXPECT_TRUE(HasSecSpeculationTagsHeader(kRedirectedUrl));
EXPECT_EQ(GetSecSpeculationTagsHeader(kRedirectedUrl), "null");
}
// Tests that requests from a prerendered page have the Purpose and
// Sec-Purpose headers, but not the Sec-Speculation-Tags header.
// TODO(nhiroki): Move this test to WPT.
IN_PROC_BROWSER_TEST_F(PrerenderRequestHeadersBrowserTest, ResourceRequests) {
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), GetUrl("/empty.html")));
// Start prerendering.
const GURL kPrerenderingUrl =
GetUrl("/prerender/purpose_prefetch_header.html");
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
RenderFrameHostWrapper prerender_main_frame(
GetPrerenderedMainFrameHost(host_id));
// The prerender request should have the "Purpose: prefetch" header.
TestPurposePrefetchHeader(kPrerenderingUrl);
EXPECT_TRUE(HasSecSpeculationTagsHeader(kPrerenderingUrl));
EXPECT_EQ(GetSecSpeculationTagsHeader(kPrerenderingUrl), "null");
// Issue iframe and subresource requests in the prerendered page.
EXPECT_TRUE(ExecJs(prerender_main_frame.get(), "run('before');",
EvalJsOptions::EXECUTE_SCRIPT_NO_USER_GESTURE));
// Requests from the prerendered page should have the purpose headers, but not
// the Sec-Speculation-Tags header.
std::vector<GURL> request_urls1 = {
GetUrl("/prerender/purpose_prefetch_header_iframe.html?before"),
GetUrl("/prerender/missing.jpg?before"),
GetUrl("/prerender/missing.txt?before"),
GetUrl("/empty.html?before"),
GetUrl("/prerender/iframe-missing.jpg?before"),
GetUrl("/prerender/iframe-missing.txt?before")};
for (const GURL& url : request_urls1) {
EXPECT_TRUE(TestPurposePrefetchHeader(url));
EXPECT_FALSE(HasSecSpeculationTagsHeader(url));
}
// Issue a cross-origin subresource request in the prerendered page. The
// request should have the purpose headers, but not the Sec-Speculation-Tags
// headers.
GURL cross_origin_url1 =
GetCrossSiteUrl("/prerender/cors-missing.txt?before");
EXPECT_TRUE(ExecJs(prerender_main_frame.get(),
"request('" + cross_origin_url1.spec() + "');",
EvalJsOptions::EXECUTE_SCRIPT_NO_USER_GESTURE));
EXPECT_TRUE(TestPurposePrefetchHeader(cross_origin_url1));
EXPECT_FALSE(HasSecSpeculationTagsHeader(cross_origin_url1));
// Activate the prerendered page.
test::PrerenderHostObserver host_observer(*web_contents(), kPrerenderingUrl);
NavigatePrimaryPage(kPrerenderingUrl);
EXPECT_TRUE(host_observer.was_activated());
// Issue iframe and subresource requests in the activated page.
EXPECT_TRUE(ExecJs(prerender_main_frame.get(), "run('after');",
EvalJsOptions::EXECUTE_SCRIPT_NO_USER_GESTURE));
// Requests from the activated page should not have the headers.
std::vector<GURL> request_urls2 = {
GetUrl("/prerender/purpose_prefetch_header_iframe.html?after"),
GetUrl("/prerender/missing.jpg?after"),
GetUrl("/prerender/missing.txt?after"),
GetUrl("/empty.html?after"),
GetUrl("/prerender/iframe-missing.jpg?after"),
GetUrl("/prerender/iframe-missing.txt?after")};
for (const GURL& url : request_urls2) {
EXPECT_FALSE(TestPurposePrefetchHeader(url));
EXPECT_FALSE(HasSecSpeculationTagsHeader(url));
}
// Issue a cross-origin subresource request in the activated page. The request
// should not have the headers.
GURL cross_origin_url2 = GetCrossSiteUrl("/prerender/cors-missing.txt?after");
EXPECT_TRUE(ExecJs(prerender_main_frame.get(),
"request('" + cross_origin_url2.spec() + "');",
EvalJsOptions::EXECUTE_SCRIPT_NO_USER_GESTURE));
EXPECT_FALSE(TestPurposePrefetchHeader(cross_origin_url2));
EXPECT_FALSE(HasSecSpeculationTagsHeader(cross_origin_url2));
}
// Tests that a request for main frame navigation in a prerendered page has the
// Purpose and Sec-Purpose headers, but not the Sec-Speculation-Tags header.
IN_PROC_BROWSER_TEST_F(PrerenderRequestHeadersBrowserTest,
MainFrameNavigation) {
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), GetUrl("/empty.html")));
// Start prerendering.
const GURL prerender_url = GetUrl("/empty.html?prerender");
FrameTreeNodeId host_id = AddPrerender(prerender_url);
ASSERT_TRUE(host_id);
// The prerender request should have the headers.
EXPECT_TRUE(TestPurposePrefetchHeader(prerender_url));
EXPECT_TRUE(HasSecSpeculationTagsHeader(prerender_url));
EXPECT_EQ(GetSecSpeculationTagsHeader(prerender_url), "null");
// Navigate the main frame in the prerendered page.
const GURL next_url = GetUrl("/empty.html?next");
TestNavigationManager navigation_observer(web_contents(), next_url);
NavigatePrerenderedPage(host_id, next_url);
ASSERT_TRUE(navigation_observer.WaitForNavigationFinished());
EXPECT_TRUE(navigation_observer.was_successful());
// The main frame navigation request should have the purpose headers, but not
// the Sec-Speculation-Tags header.
EXPECT_TRUE(TestPurposePrefetchHeader(next_url));
EXPECT_FALSE(HasSecSpeculationTagsHeader(next_url));
}
IN_PROC_BROWSER_TEST_F(PrerenderRequestHeadersBrowserTest,
SpeculationRulesTagsMergingForEagerCandidates) {
const GURL initial_url =
GetUrl("/prerender/multiple_prerender_with_tags.html");
const GURL prerender_url = GetUrl("/prerender/empty.html");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
WaitForPrerenderLoadCompletion(prerender_url);
EXPECT_TRUE(HasSecSpeculationTagsHeader(prerender_url));
EXPECT_EQ(GetSecSpeculationTagsHeader(prerender_url), "\"tag1\", \"tag2\"");
}
IN_PROC_BROWSER_TEST_F(PrerenderRequestHeadersBrowserTest,
SpeculationRulesTagForSameSiteCrossOrigin) {
const GURL initial_url = GetUrl("/prerender/empty.html");
const GURL prerender_url =
GetSameSiteCrossOriginUrl("/prerender/prerender_with_opt_in_header.html");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
FrameTreeNodeId host_id = AddPrerenderWithTags(prerender_url, "tag1");
auto* prerendered_rfh = GetPrerenderedMainFrameHost(host_id);
EXPECT_TRUE(prerendered_rfh != nullptr);
EXPECT_TRUE(HasSecSpeculationTagsHeader(prerender_url));
EXPECT_EQ(GetSecSpeculationTagsHeader(prerender_url), "\"tag1\"");
}
// This prefetch test is tentatively implemented here to reuse the test infra.
// TODO(crbug.com/381687257): Move this test to prefetch browser tests.
IN_PROC_BROWSER_TEST_F(PrerenderRequestHeadersBrowserTest, Prefetch) {
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), GetUrl("/empty.html")));
test::TestPrefetchWatcher test_prefetch_watcher;
// Start prefetching.
const GURL prefetch_url = GetUrl("/empty.html?prefetch");
AddPrefetchAsync(prefetch_url);
test_prefetch_watcher.WaitUntilPrefetchResponseCompleted(
static_cast<RenderFrameHostImpl*>(
shell()->web_contents()->GetPrimaryMainFrame())
->GetDocumentToken(),
prefetch_url);
EXPECT_TRUE(HasSecSpeculationTagsHeader(prefetch_url));
EXPECT_EQ(GetSecSpeculationTagsHeader(prefetch_url), "null");
}
// Test that there is no tags merging if both of the candidates are enacted.
IN_PROC_BROWSER_TEST_F(PrerenderRequestHeadersBrowserTest,
SpeculationRulesTagsMergingForNonEagerCandidates) {
#if !BUILDFLAG(IS_ANDROID)
const GURL initial_url = GetUrl(
"/prerender/multiple_prerender_with_tags_and_different_eagerness.html");
const GURL prerender_url = GetUrl("/prerender/empty.html");
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
InsertAnchor(prerender_url);
PointerDownToAnchor(prerender_url);
WaitForPrerenderLoadCompletion(prerender_url);
EXPECT_TRUE(HasSecSpeculationTagsHeader(prerender_url));
EXPECT_EQ(GetSecSpeculationTagsHeader(prerender_url),
"\"conservative\", \"moderate\"");
#else
// Android doesn't support pointer interaction.
GTEST_SKIP();
#endif // BUILDFLAG(IS_ANDROID)
}
// Test that there is no tags merging if only one of the candidates is enacted.
IN_PROC_BROWSER_TEST_F(PrerenderRequestHeadersBrowserTest,
SpeculationRulesTagsNoMergingForNonEagerCandidates) {
#if !BUILDFLAG(IS_ANDROID)
const GURL initial_url = GetUrl(
"/prerender/multiple_prerender_with_tags_and_different_eagerness.html");
const GURL prerender_url = GetUrl("/prerender/empty.html");
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
InsertAnchor(prerender_url);
PointerHoverToAnchor(prerender_url);
WaitForPrerenderLoadCompletion(prerender_url);
EXPECT_TRUE(HasSecSpeculationTagsHeader(prerender_url));
EXPECT_EQ(GetSecSpeculationTagsHeader(prerender_url), "\"moderate\"");
#else
// Android doesn't support pointer interaction.
GTEST_SKIP();
#endif // BUILDFLAG(IS_ANDROID)
}
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, EnterFullscreen) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/empty.html?prerendering");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start a prerender.
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
auto* prerendered_rfh = GetPrerenderedMainFrameHost(host_id);
// We should disallow to enter Fullscreen by the inactive RFH.
prerendered_rfh->EnterFullscreen(
blink::mojom::FullscreenOptions::New(),
base::BindOnce([](bool value) { EXPECT_FALSE(value); }));
EXPECT_FALSE(web_contents_impl()->IsFullscreen());
}
namespace {
class TestJavaScriptDialogManager : public JavaScriptDialogManager,
public WebContentsDelegate {
public:
TestJavaScriptDialogManager() = default;
~TestJavaScriptDialogManager() override = default;
// WebContentsDelegate overrides
JavaScriptDialogManager* GetJavaScriptDialogManager(
WebContents* source) override {
return this;
}
// JavaScriptDialogManager overrides
void RunJavaScriptDialog(WebContents* web_contents,
RenderFrameHost* render_frame_host,
JavaScriptDialogType dialog_type,
const std::u16string& message_text,
const std::u16string& default_prompt_text,
DialogClosedCallback callback,
bool* did_suppress_message) override {}
void RunBeforeUnloadDialog(WebContents* web_contents,
RenderFrameHost* render_frame_host,
bool is_reload,
DialogClosedCallback callback) override {}
void CancelDialogs(WebContents* web_contents, bool reset_state) override {
cancel_dialogs_called_ = true;
}
bool cancel_dialogs_called() { return cancel_dialogs_called_; }
private:
bool cancel_dialogs_called_ = false;
};
class PrerenderWithRenderDocumentBrowserTest : public PrerenderBrowserTest {
public:
PrerenderWithRenderDocumentBrowserTest() {
InitAndEnableRenderDocumentFeature(
&feature_list_,
GetRenderDocumentLevelName(RenderDocumentLevel::kSubframe));
}
~PrerenderWithRenderDocumentBrowserTest() override = default;
private:
base::test::ScopedFeatureList feature_list_;
};
} // namespace
IN_PROC_BROWSER_TEST_F(
PrerenderWithRenderDocumentBrowserTest,
ModalDialogShouldNotBeDismissedAfterPrerenderSubframeNavigation) {
const GURL kPrerenderingUrl = GetUrl("/title1.html");
const GURL kSubframeUrl1 = GetUrl("/empty.html");
const GURL kSubframeUrl2 = GetUrl("/title2.html");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), GetUrl("/empty.html")));
// Start prerendering.
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
RenderFrameHost* prerender_rfh = GetPrerenderedMainFrameHost(host_id);
CHECK(prerender_rfh);
AddTestUtilJS(prerender_rfh);
// Add subframe in prerendering page.
ASSERT_TRUE(
ExecJs(prerender_rfh, JsReplace("add_iframe($1)", kSubframeUrl1)));
// Setup test dialog manager and create dialog.
TestJavaScriptDialogManager dialog_manager;
web_contents_impl()->SetDelegate(&dialog_manager);
web_contents_impl()->RunJavaScriptDialog(
web_contents_impl()->GetPrimaryMainFrame(), u"", u"",
JAVASCRIPT_DIALOG_TYPE_ALERT, false, base::NullCallback());
// Navigate subframe (with render document enabled, this should cause a RFH
// swap).
TestNavigationManager subframe_nav_manager(web_contents(), kSubframeUrl2);
ASSERT_TRUE(ExecJs(
prerender_rfh,
JsReplace("document.querySelector('iframe').src = $1", kSubframeUrl2)));
ASSERT_TRUE(subframe_nav_manager.WaitForNavigationFinished());
// We should not dismiss dialogs when the prerender's subframe navigates and
// swaps its RFH.
EXPECT_FALSE(dialog_manager.cancel_dialogs_called());
// Clean up test dialog manager.
web_contents_impl()->SetDelegate(nullptr);
}
// Tests that NavigationHandle::GetNavigatingFrameType() returns the correct
// type in prerendering and after activation.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, NavigationHandleFrameType) {
{
const GURL kInitialUrl = GetUrl("/empty.html");
DidFinishNavigationObserver observer(
web_contents(),
base::BindLambdaForTesting([](NavigationHandle* navigation_handle) {
EXPECT_TRUE(navigation_handle->IsInPrimaryMainFrame());
CHECK_EQ(navigation_handle->GetNavigatingFrameType(),
FrameType::kPrimaryMainFrame);
}));
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
}
const GURL kPrerenderingUrl = GetUrl("/empty.html?prerender");
{
DidFinishNavigationObserver observer(
web_contents(),
base::BindLambdaForTesting([](NavigationHandle* navigation_handle) {
EXPECT_TRUE(navigation_handle->IsInPrerenderedMainFrame());
CHECK_EQ(navigation_handle->GetNavigatingFrameType(),
FrameType::kPrerenderMainFrame);
}));
// Start prerendering.
AddPrerender(kPrerenderingUrl);
}
{
DidFinishNavigationObserver observer(
web_contents(),
base::BindLambdaForTesting([](NavigationHandle* navigation_handle) {
EXPECT_TRUE(navigation_handle->IsInPrimaryMainFrame());
EXPECT_TRUE(navigation_handle->IsPrerenderedPageActivation());
CHECK_EQ(navigation_handle->GetNavigatingFrameType(),
FrameType::kPrimaryMainFrame);
}));
NavigatePrimaryPage(kPrerenderingUrl);
}
}
// Tests that NavigationHandle::IsRendererInitiated() returns RendererInitiated
// = true correctly.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
NavigationHandleIsRendererInitiatedTrue) {
const GURL kInitialUrl = GetUrl("/empty.html");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
const GURL kPrerenderingUrl = GetUrl("/empty.html?prerender");
{
DidFinishNavigationObserver observer(
web_contents(),
base::BindLambdaForTesting([](NavigationHandle* navigation_handle) {
EXPECT_TRUE(navigation_handle->IsInPrerenderedMainFrame());
EXPECT_TRUE(navigation_handle->IsRendererInitiated());
}));
// Start prerendering.
AddPrerender(kPrerenderingUrl);
}
NavigatePrimaryPage(kPrerenderingUrl);
}
// Tests that FrameTreeNode::has_received_user_gesture_before_nav_ is not set on
// the prerendered main frame or the activated main frame when the primary main
// frame doesn't have it.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
HasReceivedUserGestureBeforeNavigation) {
// Navigate to an initial page.
const GURL initial_url = GetUrl("/empty.html");
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
// The primary main frame doesn't have the
// has_received_user_gesture_before_nav bit.
ASSERT_FALSE(current_frame_host()
->frame_tree_node()
->has_received_user_gesture_before_nav());
// Start prerendering.
const GURL prerendering_url = GetUrl("/empty.html?prerender");
FrameTreeNodeId host_id = AddPrerender(prerendering_url);
RenderFrameHostImpl* prerendered_render_frame_host =
GetPrerenderedMainFrameHost(host_id);
// The prerendered main frame should not have the bit.
EXPECT_FALSE(prerendered_render_frame_host->frame_tree_node()
->has_received_user_gesture_before_nav());
// Activate the prerendered page.
test::PrerenderHostObserver host_observer(*web_contents(), host_id);
NavigatePrimaryPage(prerendering_url);
ASSERT_TRUE(host_observer.was_activated());
// The activated main frame should not have the bit.
EXPECT_FALSE(current_frame_host()
->frame_tree_node()
->has_received_user_gesture_before_nav());
}
// Tests that FrameTreeNode::has_received_user_gesture_before_nav_ is not
// propagated from the primary main frame to the prerendered main frame but it
// is propagated to the activated main frame.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
HasReceivedUserGestureBeforeNavigation_Propagation) {
// Navigate to an initial page.
const GURL initial_url = GetUrl("/empty.html");
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
// Set the has_received_user_gesture_before_nav bit on the primary main frame.
current_frame_host()->HadStickyUserActivationBeforeNavigationChanged(true);
ASSERT_TRUE(current_frame_host()
->frame_tree_node()
->has_received_user_gesture_before_nav());
// Start prerendering.
const GURL prerendering_url = GetUrl("/empty.html?prerender");
FrameTreeNodeId host_id = AddPrerender(prerendering_url);
RenderFrameHostImpl* prerendered_render_frame_host =
GetPrerenderedMainFrameHost(host_id);
// The prerendered main frame should not have the bit.
EXPECT_FALSE(prerendered_render_frame_host->frame_tree_node()
->has_received_user_gesture_before_nav());
// Activate the prerendered page.
test::PrerenderHostObserver host_observer(*web_contents(), host_id);
NavigatePrimaryPage(prerendering_url);
ASSERT_TRUE(host_observer.was_activated());
// The activated main frame should have the bit.
EXPECT_TRUE(current_frame_host()
->frame_tree_node()
->has_received_user_gesture_before_nav());
}
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
CancelPrerenderWhenIsOverridingUserAgentDiffers) {
const std::string user_agent_override = "foo";
// Navigate to an initial page.
const GURL initial_url = GetUrl("/empty.html");
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
// Enable user agent override for future navigations.
UserAgentInjector injector(shell()->web_contents(), user_agent_override);
const GURL prerendering_url = GetUrl("/empty.html?prerender");
// Start prerendering.
const FrameTreeNodeId host_id = AddPrerender(prerendering_url);
RenderFrameHostImpl* prerender_rfh =
static_cast<RenderFrameHostImpl*>(GetPrerenderedMainFrameHost(host_id));
EXPECT_EQ(user_agent_override, EvalJs(prerender_rfh, "navigator.userAgent"));
// Stop overriding user agent from now on.
injector.set_is_overriding_user_agent(false);
// Activate the prerendered page.
test::PrerenderHostObserver host_observer(*web_contents(), host_id);
NavigatePrimaryPage(prerendering_url);
host_observer.WaitForDestroyed();
ExpectFinalStatusForSpeculationRule(
PrerenderFinalStatus::kActivationNavigationParameterMismatch);
histogram_tester().ExpectUniqueSample(
"Prerender.Experimental.ActivationHeadersMismatch.SpeculationRule",
-511888193, 1);
}
class PrerenderSpeculationRulesHoldbackBrowserTest
: public PrerenderBrowserTest {
public:
PrerenderSpeculationRulesHoldbackBrowserTest() {
prerender_helper()->SetHoldback(
PreloadingType::kPrerender,
content_preloading_predictor::kSpeculationRules, true);
}
~PrerenderSpeculationRulesHoldbackBrowserTest() override = default;
};
IN_PROC_BROWSER_TEST_F(PrerenderSpeculationRulesHoldbackBrowserTest,
PrerenderHoldbackTest) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/empty.html?prerender");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start prerendering `kPrerenderingUrl` this should fail as we are in
// holdback.
test::PrerenderHostRegistryObserver registry_observer(*web_contents_impl());
AddPrerenderAsync(kPrerenderingUrl);
// Wait for PrerenderHostRegistry to receive the holdback prerender
// request, and it should be ignored.
registry_observer.WaitForTrigger(kPrerenderingUrl);
EXPECT_FALSE(HasHostForUrl(kPrerenderingUrl));
NavigationHandleObserver activation_observer(web_contents(),
kPrerenderingUrl);
NavigatePrimaryPage(kPrerenderingUrl);
// Cross-check that PreloadingHoldbackStatus is correctly set.
ukm::SourceId ukm_source_id = activation_observer.next_page_ukm_source_id();
ExpectPreloadingAttemptUkm({attempt_ukm_entry_builder().BuildEntry(
ukm_source_id, PreloadingType::kPrerender,
PreloadingEligibility::kEligible, PreloadingHoldbackStatus::kHoldback,
PreloadingTriggeringOutcome::kUnspecified,
PreloadingFailureReason::kUnspecified,
/*accurate=*/true,
/*ready_time=*/std::nullopt,
blink::mojom::SpeculationEagerness::kEager)});
}
class PrerenderFencedFrameBrowserTest : public PrerenderBrowserTest {
public:
PrerenderFencedFrameBrowserTest() {
feature_list_.InitWithFeaturesAndParameters(
{{blink::features::kFencedFrames, {}},
{::features::kPrivacySandboxAdsAPIsOverride, {}},
{blink::features::kFencedFramesAPIChanges, {}},
{blink::features::kFencedFramesDefaultMode, {}}},
{/* disabled_features */});
}
~PrerenderFencedFrameBrowserTest() override = default;
void SetUp() override {
ssl_server().RegisterRequestHandler(base::BindRepeating(
&net::test_server::HandlePrefixedRequest,
"/fenced-frame-with-speculation-rules",
base::BindRepeating(HandleFencedFrameWithSpeculationRulesRequest)));
ssl_server().RegisterRequestHandler(base::BindRepeating(
&net::test_server::HandlePrefixedRequest,
"/fenced-frame-with-speculation-rules-header",
base::BindRepeating(
HandleFencedFrameWithSpeculationRulesHeaderRequest)));
ssl_server().RegisterRequestHandler(base::BindRepeating(
&net::test_server::HandlePrefixedRequest, "/prerender.json",
base::BindRepeating(HandlePrerenderJsonRequest)));
PrerenderBrowserTest::SetUp();
}
static std::unique_ptr<net::test_server::HttpResponse>
HandleFencedFrameWithSpeculationRulesRequest(
const net::test_server::HttpRequest& request) {
constexpr char kSpeculationRule[] = R"({
<!doctype html>
<script type="speculationrules">
{
"prerender":[
{"source": "list", "urls": ["/empty.html"]}
]
}
</script>
})";
auto http_response =
std::make_unique<net::test_server::BasicHttpResponse>();
http_response->set_code(net::HTTP_OK);
http_response->AddCustomHeader("Supports-Loading-Mode", "fenced-frame");
http_response->set_content_type("text/html");
http_response->set_content(kSpeculationRule);
return http_response;
}
static std::unique_ptr<net::test_server::HttpResponse>
HandleFencedFrameWithSpeculationRulesHeaderRequest(
const net::test_server::HttpRequest& request) {
auto http_response =
std::make_unique<net::test_server::BasicHttpResponse>();
http_response->set_code(net::HTTP_OK);
http_response->AddCustomHeader("Supports-Loading-Mode", "fenced-frame");
http_response->AddCustomHeader("Speculation-Rules", "\"/prerender.json\"");
http_response->set_content_type("text/html");
http_response->set_content("<!doctype html>nothing");
return http_response;
}
static std::unique_ptr<net::test_server::HttpResponse>
HandlePrerenderJsonRequest(const net::test_server::HttpRequest& request) {
constexpr char kSpeculationRule[] = R"(
{
"prerender":[
{"source": "list", "urls": ["/empty.html"]}
]
}
)";
auto http_response =
std::make_unique<net::test_server::BasicHttpResponse>();
http_response->set_code(net::HTTP_OK);
http_response->set_content_type("application/speculationrules+json");
http_response->set_content(kSpeculationRule);
return http_response;
}
private:
base::test::ScopedFeatureList feature_list_;
};
// Test that creating a fenced frame in a prerendered page is deferred until
// activation.
IN_PROC_BROWSER_TEST_F(PrerenderFencedFrameBrowserTest,
CreateFencedFrameInPrerenderedPage) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/empty.html?prerender");
const GURL kFencedFrameUrl = GetUrl("/title1.html");
constexpr char kAddFencedFrameScript[] = R"({
const fenced_frame = document.createElement('fencedframe');
fenced_frame.config = new FencedFrameConfig($1);
document.body.appendChild(fenced_frame);
})";
const int kNumNavigations = 3;
TestNavigationObserver nav_observer(web_contents(), kNumNavigations);
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start a prerender.
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
auto* prerendered_rfh = GetPrerenderedMainFrameHost(host_id);
EXPECT_EQ(kPrerenderingUrl, nav_observer.last_navigation_url());
EXPECT_TRUE(ExecJs(prerendered_rfh,
JsReplace(kAddFencedFrameScript, kFencedFrameUrl)));
// Since we've deferred creating the fenced frame delegate, we should see no
// child frames.
size_t child_frame_count = 0;
prerendered_rfh->ForEachRenderFrameHostImpl([&](RenderFrameHostImpl* rfh) {
if (rfh != prerendered_rfh) {
child_frame_count++;
}
});
EXPECT_EQ(0lu, child_frame_count);
NavigatePrimaryPage(kPrerenderingUrl);
EXPECT_EQ(kPrerenderingUrl, nav_observer.last_navigation_url());
nav_observer.Wait();
EXPECT_EQ(kFencedFrameUrl, nav_observer.last_navigation_url());
}
// Test that prerendering triggered by fenced frames with speculation rules is
// blocked.
IN_PROC_BROWSER_TEST_F(PrerenderFencedFrameBrowserTest,
PrerenderFromFencedFrame_SpeculationRules) {
const GURL initial_url = GetUrl("/empty.html");
const GURL fenced_frame_url = GetUrl("/fenced-frame-with-speculation-rules");
constexpr char kAddFencedFrameScript[] = R"({
const fenced_frame = document.createElement('fencedframe');
fenced_frame.config = new FencedFrameConfig($1);
document.body.appendChild(fenced_frame);
})";
// Prerendering triggered by fenced frames will be blocked. To detect it, we
// need to wait its failure by monitoring a console error.
const char* console_pattern =
"The SpeculationRules API does not support prerendering in fenced "
"frames.";
WebContentsConsoleObserver console_observer(web_contents());
console_observer.SetPattern(console_pattern);
// Start prerendering from fenced frames.
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
RenderFrameHostImpl* primary_rfh = web_contents_impl()->GetPrimaryMainFrame();
EXPECT_TRUE(
ExecJs(primary_rfh, JsReplace(kAddFencedFrameScript, fenced_frame_url)));
ASSERT_TRUE(console_observer.Wait());
histogram_tester().ExpectTotalCount(
"Prerender.Experimental.PrerenderHostFinalStatus.SpeculationRule", 0);
}
// Test that prerendering triggered by fenced frames with speculation rules
// header is blocked.
IN_PROC_BROWSER_TEST_F(PrerenderFencedFrameBrowserTest,
PrerenderFromFencedFrame_LinkSpeculationRules) {
const GURL initial_url = GetUrl("/empty.html");
const GURL fenced_frame_url =
GetUrl("/fenced-frame-with-speculation-rules-header");
constexpr char kAddFencedFrameScript[] = R"({
const fenced_frame = document.createElement('fencedframe');
fenced_frame.config = new FencedFrameConfig($1);
document.body.appendChild(fenced_frame);
})";
// Prerendering triggered by fenced frames will be blocked. To detect it, we
// need to wait its failure by monitoring a console error.
const char* console_pattern =
"The SpeculationRules API does not support prerendering in fenced "
"frames.";
WebContentsConsoleObserver console_observer(web_contents());
console_observer.SetPattern(console_pattern);
// Start prerendering from fenced frames.
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
RenderFrameHostImpl* primary_rfh = web_contents_impl()->GetPrimaryMainFrame();
EXPECT_TRUE(
ExecJs(primary_rfh, JsReplace(kAddFencedFrameScript, fenced_frame_url)));
ASSERT_TRUE(console_observer.Wait());
histogram_tester().ExpectTotalCount(
"Prerender.Experimental.PrerenderHostFinalStatus.SpeculationRule", 0);
}
namespace {
class PrerenderWithSiteIsolationDisabledBrowserTest
: public PrerenderBrowserTest {
public:
PrerenderWithSiteIsolationDisabledBrowserTest() = default;
~PrerenderWithSiteIsolationDisabledBrowserTest() override = default;
void SetUpCommandLine(base::CommandLine* command_line) override {
PrerenderBrowserTest::SetUpCommandLine(command_line);
command_line->AppendSwitch(switches::kDisableSiteIsolation);
}
};
} // namespace
// This test sets up a scenario where we swap SiteInstances during a prerender
// page's first navigation. Full site isolation is disabled for this test, but
// we dynamically isolate "b.test". The max process count is also set to 1.
//
// We initially start off with navigating the primary main frame to b.test,
// which will be assigned to a process P1.
//
// P1 ----- b.test
//
// We then add an a.test iframe, which will be assigned to a different process
// P2. This is because P1 currently hosts content from b.test, and b.test has
// been configured to require isolation from other sites.
//
// P1 ------ b.test
// P2 ------ a.test
//
// We then start prerendering b.test. This happens in two steps. In the first
// step we initialize the FrameTree and create an empty main frame that hasn't
// been navigated. This empty main frame has an empty SiteInstance (prerenders
// use an empty SiteInfo for this currently) which is assigned to P2 (in normal
// circumstances, it would be assigned to a new process but because we're above
// the process limit, it tries to reuse an existing process, and P2 is eligible
// as it currently only has the a.test iframe and a.test does not need to be
// isolated).
//
// P1 ------ b.test
// P2 ------ a.test, <empty prerender>
//
// In the second step, we navigate the prerender main frame to the prerender
// url, which is b.test. Now b.test is configured to be in an isolated process,
// so we can't reuse the current SiteInstance (as it is assigned to P1 which has
// content from a.test), and have to move it to a new process (and therefore
// have to swap the SiteInstance).
//
// P1 ------ b.test (primary), b.test (prerender)
// P2 ------ a.test
IN_PROC_BROWSER_TEST_F(PrerenderWithSiteIsolationDisabledBrowserTest,
ForceSiteInstanceSwapForInitialPrerenderNavigation) {
if (AreAllSitesIsolatedForTesting()) {
LOG(ERROR) << "Site Isolation should be disabled for this test.";
return;
}
// Set max renderer process count to force process reuse and prevent
// prerendering pages from getting dedicated processes by default.
RenderProcessHost::SetMaxRendererProcessCount(1);
const GURL kInitialUrl =
ssl_server().GetURL("isolated.b.test", "/empty.html");
const GURL kIframeUrl = ssl_server().GetURL("a.test", "/empty.html");
const GURL kPrerenderingUrl =
ssl_server().GetURL("isolated.b.test", "/title1.html");
auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
policy->AddFutureIsolatedOrigins(
{url::Origin::Create(kInitialUrl)},
ChildProcessSecurityPolicy::IsolatedOriginSource::TEST);
// Navigate primary main frame to b.test. It will be assigned to a process
// that is locked to b.test.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Add an a.test iframe, which will be loaded in a new process that isn't
// locked.
ASSERT_TRUE(AddTestUtilJS(current_frame_host()));
ASSERT_TRUE(
ExecJs(current_frame_host(), JsReplace("add_iframe($1)", kIframeUrl)));
RenderFrameHostImplWrapper iframe(
static_cast<RenderFrameHostImpl*>(ChildFrameAt(current_frame_host(), 0)));
ASSERT_NE(current_frame_host()->GetProcess(), iframe->GetProcess());
// Prerender b.test. The initial empty document will be assigned to
// the same process as the a.test iframe, but on navigation to b.test, it
// can no longer use the same process, and the SiteInstance will have to be
// changed in order to assign the document to a different process.
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
RenderFrameHostImplWrapper prerender_rfh(
GetPrerenderedMainFrameHost(host_id));
EXPECT_EQ(prerender_rfh->lifecycle_state(),
LifecycleStateImpl::kPrerendering);
EXPECT_EQ(prerender_rfh->GetProcess(), current_frame_host()->GetProcess());
}
class PrerenderClientHintsBrowserTest : public PrerenderBrowserTest {
public:
PrerenderClientHintsBrowserTest() = default;
~PrerenderClientHintsBrowserTest() override = default;
void SetUp() override {
ssl_server().RegisterRequestHandler(base::BindRepeating(&HandleRequest));
PrerenderBrowserTest::SetUp();
}
static std::unique_ptr<net::test_server::HttpResponse> HandleRequest(
const net::test_server::HttpRequest& request) {
if (request.relative_url.find("acceptch") == std::string::npos) {
return nullptr;
}
// Serve a response indicating clients to provide full version of UA.
auto response = std::make_unique<net::test_server::BasicHttpResponse>();
if (request.relative_url.find("full-version") != std::string::npos) {
response->AddCustomHeader("Accept-CH", "sec-ch-ua-full-version");
} else if (request.relative_url.find("bitness") != std::string::npos) {
response->AddCustomHeader("Accept-CH", "sec-ch-ua-bitness");
} else if (request.relative_url.find("viewport-width") !=
std::string::npos) {
response->AddCustomHeader("Accept-CH", "viewport-width");
response->AddCustomHeader("Accept-CH", "sec-ch-viewport-width");
} else if (request.relative_url.find("viewport-height") !=
std::string::npos) {
// Don't need to add "viewport-height" as it is not defined in the specs.
response->AddCustomHeader("Accept-CH", "sec-ch-viewport-height");
} else if (request.relative_url.find("no-value") != std::string::npos) {
response->AddCustomHeader("Accept-CH", "");
}
response->set_code(net::HTTP_OK);
if (request.relative_url.find("iframe") != std::string::npos) {
response->set_content(R"(
<html><head><title>iframe test</title></head>
<body>
<iframe src="title1.html" id="test"></iframe>
</body></html>
)");
response->set_content_type("text/html");
} else if (request.relative_url.find("image") != std::string::npos) {
response->set_content(R"(
<html>
<head></head>
<body>
<img src="./blank.jpg"/>
<p>This page has an image. Yay for images!
</body>
</html>
)");
response->set_content_type("text/html");
} else {
response->set_content("");
response->set_content_type("text/plain");
}
return response;
}
protected:
bool HasRequestHeader(const GURL& url, const std::string& key) {
net::test_server::HttpRequest::HeaderMap headers = GetRequestHeaders(url);
return headers.find(key) != headers.end();
}
};
IN_PROC_BROWSER_TEST_F(PrerenderClientHintsBrowserTest,
PrerenderResponseChangesClientHintsLocally) {
MockClientHintsControllerDelegate client_hints_controller_delegate(
GetShellUserAgentMetadata());
ShellContentBrowserClient::Get()
->browser_context()
->set_client_hints_controller_delegate(&client_hints_controller_delegate);
// Navigate to an initial page.
GURL url = GetUrl("/empty.html?acceptch-bitness");
ASSERT_TRUE(NavigateToURL(shell(), url));
// Start prerendering.
GURL prerender_url = GetUrl("/iframe.html?acceptch-full-version");
FrameTreeNodeId host_id = AddPrerender(prerender_url);
// The main frame request does not contain sec-ch-ua-full-version, because it
// is using the global setting at this moment. sec-ch-ua-bitness should be
// contained as well, because it is a global setting and applies to all
// navigations.
EXPECT_TRUE(HasRequestHeader(prerender_url, "sec-ch-ua-bitness"));
EXPECT_FALSE(HasRequestHeader(prerender_url, "sec-ch-ua-full-version"));
// The subframe prerender navigation requests should contain
// sec-ch-ua-full-version, as the main frame navigation request changed the
// client hints setting.
GURL prerender_iframe_url = GetUrl("/title1.html");
WaitForRequest(prerender_iframe_url, 1);
EXPECT_TRUE(HasRequestHeader(prerender_iframe_url, "sec-ch-ua-full-version"));
EXPECT_TRUE(HasRequestHeader(prerender_iframe_url, "sec-ch-ua-bitness"));
test::PrerenderHostObserver prerender_observer(*web_contents_impl(), host_id);
NavigatePrimaryPage(prerender_url);
// The prerendered page should be activated successfully. The settings on the
// prerendered page should not apply to the primary navigation before
// activation, so at this point the navigation request is using the global
// setting, which is the same as the prerender initial navigation.
prerender_observer.WaitForActivation();
GURL real_navigate_url = GetUrl("/empty.html?real");
NavigatePrimaryPage(real_navigate_url);
// The request headers should contain sec-ch-ua-full-version, because the
// prerender local setting was propagated to the global setting. The final
// setting is the union set of global setting and local setting.
EXPECT_TRUE(HasRequestHeader(real_navigate_url, "sec-ch-ua-full-version"));
EXPECT_TRUE(HasRequestHeader(prerender_iframe_url, "sec-ch-ua-bitness"));
}
IN_PROC_BROWSER_TEST_F(PrerenderClientHintsBrowserTest,
ChangesToClientHintsAreDiscardIfNoActivation) {
MockClientHintsControllerDelegate client_hints_controller_delegate(
GetShellUserAgentMetadata());
ShellContentBrowserClient::Get()
->browser_context()
->set_client_hints_controller_delegate(&client_hints_controller_delegate);
// Navigate to an initial page.
GURL url = GetUrl("/empty.html");
ASSERT_TRUE(NavigateToURL(shell(), url));
// Start prerendering.
GURL prerender_url = GetUrl("/empty.html?acceptch");
GURL real_navigate_url = GetUrl("/empty.html?real");
FrameTreeNodeId host_id = AddPrerender(prerender_url);
test::PrerenderHostObserver prerender_observer(*web_contents_impl(), host_id);
NavigatePrimaryPage(real_navigate_url);
// The request headers should not contain sec-ch-ua-full-version, because no
// primary pages indicate to do so and the prerender local setting has been
// discarded.
EXPECT_FALSE(HasRequestHeader(real_navigate_url, "sec-ch-ua-full-version"));
GURL real_navigate_url_2 = GetUrl("/empty.html?real2");
NavigatePrimaryPage(real_navigate_url_2);
// The request headers should not contain sec-ch-ua-full-version, because no
// primary pages indicate to do so and the prerender local setting has been
// discarded.
EXPECT_FALSE(HasRequestHeader(real_navigate_url_2, "sec-ch-ua-full-version"));
}
IN_PROC_BROWSER_TEST_F(PrerenderClientHintsBrowserTest,
PrimaryResponsesDoNotResetPrenderSettings) {
MockClientHintsControllerDelegate client_hints_controller_delegate(
GetShellUserAgentMetadata());
ShellContentBrowserClient::Get()
->browser_context()
->set_client_hints_controller_delegate(&client_hints_controller_delegate);
// Navigate to an initial page.
GURL url = GetUrl("/empty.html");
ASSERT_TRUE(NavigateToURL(shell(), url));
// Start prerendering.
GURL prerender_url = GetUrl("/iframe.html?acceptch-full-version");
FrameTreeNodeId host_id = AddPrerender(prerender_url);
// The main frame request does not contain sec-ch-ua-full-version, because it
// is using the global setting at this moment.
EXPECT_FALSE(HasRequestHeader(prerender_url, "sec-ch-ua-full-version"));
// The subframe prerender navigation requests should contain
// sec-ch-ua-full-version, as the main frame navigation request changed the
// client hints setting.
GURL prerender_iframe_url = GetUrl("/title1.html");
WaitForRequest(prerender_iframe_url, 1);
EXPECT_TRUE(HasRequestHeader(prerender_iframe_url, "sec-ch-ua-full-version"));
// Open a new tab, and the new page clears all settings.
GURL new_tab_url = GetUrl("/image.html?acceptch-no-value");
OpenURLParams params(
new_tab_url, Referrer(), WindowOpenDisposition::NEW_BACKGROUND_TAB,
ui::PAGE_TRANSITION_LINK, /*is_renderer_initiated=*/false);
auto* new_web_contents =
web_contents_impl()->OpenURL(params, /*navigation_handle_callback=*/{});
ASSERT_NE(nullptr, new_web_contents);
GURL new_tab_image_url = GetUrl("/blank.jpg");
WaitForRequest(new_tab_image_url, 1);
EXPECT_FALSE(HasRequestHeader(new_tab_url, "sec-ch-ua-full-version"));
test::PrerenderHostObserver prerender_observer(*web_contents_impl(), host_id);
NavigatePrimaryPage(prerender_url);
// The prerendered page should be activated successfully.
prerender_observer.WaitForActivation();
GURL real_navigate_url = GetUrl("/empty.html?real");
NavigatePrimaryPage(real_navigate_url);
// The request headers should contain sec-ch-ua-full-version, because the
// prerender local setting was propagated to the global setting.
EXPECT_TRUE(HasRequestHeader(real_navigate_url, "sec-ch-ua-full-version"));
}
// Test that changes on the viewport width of the initiator page between when to
// trigger prerendering and when to activate don't fail activation params match.
IN_PROC_BROWSER_TEST_F(PrerenderClientHintsBrowserTest, ViewPort_Width) {
MockClientHintsControllerDelegate client_hints_controller_delegate(
GetShellUserAgentMetadata());
ShellContentBrowserClient::Get()
->browser_context()
->set_client_hints_controller_delegate(&client_hints_controller_delegate);
// Set the initial window size.
web_contents_impl()->Resize(gfx::Rect(10, 20));
// Navigate to an initial page.
GURL url = GetUrl("/empty.html?acceptch-viewport-width");
ASSERT_TRUE(NavigateToURL(shell(), url));
// Start prerendering. This won't have the "(sec-ch-)viewport-width" headers
// as the width is 0 due to the lack of a cached/known viewport size.
GURL prerender_url = GetUrl("/iframe.html?acceptch");
FrameTreeNodeId host_id = AddPrerender(prerender_url);
EXPECT_FALSE(HasRequestHeader(prerender_url, "viewport-width"));
EXPECT_FALSE(HasRequestHeader(prerender_url, "sec-ch-viewport-width"));
// Resize the window.
web_contents_impl()->Resize(gfx::Rect(30, 40));
// Activation should also not have the "(sec-ch-)viewport-width" headers.
test::PrerenderHostObserver prerender_observer(*web_contents_impl(), host_id);
NavigatePrimaryPage(prerender_url);
prerender_observer.WaitForActivation();
EXPECT_FALSE(HasRequestHeader(prerender_url, "viewport-width"));
EXPECT_FALSE(HasRequestHeader(prerender_url, "sec-ch-viewport-width"));
}
// Test that changes on the viewport height of the initiator page between when
// to trigger prerendering and when to activate don't fail activation params
// match.
IN_PROC_BROWSER_TEST_F(PrerenderClientHintsBrowserTest, ViewPort_Height) {
MockClientHintsControllerDelegate client_hints_controller_delegate(
GetShellUserAgentMetadata());
ShellContentBrowserClient::Get()
->browser_context()
->set_client_hints_controller_delegate(&client_hints_controller_delegate);
// Set the initial window size.
web_contents_impl()->Resize(gfx::Rect(10, 20));
// Navigate to an initial page.
GURL url = GetUrl("/empty.html?acceptch-viewport-height");
ASSERT_TRUE(NavigateToURL(shell(), url));
// Start prerendering. This won't have the "sec-ch-viewport-height" header
// as the height is 0 due to the lack of a cached/known viewport size.
GURL prerender_url = GetUrl("/iframe.html?acceptch");
FrameTreeNodeId host_id = AddPrerender(prerender_url);
EXPECT_FALSE(HasRequestHeader(prerender_url, "sec-ch-viewport-height"));
// Resize the window.
web_contents_impl()->Resize(gfx::Rect(30, 40));
// Activation should also not have the "sec-ch-viewport-height" header.
test::PrerenderHostObserver prerender_observer(*web_contents_impl(), host_id);
NavigatePrimaryPage(prerender_url);
prerender_observer.WaitForActivation();
EXPECT_FALSE(HasRequestHeader(prerender_url, "sec-ch-viewport-height"));
}
void CheckExpectedCrossOriginMetrics(
const base::HistogramTester& histogram_tester,
PrerenderCrossOriginRedirectionMismatch mismatch_type,
std::optional<PrerenderCrossOriginRedirectionProtocolChange>
protocol_change) {
histogram_tester.ExpectUniqueSample(
"Prerender.Experimental.PrerenderHostFinalStatus.Embedder_"
"EmbedderSuffixForTest",
PrerenderFinalStatus::kCrossSiteRedirectInInitialNavigation, 1);
histogram_tester.ExpectUniqueSample(
"Prerender.Experimental.PrerenderCrossOriginRedirectionMismatch.Embedder_"
"EmbedderSuffixForTest",
mismatch_type, 1);
if (protocol_change.has_value()) {
histogram_tester.ExpectUniqueSample(
"Prerender.Experimental.CrossOriginRedirectionProtocolChange.Embedder_"
"EmbedderSuffixForTest",
protocol_change.value(), 1);
}
}
// Tests PrerenderCrossOriginRedirectionMismatch.kSchemeHostPortMismatch was
// recorded when a prerendering navigaton was redireted to another origin with
// different scheme, host and port.
IN_PROC_BROWSER_TEST_F(
PrerenderBrowserTest,
EmbedderTrigger_CrossOriginRedirection_SchemeHostPortMismatch) {
base::HistogramTester histogram_tester;
embedded_test_server()->AddDefaultHandlers(GetTestDataFilePath());
ASSERT_TRUE(embedded_test_server()->Start());
GURL initial_url = GetUrl("/empty.html");
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
// The redirected_url's origin completely differs from the prerendering one.
GURL redirected_url = embedded_test_server()->GetURL("b.test", "/empty.html");
GURL prerendering_url = GetUrl("/server-redirect?" + redirected_url.spec());
ASSERT_NE(prerendering_url.scheme(), redirected_url.scheme());
ASSERT_NE(prerendering_url.host(), redirected_url.host());
ASSERT_NE(prerendering_url.port(), redirected_url.port());
PrerenderEmbedderTriggeredCrossOriginRedirectionPage(
*web_contents_impl(), prerendering_url, redirected_url);
CheckExpectedCrossOriginMetrics(
histogram_tester,
PrerenderCrossOriginRedirectionMismatch::kSchemeHostPortMismatch,
/*protocol_change=*/std::nullopt);
}
// Tests a prerendering navigaton goes with HTTP protocol, and being redirected
// to upgrade its protocol to HTTPS.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
EmbedderTrigger_CrossOriginRedirection_ProtocolUpgrade) {
base::HistogramTester histogram_tester;
embedded_test_server()->AddDefaultHandlers(GetTestDataFilePath());
ASSERT_TRUE(embedded_test_server()->Start());
GURL initial_url = embedded_test_server()->GetURL("a.test", "/empty.html");
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
// Redirect to another url with protocol upgraded.
GURL redirected_url = ssl_server().GetURL("a.test", "/empty.html");
GURL prerendering_url = embedded_test_server()->GetURL(
"a.test", "/server-redirect?" + redirected_url.spec());
ASSERT_NE(prerendering_url.scheme(), redirected_url.scheme());
ASSERT_NE(prerendering_url.port(), redirected_url.port());
ASSERT_EQ(prerendering_url.scheme(), url::kHttpScheme);
ASSERT_EQ(redirected_url.scheme(), url::kHttpsScheme);
PrerenderEmbedderTriggeredCrossOriginRedirectionPage(
*web_contents_impl(), prerendering_url, redirected_url);
CheckExpectedCrossOriginMetrics(
histogram_tester,
PrerenderCrossOriginRedirectionMismatch::kSchemePortMismatch,
PrerenderCrossOriginRedirectionProtocolChange::kHttpProtocolUpgrade);
}
// Similar to
// CancelEmbedderTriggeredPrerenderingCrossOriginRedirection_ProtocolUpgrade,
// tests a prerendering navigaton goes with HTTPS protocol, and being redirected
// to upgrade its protocol to HTTPS.
IN_PROC_BROWSER_TEST_F(
PrerenderBrowserTest,
EmbedderTrigger_CrossOriginRedirection_ProtocolDowngrade) {
base::HistogramTester histogram_tester;
GURL initial_url = GetUrl("/empty.html");
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
GURL::Replacements downgrade_protocol;
downgrade_protocol.SetSchemeStr(url::kHttpScheme);
std::string port_str(base::NumberToString(ssl_server().port() + 1));
downgrade_protocol.SetPortStr(port_str);
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
// Redirect to another url with protocol upgraded.
GURL redirected_url =
GetUrl("/empty.html").ReplaceComponents(downgrade_protocol);
GURL prerendering_url = GetUrl("/server-redirect?" + redirected_url.spec());
ASSERT_NE(prerendering_url.scheme(), redirected_url.scheme());
ASSERT_NE(prerendering_url.port(), redirected_url.port());
ASSERT_EQ(prerendering_url.scheme(), url::kHttpsScheme);
ASSERT_EQ(redirected_url.scheme(), "http");
PrerenderEmbedderTriggeredCrossOriginRedirectionPage(
*web_contents_impl(), prerendering_url, redirected_url);
CheckExpectedCrossOriginMetrics(
histogram_tester,
PrerenderCrossOriginRedirectionMismatch::kSchemePortMismatch,
PrerenderCrossOriginRedirectionProtocolChange::kHttpProtocolDowngrade);
}
// Tests that embedder triggered prerender can be redirected to the subdomain
// because they are same-site.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
EmbedderTrigger_CrossOriginRedirection_ToSubdomain) {
GURL initial_url = GetUrl("/empty.html");
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
GURL::Replacements set_host;
set_host.SetHostStr("www.a.test");
GURL redirected_url = GetUrl("/empty.html").ReplaceComponents(set_host);
GURL prerendering_url = GetUrl("/server-redirect?" + redirected_url.spec());
std::unique_ptr<PrerenderHandle> prerender_handle =
PrerenderEmbedderTriggeredCrossOriginRedirectionPage(
*web_contents_impl(), prerendering_url, redirected_url);
test::PrerenderHostObserver prerender_observer(*web_contents_impl(),
prerendering_url);
prerender_helper()->NavigatePrimaryPageAsync(
prerendering_url,
ui::PageTransitionFromInt(ui::PAGE_TRANSITION_TYPED |
ui::PAGE_TRANSITION_FROM_ADDRESS_BAR));
prerender_observer.WaitForActivation();
histogram_tester().ExpectUniqueSample(
"Prerender.Experimental.PrerenderHostFinalStatus.Embedder_"
"EmbedderSuffixForTest",
PrerenderFinalStatus::kActivated, 1);
}
// Tests that embedder triggered prerender can be redirected to the same site.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
EmbedderTrigger_CrossOriginRedirection_FromSubdomain) {
GURL initial_url = GetUrl("/empty.html");
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
GURL::Replacements set_host;
set_host.SetHostStr("www.a.test");
GURL redirected_url = GetUrl("/empty.html");
GURL prerendering_url = GetUrl("/server-redirect?" + redirected_url.spec())
.ReplaceComponents(set_host);
std::unique_ptr<PrerenderHandle> prerender_handle =
PrerenderEmbedderTriggeredCrossOriginRedirectionPage(
*web_contents_impl(), prerendering_url, redirected_url);
test::PrerenderHostObserver prerender_observer(*web_contents_impl(),
prerendering_url);
prerender_helper()->NavigatePrimaryPageAsync(
prerendering_url,
ui::PageTransitionFromInt(ui::PAGE_TRANSITION_TYPED |
ui::PAGE_TRANSITION_FROM_ADDRESS_BAR));
prerender_observer.WaitForActivation();
histogram_tester().ExpectUniqueSample(
"Prerender.Experimental.PrerenderHostFinalStatus.Embedder_"
"EmbedderSuffixForTest",
PrerenderFinalStatus::kActivated, 1);
}
// Tests PrerenderCrossOriginRedirectionMismatch.kHostMismatch is recorded
// when the prerendering navigation is redirected to a different domain.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
EmbedderTrigger_CrossOriginRedirection_DifferentDomain) {
base::HistogramTester histogram_tester;
GURL kInitialUrl = GetUrl("/empty.html");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
GURL kRedirectedUrl = GetCrossSiteUrl("/empty.html?prerender");
GURL kPrerenderingUrl = GetUrl("/server-redirect?" + kRedirectedUrl.spec());
PrerenderEmbedderTriggeredCrossOriginRedirectionPage(
*web_contents_impl(), kPrerenderingUrl, kRedirectedUrl);
CheckExpectedCrossOriginMetrics(
histogram_tester, PrerenderCrossOriginRedirectionMismatch::kHostMismatch,
/*protocol_change=*/std::nullopt);
}
// Tests that prerender works with accessibility.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
PrerenderWithAccessibilityEnabled) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/page_with_iframe.html");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
ASSERT_EQ(web_contents()->GetLastCommittedURL(), kInitialUrl);
// Enable accessibility.
ScopedAccessibilityModeOverride inner_scoped_accessibility_mode(
shell()->web_contents(), ui::kAXModeComplete);
// Start prerendering `kPrerenderingUrl`, which has an iframe attached.
ASSERT_EQ(GetRequestCount(kPrerenderingUrl), 0);
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
ASSERT_TRUE(host_id);
ASSERT_EQ(GetRequestCount(kPrerenderingUrl), 1);
test::PrerenderHostObserver prerender_observer(*web_contents_impl(),
kPrerenderingUrl);
NavigatePrimaryPage(kPrerenderingUrl);
prerender_observer.WaitForActivation();
ExpectFinalStatusForSpeculationRule(PrerenderFinalStatus::kActivated);
}
class UpdateTargetURLDelegate : public WebContentsDelegate {
public:
explicit UpdateTargetURLDelegate(WebContents* web_contents) {
web_contents->SetDelegate(this);
}
UpdateTargetURLDelegate(const UpdateTargetURLDelegate&) = delete;
UpdateTargetURLDelegate& operator=(const UpdateTargetURLDelegate&) = delete;
bool is_updated_target_url() { return is_updated_target_url_; }
private:
void UpdateTargetURL(WebContents* source, const GURL& url) override {
is_updated_target_url_ = true;
}
bool is_updated_target_url_ = false;
};
// Tests that text autosizer works per page.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, FocusChangeInPrerenderedPage) {
const GURL kInitialUrl = GetUrl("/empty.html");
const GURL kPrerenderingUrl = GetUrl("/simple_links.html");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
RenderFrameHostImpl* prerender_frame_host =
GetPrerenderedMainFrameHost(host_id);
UpdateTargetURLDelegate delegate(shell()->web_contents());
// No crash.
EXPECT_TRUE(ExecJs(prerender_frame_host,
"document.getElementById('same_site_link').focus();"));
// The prerendered page should not update the target url.
EXPECT_FALSE(delegate.is_updated_target_url());
}
// Tests that an unused RenderWidgetHost (that is owned by a RenderViewHostImpl)
// created by a prerendering FrameTree points to the primary frame tree after
// activation. Regression test for crbug.com/1324149.
IN_PROC_BROWSER_TEST_F(
PrerenderBrowserTest,
UnusedRenderWidgetHostFrameTreePointerUpdatedOnActivation) {
// Since the render view host won't be created until the response is received
// if feature DeferSpeculativeRFHCreation is on. The test is no longer valid
// for this case.
if (base::FeatureList::IsEnabled(features::kDeferSpeculativeRFHCreation)) {
return;
}
IsolateAllSitesForTesting(base::CommandLine::ForCurrentProcess());
// Navigate to an initial page.
const GURL kInitialUrl = GetUrl("/title1.html");
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
EXPECT_TRUE(AddTestUtilJS(current_frame_host()));
// Start a prerender.
const GURL kPrerenderingUrl = GetUrl("/title2.html");
FrameTreeNodeId host_id = AddPrerender(kPrerenderingUrl);
// Add a cross-origin iframe to the prerendering page.
const GURL kCrossOriginSubframeUrl = GetCrossSiteUrl("/title2.html");
RenderFrameHostImpl* prerender_rfh = GetPrerenderedMainFrameHost(host_id);
EXPECT_TRUE(AddTestUtilJS(prerender_rfh));
EXPECT_TRUE(ExecJs(prerender_rfh, JsReplace("add_iframe_async($1)",
kCrossOriginSubframeUrl)));
base::RunLoop().RunUntilIdle();
ASSERT_EQ(prerender_rfh->child_count(), 1u);
FrameTreeNode* iframe = prerender_rfh->child_at(0);
// The cross-origin navigation in the iframe will be throttled, but not before
// creating a out-of-process speculative RFH (which would also result in an
// RVH created for the subframe speculatively).
ASSERT_TRUE(iframe->render_manager()->speculative_frame_host());
RenderViewHostImpl* render_view_host =
iframe->render_manager()->speculative_frame_host()->render_view_host();
// Activate.
NavigatePrimaryPage(kPrerenderingUrl);
ASSERT_EQ(web_contents()->GetLastCommittedURL(), kPrerenderingUrl);
// Wait for iframe to finish navigating.
ASSERT_EQ("LOADED",
EvalJs(prerender_rfh, JsReplace("wait_iframe_async($1)",
kCrossOriginSubframeUrl)));
// This asserts that the current RenderViewHost was created before activation
// (to make sure we're testing the right thing).
EXPECT_EQ(render_view_host, iframe->current_frame_host()->render_view_host());
// The unused RenderWidgetHost should point to the primary FrameTree now.
RenderWidgetHostImpl* render_widget_host = render_view_host->GetWidget();
EXPECT_NE(render_widget_host,
iframe->current_frame_host()->GetRenderWidgetHost());
EXPECT_EQ(render_widget_host->frame_tree(),
current_frame_host()->frame_tree());
// Navigate the primary main frame to the same origin as |iframe|; this
// should reuse |render_view_host|, and as a result |render_widget_host| will
// be used. If the |render_widget_host| points to the wrong frame_tree, this
// will result in a segfault (reproducing crbug.com/1324149) when we try to
// focus the new page's view.
const GURL kCrossOriginUrl = GetCrossSiteUrl("/title1.html");
DisableProactiveBrowsingInstanceSwapFor(current_frame_host());
NavigatePrimaryPage(kCrossOriginUrl);
ASSERT_EQ(current_frame_host()->render_view_host(), render_view_host);
ASSERT_EQ(current_frame_host()->GetRenderWidgetHost(), render_widget_host);
}
// Tests that window.close() can cancel speculation rules.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, WindowClosedSpeculationRules) {
ASSERT_TRUE(embedded_test_server()->Start());
const GURL kInitialUrl = embedded_test_server()->GetURL("/empty.html");
const GURL kPrerenderingUrl = embedded_test_server()->GetURL("/title1.html");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start a prerender.
AddPrerender(kPrerenderingUrl);
FrameTreeNodeId host_id = GetHostForUrl(kPrerenderingUrl);
WaitForPrerenderLoadCompletion(host_id);
test::PrerenderHostObserver host_observer(*web_contents(), host_id);
RenderFrameHostImpl* prerender_rfh = GetPrerenderedMainFrameHost(host_id);
ASSERT_TRUE(ExecJs(prerender_rfh, "window.close()"));
host_observer.WaitForDestroyed();
ExpectFinalStatusForSpeculationRule(PrerenderFinalStatus::kWindowClosed);
// The initiator page should not be closed by window.closed().
EXPECT_TRUE(ExecJs(web_contents(), ""));
}
// Tests that window.close() can cancel speculation rules whose target_hint is
// "_blank" (i.e., prerender into new tab).
IN_PROC_BROWSER_TEST_F(PrerenderTargetHintEnabledBrowserTest,
WindowClosedSpeculationRules_WithTargetHintBlank) {
ASSERT_TRUE(embedded_test_server()->Start());
const GURL kInitialUrl = embedded_test_server()->GetURL("/empty.html");
const GURL kPrerenderingUrl = embedded_test_server()->GetURL("/title1.html");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), kInitialUrl));
// Start a prerender.
FrameTreeNodeId host_id = prerender_helper()->AddPrerender(
kPrerenderingUrl, /*eagerness=*/std::nullopt, "_blank");
auto* prerender_web_contents = WebContents::FromFrameTreeNodeId(host_id);
ASSERT_NE(prerender_web_contents, web_contents_impl());
ExpectWebContentsIsForNewTabPrerendering(*prerender_web_contents);
test::PrerenderHostObserver host_observer(*prerender_web_contents, host_id);
RenderFrameHost* prerender_rfh =
test::PrerenderTestHelper::GetPrerenderedMainFrameHost(
*prerender_web_contents, host_id);
ASSERT_TRUE(ExecJs(prerender_rfh, "window.close()"));
host_observer.WaitForDestroyed();
ExpectFinalStatusForSpeculationRule(PrerenderFinalStatus::kWindowClosed);
// The initiator page should not be closed by window.closed().
EXPECT_TRUE(ExecJs(web_contents(), ""));
}
// Tests that Prerender is suppressed by slow network.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, SlowNetwork) {
// Emulate slow network.
MockClientHintsControllerDelegate client_hints_controller_delegate(
GetShellUserAgentMetadata());
ShellContentBrowserClient::Get()
->browser_context()
->set_client_hints_controller_delegate(&client_hints_controller_delegate);
network::NetworkQualityTracker& network_quality_tracker =
*client_hints_controller_delegate.GetNetworkQualityTracker();
base::TimeDelta http_rtt =
base::Milliseconds(1) +
::features::kSuppressesPrerenderingOnSlowNetworkThreshold.Get();
network_quality_tracker.ReportRTTsAndThroughputForTesting(
http_rtt, network_quality_tracker.GetDownstreamThroughputKbps());
ASSERT_TRUE(embedded_test_server()->Start());
GURL initial_url = GetUrl("/empty.html");
GURL prerendering_url = GetUrl("/empty.html?prerender");
// Attempt to prerender.
test::PrerenderHostRegistryObserver observer(*web_contents_impl());
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
AddPrerenderAsync(prerendering_url);
observer.WaitForTrigger(prerendering_url);
// It should fail.
EXPECT_FALSE(HasHostForUrl(prerendering_url));
ExpectFinalStatusForSpeculationRule(PrerenderFinalStatus::kSlowNetwork);
// Navigate primary page to flush the metrics.
NavigatePrimaryPage(prerendering_url);
// Cross-check that the eligibility reason points to kSlowNetwork on slow
// network.
ExpectPreloadingAttemptUkm({attempt_ukm_entry_builder().BuildEntry(
PrimaryPageSourceId(), PreloadingType::kPrerender,
PreloadingEligibility::kSlowNetwork,
PreloadingHoldbackStatus::kUnspecified,
PreloadingTriggeringOutcome::kUnspecified,
PreloadingFailureReason::kUnspecified,
/*accurate=*/true,
/*ready_time=*/std::nullopt,
blink::mojom::SpeculationEagerness::kEager)});
}
class V8OptimizerContentBrowserClient
: public ContentBrowserTestContentBrowserClient {
public:
explicit V8OptimizerContentBrowserClient(bool disable) : disable_(disable) {}
~V8OptimizerContentBrowserClient() override = default;
bool AreV8OptimizationsDisabledForSite(BrowserContext* browser_context,
const GURL& site_url) override {
return disable_;
}
public:
const bool disable_ = false;
};
// Previously, prerendering a page that had the COOP crashed when the V8
// optimizer was disabled by the site settings. This is the regression test for
// the issue. See https://crbug.com/40076091 for details.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderCOOPWithoutV8Optimizer) {
// Disable the V8 optimizer.
V8OptimizerContentBrowserClient test_browser_client(/*disable=*/true);
// Attempt to prerender the page that has the COOP.
const GURL initial_url = GetUrl("/empty.html");
const GURL prerendering_url =
GetUrl("/set-header?Cross-Origin-Opener-Policy: same-origin");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
ASSERT_EQ(web_contents()->GetLastCommittedURL(), initial_url);
FrameTreeNodeId host_id = AddPrerender(prerendering_url);
test::PrerenderHostObserver prerender_observer(*web_contents(), host_id);
NavigatePrimaryPage(prerendering_url);
prerender_observer.WaitForActivation();
ExpectFinalStatusForSpeculationRule(PrerenderFinalStatus::kActivated);
}
// See the comment on PrerenderCOOPWithoutV8Optimizer test for details. This
// test ensures that prerendering is enabled regardless of whether the target
// page has the COOP, when the V8 optimizer is disabled.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
PrerenderNonCOOPWithoutV8Optimizer) {
// Disable the V8 optimizer.
V8OptimizerContentBrowserClient test_browser_client(/*disable=*/true);
const GURL initial_url = GetUrl("/empty.html");
const GURL prerendering_url = GetUrl("/empty.html?prerender");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
ASSERT_EQ(web_contents()->GetLastCommittedURL(), initial_url);
FrameTreeNodeId host_id = AddPrerender(prerendering_url);
test::PrerenderHostObserver prerender_observer(*web_contents(), host_id);
NavigatePrimaryPage(prerendering_url);
prerender_observer.WaitForActivation();
ExpectFinalStatusForSpeculationRule(PrerenderFinalStatus::kActivated);
}
// See the comment on PrerenderCOOPWithoutV8Optimizer test for details. This
// test ensures that prerendering a page that has the COOP succeeds when the V8
// optimizer is enabled.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderCOOPWithV8Optimizer) {
// Enable the V8 optimizer.
V8OptimizerContentBrowserClient test_browser_client(/*disable=*/false);
const GURL initial_url = GetUrl("/empty.html");
const GURL prerendering_url =
GetUrl("/set-header?Cross-Origin-Opener-Policy: same-origin");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
ASSERT_EQ(web_contents()->GetLastCommittedURL(), initial_url);
// Start prerendering a page that has the COOP.
FrameTreeNodeId host_id = AddPrerender(prerendering_url);
ASSERT_TRUE(host_id);
// Activate the prerendered page.
NavigatePrimaryPage(prerendering_url);
ExpectFinalStatusForSpeculationRule(PrerenderFinalStatus::kActivated);
}
// Many of these tests navigate away from a page and then test whether the back
// navigation entry can be prerendered. This is parameterized on whether the
// navigation away from the original page is browser or renderer initiated.
class PrerenderSessionHistoryBrowserTest
: public PrerenderBrowserTest,
public testing::WithParamInterface<bool> {
public:
static std::string DescribeParams(
const testing::TestParamInfo<ParamType>& info) {
return info.param ? "FromBrowser" : "FromRenderer";
}
// Navigate `web_contents` to `url`. The test parameterization determines
// whether to do a browser initiated navigation or a renderer initiated
// navigation.
void NavigateAway(WebContentsImpl* web_contents, const GURL& url) {
const bool from_browser = GetParam();
if (from_browser) {
ASSERT_TRUE(NavigateToURL(web_contents, url));
} else {
ASSERT_TRUE(NavigateToURLFromRenderer(web_contents, url));
}
}
// Tests in this fixture generally begin by setting up a back navigation
// entry, with `url1` being the back navigation entry and `url2` being the
// last committed entry.
void PerformInitialNavigations(WebContentsImpl* web_contents,
const GURL& url1,
const GURL& url2) {
ASSERT_TRUE(NavigateToURL(web_contents, url1));
NavigateAway(web_contents, url2);
}
void PredictBackNavigation(WebContentsImpl* web_contents) {
PrerenderHostRegistry* registry = web_contents->GetPrerenderHostRegistry();
// For testing convenience, pretend that the mouse back button is the
// predictor.
const auto predictor = content_preloading_predictor::kMouseBackButton;
registry->BackNavigationLikely(predictor);
WaitForHttpCacheQueryCompletion(web_contents);
}
void PerformBackNavigation(WebContentsImpl* web_contents) {
NavigationControllerImpl& controller = web_contents->GetController();
ASSERT_TRUE(controller.CanGoBack());
TestNavigationObserver back_observer(web_contents);
controller.GoBack();
back_observer.Wait();
}
void WaitForHttpCacheQueryCompletion(WebContentsImpl* web_contents) {
PrerenderHostRegistry* registry = web_contents->GetPrerenderHostRegistry();
EXPECT_TRUE(base::test::RunUntil(
[&]() { return !registry->HasOngoingHttpCacheQueryForTesting(); }));
}
void ClearBackForwardCache(WebContentsImpl* web_contents) {
web_contents->GetController().GetBackForwardCache().Flush();
}
void ClearAllCaches(WebContentsImpl* web_contents) {
BrowsingDataRemover* cache_remover =
web_contents->GetBrowserContext()->GetBrowsingDataRemover();
BrowsingDataRemoverCompletionObserver cache_clear_completion_observer(
cache_remover);
cache_remover->RemoveAndReply(
base::Time::Min(), base::Time::Max(),
BrowsingDataRemover::DATA_TYPE_CACHE,
BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB,
&cache_clear_completion_observer);
cache_clear_completion_observer.BlockUntilCompletion();
}
void ExpectAttemptUkm(ukm::TestUkmRecorder& ukm_recorder,
bool accurate,
PreloadingEligibility eligibility,
ukm::SourceId source_id) {
std::vector<ukm::TestUkmRecorder::HumanReadableUkmEntry> attempts =
ukm_recorder.GetEntries(ukm::builders::Preloading_Attempt::kEntryName,
test::kPreloadingAttemptUkmMetrics);
ASSERT_EQ(attempts.size(), 1u);
const auto predictor = content_preloading_predictor::kMouseBackButton;
const PreloadingHoldbackStatus holdback_status =
eligibility == PreloadingEligibility::kEligible
? PreloadingHoldbackStatus::kAllowed
: PreloadingHoldbackStatus::kUnspecified;
const PreloadingTriggeringOutcome triggering_outcome =
eligibility == PreloadingEligibility::kEligible
? PreloadingTriggeringOutcome::kNoOp
: PreloadingTriggeringOutcome::kUnspecified;
test::PreloadingAttemptUkmEntryBuilder entry_builder(predictor);
ukm::TestUkmRecorder::HumanReadableUkmEntry expected_entry =
entry_builder.BuildEntry(
source_id, PreloadingType::kPrerender, eligibility, holdback_status,
triggering_outcome, PreloadingFailureReason::kUnspecified,
accurate);
EXPECT_EQ(attempts[0], expected_entry)
<< test::ActualVsExpectedUkmEntryToString(attempts[0], expected_entry);
}
};
INSTANTIATE_TEST_SUITE_P(All,
PrerenderSessionHistoryBrowserTest,
testing::Bool(),
PrerenderSessionHistoryBrowserTest::DescribeParams);
// Other tests in `PrerenderSessionHistoryBrowserTest` explicitly trigger the
// prediction and the navigation. For this test, we actually simulate the back
// button press events.
IN_PROC_BROWSER_TEST_P(PrerenderSessionHistoryBrowserTest,
BackButtonNavigation) {
const GURL url1 = GetUrl("/title1.html");
const GURL url2 = GetCrossSiteUrl("/title2.html");
PerformInitialNavigations(web_contents_impl(), url1, url2);
ClearBackForwardCache(web_contents_impl());
base::HistogramTester histogram_tester;
NavigationControllerImpl& controller = web_contents_impl()->GetController();
ASSERT_TRUE(controller.CanGoBack());
TestNavigationObserver back_observer(web_contents_impl());
InputEventAckWaiter mouse_down_waiter(
web_contents_impl()->GetPrimaryMainFrame()->GetRenderWidgetHost(),
blink::WebInputEvent::Type::kMouseDown);
const gfx::Point click_location(50, 50);
SimulateMouseEvent(web_contents_impl(),
blink::WebInputEvent::Type::kMouseDown,
blink::WebMouseEvent::Button::kBack, click_location);
// The mouse up triggers the navigation. We wait until after the cache query
// to send the mouse up to ensure the navigation happens after the browser
// decides whether to prerender.
mouse_down_waiter.Wait();
WaitForHttpCacheQueryCompletion(web_contents_impl());
SimulateMouseEvent(web_contents_impl(), blink::WebInputEvent::Type::kMouseUp,
blink::WebMouseEvent::Button::kBack, click_location);
back_observer.Wait();
histogram_tester.ExpectUniqueSample(
"Preloading.PrerenderBackNavigationEligibility.MouseBackButton",
PrerenderBackNavigationEligibility::kEligible, 1);
}
IN_PROC_BROWSER_TEST_P(PrerenderSessionHistoryBrowserTest,
PredictionForEligibleBackNavigation) {
const GURL url1 = GetUrl("/title1.html");
const GURL url2 = GetCrossSiteUrl("/title2.html");
PerformInitialNavigations(web_contents_impl(), url1, url2);
ClearBackForwardCache(web_contents_impl());
base::HistogramTester histogram_tester;
ukm::TestAutoSetUkmRecorder ukm_recorder;
PredictBackNavigation(web_contents_impl());
PerformBackNavigation(web_contents_impl());
ukm::SourceId source_id =
web_contents_impl()->GetPrimaryMainFrame()->GetPageUkmSourceId();
histogram_tester.ExpectUniqueSample(
"Preloading.PrerenderBackNavigationEligibility.MouseBackButton",
PrerenderBackNavigationEligibility::kEligible, 1);
histogram_tester.ExpectUniqueSample(
"Preloading.Predictor.MouseBackButton.Precision",
PredictorConfusionMatrix::kTruePositive, 1);
histogram_tester.ExpectUniqueSample(
"Preloading.Predictor.MouseBackButton.Recall",
PredictorConfusionMatrix::kTruePositive, 1);
histogram_tester.ExpectUniqueSample(
"Preloading.Prerender.Attempt.MouseBackButton.Precision",
PredictorConfusionMatrix::kTruePositive, 1);
histogram_tester.ExpectUniqueSample(
"Preloading.Prerender.Attempt.MouseBackButton.Recall",
PredictorConfusionMatrix::kTruePositive, 1);
ExpectAttemptUkm(ukm_recorder, true, PreloadingEligibility::kEligible,
source_id);
}
IN_PROC_BROWSER_TEST_P(PrerenderSessionHistoryBrowserTest,
NoPredictionDueToBfcache) {
if (!BackForwardCache::IsBackForwardCacheFeatureEnabled()) {
GTEST_SKIP()
<< "This test assumes the back navigation is restoring from bfcache.";
}
const GURL url1 = GetUrl("/title1.html");
const GURL url2 = GetCrossSiteUrl("/title2.html");
PerformInitialNavigations(web_contents_impl(), url1, url2);
base::HistogramTester histogram_tester;
PredictBackNavigation(web_contents_impl());
PerformBackNavigation(web_contents_impl());
histogram_tester.ExpectUniqueSample(
"Preloading.PrerenderBackNavigationEligibility.MouseBackButton",
PrerenderBackNavigationEligibility::kBfcacheEntryExists, 1);
histogram_tester.ExpectTotalCount(
"Preloading.Predictor.MouseBackButton.Precision", 0);
histogram_tester.ExpectTotalCount(
"Preloading.Predictor.MouseBackButton.Recall", 0);
histogram_tester.ExpectTotalCount(
"Preloading.Prerender.Attempt.MouseBackButton.Precision", 0);
histogram_tester.ExpectTotalCount(
"Preloading.Prerender.Attempt.MouseBackButton.Recall", 0);
}
IN_PROC_BROWSER_TEST_P(PrerenderSessionHistoryBrowserTest,
RendererNavigationAfterBackPrediction) {
const GURL url1 = GetUrl("/title1.html");
const GURL url2 = GetCrossSiteUrl("/title2.html");
const GURL url3 = GetCrossSiteUrl("/title3.html");
PerformInitialNavigations(web_contents_impl(), url1, url2);
ClearBackForwardCache(web_contents_impl());
base::HistogramTester histogram_tester;
ukm::TestAutoSetUkmRecorder ukm_recorder;
PredictBackNavigation(web_contents_impl());
TestNavigationObserver nav_observer(web_contents_impl());
ASSERT_TRUE(ExecJs(web_contents_impl(), JsReplace("location = $1;", url3)));
nav_observer.Wait();
ukm::SourceId source_id =
web_contents_impl()->GetPrimaryMainFrame()->GetPageUkmSourceId();
histogram_tester.ExpectUniqueSample(
"Preloading.PrerenderBackNavigationEligibility.MouseBackButton",
PrerenderBackNavigationEligibility::kEligible, 1);
histogram_tester.ExpectUniqueSample(
"Preloading.Predictor.MouseBackButton.Precision",
PredictorConfusionMatrix::kFalsePositive, 1);
// A renderer navigation is not a false negative for this predictor.
histogram_tester.ExpectTotalCount(
"Preloading.Predictor.MouseBackButton.Recall", 0);
histogram_tester.ExpectUniqueSample(
"Preloading.Prerender.Attempt.MouseBackButton.Precision",
PredictorConfusionMatrix::kFalsePositive, 1);
histogram_tester.ExpectTotalCount(
"Preloading.Prerender.Attempt.MouseBackButton.Recall", 0);
ExpectAttemptUkm(ukm_recorder, false, PreloadingEligibility::kEligible,
source_id);
}
IN_PROC_BROWSER_TEST_P(PrerenderSessionHistoryBrowserTest,
NotEligibleForSameDocument) {
const GURL url1 = GetUrl("/title1.html");
const GURL url2 = GetUrl("/title1.html#same");
PerformInitialNavigations(web_contents_impl(), url1, url2);
base::HistogramTester histogram_tester;
PredictBackNavigation(web_contents_impl());
PerformBackNavigation(web_contents_impl());
histogram_tester.ExpectUniqueSample(
"Preloading.PrerenderBackNavigationEligibility.MouseBackButton",
PrerenderBackNavigationEligibility::kTargetIsSameDocument, 1);
histogram_tester.ExpectTotalCount(
"Preloading.Predictor.MouseBackButton.Precision", 0);
histogram_tester.ExpectTotalCount(
"Preloading.Predictor.MouseBackButton.Recall", 0);
histogram_tester.ExpectTotalCount(
"Preloading.Prerender.Attempt.MouseBackButton.Precision", 0);
histogram_tester.ExpectTotalCount(
"Preloading.Prerender.Attempt.MouseBackButton.Recall", 0);
}
IN_PROC_BROWSER_TEST_P(PrerenderSessionHistoryBrowserTest,
NotEligibleForSameSite) {
const GURL url1 = GetUrl("/title1.html");
const GURL url2 = GetSameSiteCrossOriginUrl("/title2.html");
PerformInitialNavigations(web_contents_impl(), url1, url2);
ClearBackForwardCache(web_contents_impl());
base::HistogramTester histogram_tester;
ukm::TestAutoSetUkmRecorder ukm_recorder;
PredictBackNavigation(web_contents_impl());
PerformBackNavigation(web_contents_impl());
ukm::SourceId source_id =
web_contents_impl()->GetPrimaryMainFrame()->GetPageUkmSourceId();
histogram_tester.ExpectUniqueSample(
"Preloading.PrerenderBackNavigationEligibility.MouseBackButton",
PrerenderBackNavigationEligibility::kTargetIsSameSite, 1);
histogram_tester.ExpectUniqueSample(
"Preloading.Predictor.MouseBackButton.Precision",
PredictorConfusionMatrix::kTruePositive, 1);
histogram_tester.ExpectUniqueSample(
"Preloading.Predictor.MouseBackButton.Recall",
PredictorConfusionMatrix::kTruePositive, 1);
histogram_tester.ExpectUniqueSample(
"Preloading.Prerender.Attempt.MouseBackButton.Precision",
PredictorConfusionMatrix::kTruePositive, 1);
histogram_tester.ExpectUniqueSample(
"Preloading.Prerender.Attempt.MouseBackButton.Recall",
PredictorConfusionMatrix::kTruePositive, 1);
ExpectAttemptUkm(ukm_recorder, true,
ToPreloadingEligibility(
PrerenderBackNavigationEligibility::kTargetIsSameSite),
source_id);
}
IN_PROC_BROWSER_TEST_P(PrerenderSessionHistoryBrowserTest,
NotEligibleForUncached) {
const GURL url1 = GetUrl("/title1.html");
const GURL url2 = GetCrossSiteUrl("/title2.html");
PerformInitialNavigations(web_contents_impl(), url1, url2);
// Ensure `url1` is not served from the HTTP cache or bfcache.
ClearAllCaches(web_contents_impl());
base::HistogramTester histogram_tester;
ukm::TestAutoSetUkmRecorder ukm_recorder;
PredictBackNavigation(web_contents_impl());
PerformBackNavigation(web_contents_impl());
ukm::SourceId source_id =
web_contents_impl()->GetPrimaryMainFrame()->GetPageUkmSourceId();
histogram_tester.ExpectUniqueSample(
"Preloading.PrerenderBackNavigationEligibility.MouseBackButton",
PrerenderBackNavigationEligibility::kNoHttpCacheEntry, 1);
histogram_tester.ExpectUniqueSample(
"Preloading.Predictor.MouseBackButton.Precision",
PredictorConfusionMatrix::kTruePositive, 1);
histogram_tester.ExpectUniqueSample(
"Preloading.Predictor.MouseBackButton.Recall",
PredictorConfusionMatrix::kTruePositive, 1);
histogram_tester.ExpectUniqueSample(
"Preloading.Prerender.Attempt.MouseBackButton.Precision",
PredictorConfusionMatrix::kTruePositive, 1);
histogram_tester.ExpectUniqueSample(
"Preloading.Prerender.Attempt.MouseBackButton.Recall",
PredictorConfusionMatrix::kTruePositive, 1);
ExpectAttemptUkm(ukm_recorder, true,
ToPreloadingEligibility(
PrerenderBackNavigationEligibility::kNoHttpCacheEntry),
source_id);
}
IN_PROC_BROWSER_TEST_P(PrerenderSessionHistoryBrowserTest,
NotEligibleForPostMethod) {
const GURL url1 = GetUrl("/form_that_posts_to_echoall.html");
const GURL url2 = GetUrl("/echoall");
const GURL url3 = GetCrossSiteUrl("/title1.html");
ASSERT_TRUE(NavigateToURL(shell(), url1));
TestNavigationObserver form_post_observer(web_contents_impl());
ASSERT_TRUE(
ExecJs(web_contents_impl(), "document.getElementById('form').submit();"));
form_post_observer.Wait();
ASSERT_EQ(url2, web_contents_impl()->GetLastCommittedURL());
ASSERT_TRUE(web_contents_impl()
->GetController()
.GetLastCommittedEntry()
->GetHasPostData());
NavigateAway(web_contents_impl(), url3);
ClearBackForwardCache(web_contents_impl());
base::HistogramTester histogram_tester;
ukm::TestAutoSetUkmRecorder ukm_recorder;
PredictBackNavigation(web_contents_impl());
PerformBackNavigation(web_contents_impl());
ukm::SourceId source_id =
web_contents_impl()->GetPrimaryMainFrame()->GetPageUkmSourceId();
histogram_tester.ExpectUniqueSample(
"Preloading.PrerenderBackNavigationEligibility.MouseBackButton",
PrerenderBackNavigationEligibility::kMethodNotGet, 1);
histogram_tester.ExpectUniqueSample(
"Preloading.Predictor.MouseBackButton.Precision",
PredictorConfusionMatrix::kTruePositive, 1);
// A POST navigation is not a false negative for this predictor.
histogram_tester.ExpectTotalCount(
"Preloading.Predictor.MouseBackButton.Recall", 0);
histogram_tester.ExpectUniqueSample(
"Preloading.Prerender.Attempt.MouseBackButton.Precision",
PredictorConfusionMatrix::kTruePositive, 1);
histogram_tester.ExpectTotalCount(
"Preloading.Prerender.Attempt.MouseBackButton.Recall", 0);
ExpectAttemptUkm(ukm_recorder, true,
ToPreloadingEligibility(
PrerenderBackNavigationEligibility::kMethodNotGet),
source_id);
}
IN_PROC_BROWSER_TEST_P(PrerenderSessionHistoryBrowserTest,
NotEligibleForFailedNavigation) {
const GURL url1 = GetUrl("/page404.html");
const GURL url2 = GetCrossSiteUrl("/title1.html");
PerformInitialNavigations(web_contents_impl(), url1, url2);
ClearBackForwardCache(web_contents_impl());
base::HistogramTester histogram_tester;
ukm::TestAutoSetUkmRecorder ukm_recorder;
PredictBackNavigation(web_contents_impl());
PerformBackNavigation(web_contents_impl());
ukm::SourceId source_id =
web_contents_impl()->GetPrimaryMainFrame()->GetPageUkmSourceId();
histogram_tester.ExpectUniqueSample(
"Preloading.PrerenderBackNavigationEligibility.MouseBackButton",
PrerenderBackNavigationEligibility::kTargetIsFailedNavigation, 1);
histogram_tester.ExpectUniqueSample(
"Preloading.Predictor.MouseBackButton.Precision",
PredictorConfusionMatrix::kTruePositive, 1);
histogram_tester.ExpectUniqueSample(
"Preloading.Predictor.MouseBackButton.Recall",
PredictorConfusionMatrix::kTruePositive, 1);
histogram_tester.ExpectUniqueSample(
"Preloading.Prerender.Attempt.MouseBackButton.Precision",
PredictorConfusionMatrix::kTruePositive, 1);
histogram_tester.ExpectUniqueSample(
"Preloading.Prerender.Attempt.MouseBackButton.Recall",
PredictorConfusionMatrix::kTruePositive, 1);
ExpectAttemptUkm(
ukm_recorder, true,
ToPreloadingEligibility(
PrerenderBackNavigationEligibility::kTargetIsFailedNavigation),
source_id);
}
IN_PROC_BROWSER_TEST_P(PrerenderSessionHistoryBrowserTest,
NotEligibleForNonHttpScheme) {
const GURL url1 = GURL("data:text/html,test");
const GURL url2 = GetUrl("/title1.html");
PerformInitialNavigations(web_contents_impl(), url1, url2);
ClearBackForwardCache(web_contents_impl());
base::HistogramTester histogram_tester;
ukm::TestAutoSetUkmRecorder ukm_recorder;
PredictBackNavigation(web_contents_impl());
PerformBackNavigation(web_contents_impl());
ukm::SourceId source_id =
web_contents_impl()->GetPrimaryMainFrame()->GetPageUkmSourceId();
histogram_tester.ExpectUniqueSample(
"Preloading.PrerenderBackNavigationEligibility.MouseBackButton",
PrerenderBackNavigationEligibility::kTargetIsNonHttp, 1);
histogram_tester.ExpectUniqueSample(
"Preloading.Predictor.MouseBackButton.Precision",
PredictorConfusionMatrix::kTruePositive, 1);
// A navigation to a data URL is not a false negative for this predictor.
histogram_tester.ExpectTotalCount(
"Preloading.Predictor.MouseBackButton.Recall", 0);
histogram_tester.ExpectUniqueSample(
"Preloading.Prerender.Attempt.MouseBackButton.Precision",
PredictorConfusionMatrix::kTruePositive, 1);
histogram_tester.ExpectTotalCount(
"Preloading.Prerender.Attempt.MouseBackButton.Recall", 0);
ExpectAttemptUkm(ukm_recorder, true,
ToPreloadingEligibility(
PrerenderBackNavigationEligibility::kTargetIsNonHttp),
source_id);
}
// Returns whether the two given windows can script each other.
// Assumes `opener` has a variable named `newWindow` which refers to `openee`.
bool IsScriptable(WebContentsImpl* opener, WebContentsImpl* openee) {
// Have `opener` set a property such that `openee` can read it.
const std::string kPropName = "mrPostman";
const std::string kPropValue = "a property for me";
if (EvalJs(opener, JsReplace(R"((() => {
let result = '';
try {
newWindow[$1] = $2;
result = newWindow[$1] || '';
} catch {}
return result;
})();)",
kPropName, kPropValue))
.ExtractString() != kPropValue) {
return false;
}
return EvalJs(openee, JsReplace("window[$1] || '';", kPropName))
.ExtractString() == kPropValue;
}
IN_PROC_BROWSER_TEST_P(PrerenderSessionHistoryBrowserTest,
NotEligibleForRelatedActiveContents) {
const GURL url1 = GetUrl("/title1.html");
const GURL url2 = GetCrossSiteUrl("/title2.html");
ASSERT_TRUE(NavigateToURL(shell(), url1));
RenderFrameHostImplWrapper opener_rfh(current_frame_host());
EXPECT_EQ(1u, opener_rfh->GetSiteInstance()->GetRelatedActiveContentsCount());
ShellAddedObserver shell_observer;
EXPECT_TRUE(
ExecJs(shell(), JsReplace("window.newWindow = window.open($1);", url1)));
Shell* popup = shell_observer.GetShell();
WebContentsImpl* popup_contents =
static_cast<WebContentsImpl*>(popup->web_contents());
EXPECT_TRUE(WaitForLoadStop(popup_contents));
EXPECT_TRUE(IsScriptable(web_contents_impl(), popup_contents));
EXPECT_EQ(2u, opener_rfh->GetSiteInstance()->GetRelatedActiveContentsCount());
NavigateAway(popup_contents, url2);
ClearBackForwardCache(popup_contents);
EXPECT_FALSE(IsScriptable(web_contents_impl(), popup_contents));
RenderFrameHostImplWrapper cross_site_popup_rfh(
popup_contents->GetPrimaryMainFrame());
// Whether the SiteInstance changes depends on the process model. The default
// SiteInstance could be in use.
if (cross_site_popup_rfh->GetSiteInstance() ==
opener_rfh->GetSiteInstance()) {
EXPECT_EQ(2u,
opener_rfh->GetSiteInstance()->GetRelatedActiveContentsCount());
} else if (cross_site_popup_rfh->GetSiteInstance()->IsRelatedSiteInstance(
opener_rfh->GetSiteInstance())) {
EXPECT_EQ(2u,
opener_rfh->GetSiteInstance()->GetRelatedActiveContentsCount());
} else {
// `NavigateAway` may have swapped BrowsingInstances depending on test
// parameterization.
EXPECT_EQ(1u,
opener_rfh->GetSiteInstance()->GetRelatedActiveContentsCount());
}
// `opener_rfh` is active and is using the same BrowsingInstance as the
// popup's back navigation entry, so it would not be safe to prerender for
// that entry.
SiteInstanceImpl* target_site_instance =
popup_contents->GetController().GetEntryAtOffset(-1)->site_instance();
EXPECT_TRUE(opener_rfh->GetSiteInstance()->IsRelatedSiteInstance(
target_site_instance));
base::HistogramTester histogram_tester;
ukm::TestAutoSetUkmRecorder ukm_recorder;
PredictBackNavigation(popup_contents);
PerformBackNavigation(popup_contents);
EXPECT_TRUE(IsScriptable(web_contents_impl(), popup_contents));
EXPECT_EQ(2u, opener_rfh->GetSiteInstance()->GetRelatedActiveContentsCount());
ukm::SourceId source_id =
popup_contents->GetPrimaryMainFrame()->GetPageUkmSourceId();
histogram_tester.ExpectUniqueSample(
"Preloading.PrerenderBackNavigationEligibility.MouseBackButton",
PrerenderBackNavigationEligibility::kRelatedActiveContents, 1);
histogram_tester.ExpectUniqueSample(
"Preloading.Predictor.MouseBackButton.Precision",
PredictorConfusionMatrix::kTruePositive, 1);
histogram_tester.ExpectUniqueSample(
"Preloading.Predictor.MouseBackButton.Recall",
PredictorConfusionMatrix::kTruePositive, 1);
histogram_tester.ExpectUniqueSample(
"Preloading.Prerender.Attempt.MouseBackButton.Precision",
PredictorConfusionMatrix::kTruePositive, 1);
histogram_tester.ExpectUniqueSample(
"Preloading.Prerender.Attempt.MouseBackButton.Recall",
PredictorConfusionMatrix::kTruePositive, 1);
ExpectAttemptUkm(
ukm_recorder, true,
ToPreloadingEligibility(
PrerenderBackNavigationEligibility::kRelatedActiveContents),
source_id);
}
IN_PROC_BROWSER_TEST_P(PrerenderSessionHistoryBrowserTest,
PredictAfterOpeneeDestroyed) {
const GURL url1 = GetUrl("/title1.html");
const GURL url2 = GetCrossSiteUrl("/title2.html");
ASSERT_TRUE(NavigateToURL(shell(), url1));
RenderFrameHostImplWrapper opener_rfh(current_frame_host());
ShellAddedObserver shell_observer;
EXPECT_TRUE(
ExecJs(shell(), JsReplace("window.newWindow = window.open($1);", url1)));
Shell* popup = shell_observer.GetShell();
WebContentsImpl* popup_contents =
static_cast<WebContentsImpl*>(popup->web_contents());
EXPECT_TRUE(WaitForLoadStop(popup_contents));
EXPECT_EQ(2u, opener_rfh->GetSiteInstance()->GetRelatedActiveContentsCount());
NavigateAway(web_contents_impl(), url2);
ClearBackForwardCache(web_contents_impl());
WebContentsDestroyedWatcher close_popup_waiter(popup_contents);
popup_contents->ClosePage();
close_popup_waiter.Wait();
// Unlike `NotEligibleForRelatedActiveContents`, there's no longer another
// WebContents which is sharing the BrowsingInstance of the back navigation
// entry, so it would be safe to prerender.
base::HistogramTester histogram_tester;
ukm::TestAutoSetUkmRecorder ukm_recorder;
PredictBackNavigation(web_contents_impl());
PerformBackNavigation(web_contents_impl());
ukm::SourceId source_id =
web_contents_impl()->GetPrimaryMainFrame()->GetPageUkmSourceId();
histogram_tester.ExpectUniqueSample(
"Preloading.PrerenderBackNavigationEligibility.MouseBackButton",
PrerenderBackNavigationEligibility::kEligible, 1);
histogram_tester.ExpectUniqueSample(
"Preloading.Predictor.MouseBackButton.Precision",
PredictorConfusionMatrix::kTruePositive, 1);
histogram_tester.ExpectUniqueSample(
"Preloading.Predictor.MouseBackButton.Recall",
PredictorConfusionMatrix::kTruePositive, 1);
histogram_tester.ExpectUniqueSample(
"Preloading.Prerender.Attempt.MouseBackButton.Precision",
PredictorConfusionMatrix::kTruePositive, 1);
histogram_tester.ExpectUniqueSample(
"Preloading.Prerender.Attempt.MouseBackButton.Recall",
PredictorConfusionMatrix::kTruePositive, 1);
ExpectAttemptUkm(ukm_recorder, true, PreloadingEligibility::kEligible,
source_id);
}
IN_PROC_BROWSER_TEST_P(PrerenderSessionHistoryBrowserTest,
BackNavigationOfCloneWebContents) {
const GURL url1 = GetUrl("/title1.html");
const GURL url2 = GetCrossSiteUrl("/title2.html");
PerformInitialNavigations(web_contents_impl(), url1, url2);
// Whether the navigation from `url1` to `url2` swapped BrowsingInstances
// depends on test parameterization and additional configuration options that
// are not particularly relevant for the intended scope of this test. So we'll
// just handle both possibilities as part of this test.
SiteInstanceImpl* prev_site_instance = web_contents_impl()
->GetController()
.GetEntryAtOffset(-1)
->site_instance();
const bool original_navs_swapped_browsing_instance =
!web_contents_impl()->GetSiteInstance()->IsRelatedSiteInstance(
prev_site_instance);
FakeWebContentsDelegate clone_delegate;
std::unique_ptr<WebContents> new_web_contents_owned =
web_contents_impl()->Clone();
WebContentsImpl* new_web_contents =
static_cast<WebContentsImpl*>(new_web_contents_owned.get());
new_web_contents->SetDelegate(&clone_delegate);
TestNavigationObserver clone_load_observer(new_web_contents);
new_web_contents->GetController().LoadIfNecessary();
clone_load_observer.Wait();
base::HistogramTester histogram_tester;
ukm::TestAutoSetUkmRecorder ukm_recorder;
PredictBackNavigation(new_web_contents);
PerformBackNavigation(new_web_contents);
const PrerenderBackNavigationEligibility expected_eligibility =
original_navs_swapped_browsing_instance
? PrerenderBackNavigationEligibility::kEligible
: PrerenderBackNavigationEligibility::kRelatedActiveContents;
ukm::SourceId source_id =
new_web_contents->GetPrimaryMainFrame()->GetPageUkmSourceId();
histogram_tester.ExpectUniqueSample(
"Preloading.PrerenderBackNavigationEligibility.MouseBackButton",
expected_eligibility, 1);
histogram_tester.ExpectUniqueSample(
"Preloading.Predictor.MouseBackButton.Precision",
PredictorConfusionMatrix::kTruePositive, 1);
histogram_tester.ExpectUniqueSample(
"Preloading.Predictor.MouseBackButton.Recall",
PredictorConfusionMatrix::kTruePositive, 1);
histogram_tester.ExpectUniqueSample(
"Preloading.Prerender.Attempt.MouseBackButton.Precision",
PredictorConfusionMatrix::kTruePositive, 1);
histogram_tester.ExpectUniqueSample(
"Preloading.Prerender.Attempt.MouseBackButton.Recall",
PredictorConfusionMatrix::kTruePositive, 1);
ExpectAttemptUkm(ukm_recorder, true,
ToPreloadingEligibility(expected_eligibility), source_id);
}
IN_PROC_BROWSER_TEST_P(
PrerenderSessionHistoryBrowserTest,
BackNavigationOfClonedWebContentsWithOriginalAtTargetEntry) {
const GURL url1 = GetUrl("/title1.html");
const GURL url2 = GetCrossSiteUrl("/title2.html");
PerformInitialNavigations(web_contents_impl(), url1, url2);
FakeWebContentsDelegate clone_delegate;
std::unique_ptr<WebContents> new_web_contents_owned =
web_contents_impl()->Clone();
WebContentsImpl* new_web_contents =
static_cast<WebContentsImpl*>(new_web_contents_owned.get());
new_web_contents->SetDelegate(&clone_delegate);
TestNavigationObserver clone_load_observer(new_web_contents);
new_web_contents->GetController().LoadIfNecessary();
clone_load_observer.Wait();
PerformBackNavigation(web_contents_impl());
base::HistogramTester histogram_tester;
ukm::TestAutoSetUkmRecorder ukm_recorder;
PredictBackNavigation(new_web_contents);
PerformBackNavigation(new_web_contents);
ukm::SourceId source_id =
new_web_contents->GetPrimaryMainFrame()->GetPageUkmSourceId();
histogram_tester.ExpectUniqueSample(
"Preloading.PrerenderBackNavigationEligibility.MouseBackButton",
PrerenderBackNavigationEligibility::kRelatedActiveContents, 1);
histogram_tester.ExpectUniqueSample(
"Preloading.Predictor.MouseBackButton.Precision",
PredictorConfusionMatrix::kTruePositive, 1);
histogram_tester.ExpectUniqueSample(
"Preloading.Predictor.MouseBackButton.Recall",
PredictorConfusionMatrix::kTruePositive, 1);
histogram_tester.ExpectUniqueSample(
"Preloading.Prerender.Attempt.MouseBackButton.Precision",
PredictorConfusionMatrix::kTruePositive, 1);
histogram_tester.ExpectUniqueSample(
"Preloading.Prerender.Attempt.MouseBackButton.Recall",
PredictorConfusionMatrix::kTruePositive, 1);
ExpectAttemptUkm(
ukm_recorder, true,
ToPreloadingEligibility(
PrerenderBackNavigationEligibility::kRelatedActiveContents),
source_id);
}
// PrerenderHosts created through speculation rules are not suitable for use in
// session history navigations. In particular, the SiteInstances would be
// mismatched.
IN_PROC_BROWSER_TEST_P(
PrerenderSessionHistoryBrowserTest,
BackButtonNavigationDoesNotUseSpeculationRulePrerenders) {
const GURL url1 = GetUrl("/title1.html");
const GURL url2 = GetUrl("/title2.html");
PerformInitialNavigations(web_contents_impl(), url1, url2);
ClearBackForwardCache(web_contents_impl());
FrameTreeNodeId host_id = AddPrerender(url1);
test::PrerenderHostObserver prerender_observer(*web_contents(), host_id);
PerformBackNavigation(web_contents_impl());
EXPECT_FALSE(prerender_observer.was_activated());
}
// Tests that the prerendering page does not crash when performing compositor
// warming up.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, WarmingUpCCDoesntInvokeCrashes) {
const GURL initial_url = GetUrl("/empty.html");
const GURL prerendering_url = GetUrl("/empty.html?prerender");
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
auto prerender_handle = AddEmbedderTriggeredPrerender(
prerendering_url, /*preloading_attempt=*/nullptr,
/*should_warm_up_compositor=*/true);
FrameTreeNodeId prerender_host_id =
static_cast<PrerenderHandleImpl*>(prerender_handle.get())
->frame_tree_node_id_for_testing();
test::PrerenderHostObserver prerender_observer(*web_contents(),
prerender_host_id);
NavigatePrimaryPageFromAddressBar(prerendering_url);
prerender_observer.WaitForActivation();
EXPECT_EQ(web_contents()->GetLastCommittedURL(), prerendering_url);
EXPECT_TRUE(prerender_observer.was_activated());
}
class PrerenderTargetHintKillSwitchBrowserTest : public PrerenderBrowserTest {
public:
PrerenderTargetHintKillSwitchBrowserTest() {
feature_list_.InitWithFeatures({}, {blink::features::kPrerender2InNewTab});
}
void SetUpCommandLine(base::CommandLine* command_line) override {
PrerenderBrowserTest::SetUpCommandLine(command_line);
command_line->AppendSwitchASCII("enable-blink-features",
"SpeculationRulesTargetHint");
}
private:
base::test::ScopedFeatureList feature_list_;
};
IN_PROC_BROWSER_TEST_F(PrerenderTargetHintKillSwitchBrowserTest,
Prerender2InNewTabKillSwitch) {
const GURL initial_url = GetUrl("/simple_links.html");
const GURL prerender_url = GetUrl("/title2.html");
// Navigate to an initial page which has a link to `prerender_url`.
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
// Start prerendering `prerender_url`.
test::PrerenderHostCreationWaiter host_creation_waiter;
AddPrerendersAsync({prerender_url},
/*eagerness=*/std::nullopt,
/*target_hint=*/"_blank");
FrameTreeNodeId host_id = host_creation_waiter.Wait();
auto* prerender_web_contents = WebContents::FromFrameTreeNodeId(host_id);
// kPrerender2InNewTab is expected to suppress Prerendering into new tab and
// the prerendered page is expected to fall back into same tab version.
ASSERT_EQ(prerender_web_contents, web_contents_impl());
}
} // namespace content
|