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
|
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/web_contents/web_contents_impl.h"
#include <algorithm>
#include <array>
#include <optional>
#include <tuple>
#include <utility>
#include <vector>
#include "base/allocator/partition_alloc_features.h"
#include "base/command_line.h"
#include "base/containers/contains.h"
#include "base/feature_list.h"
#include "base/files/file_util.h"
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/ref_counted.h"
#include "base/path_service.h"
#include "base/run_loop.h"
#include "base/strings/pattern.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/single_thread_task_runner.h"
#include "base/test/bind.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/run_until.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/test_future.h"
#include "base/test/test_timeouts.h"
#include "base/threading/thread_restrictions.h"
#include "base/time/time.h"
#include "base/values.h"
#include "build/build_config.h"
#include "components/fingerprinting_protection_filter/interventions/common/interventions_features.h"
#include "components/input/render_widget_host_input_event_router.h"
#include "components/ukm/test_ukm_recorder.h"
#include "components/url_formatter/url_formatter.h"
#include "content/browser/preloading/prerender/prerender_host_registry.h"
#include "content/browser/renderer_host/cross_process_frame_connector.h"
#include "content/browser/renderer_host/frame_tree.h"
#include "content/browser/renderer_host/navigation_entry_impl.h"
#include "content/browser/renderer_host/navigation_entry_restore_context_impl.h"
#include "content/browser/renderer_host/navigation_request.h"
#include "content/browser/renderer_host/render_frame_host_impl.h"
#include "content/browser/renderer_host/render_process_host_impl.h"
#include "content/browser/renderer_host/render_widget_host_impl.h"
#include "content/browser/renderer_host/text_input_manager.h"
#include "content/browser/web_contents/web_contents_view.h"
#include "content/common/content_navigation_policy.h"
#include "content/common/frame.mojom-test-utils.h"
#include "content/common/frame.mojom.h"
#include "content/public/browser/back_forward_cache.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/file_select_listener.h"
#include "content/public/browser/global_routing_id.h"
#include "content/public/browser/host_zoom_map.h"
#include "content/public/browser/invalidate_type.h"
#include "content/public/browser/javascript_dialog_manager.h"
#include "content/public/browser/media_player_id.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/browser/site_isolation_policy.h"
#include "content/public/browser/unowned_inner_web_contents_client.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_delegate.h"
#include "content/public/browser/web_contents_observer.h"
#include "content/public/common/content_client.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_paths.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/isolated_world_ids.h"
#include "content/public/common/url_constants.h"
#include "content/public/test/back_forward_cache_util.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/content_browser_test.h"
#include "content/public/test/content_browser_test_utils.h"
#include "content/public/test/fenced_frame_test_util.h"
#include "content/public/test/mock_client_hints_controller_delegate.h"
#include "content/public/test/mock_web_contents_observer.h"
#include "content/public/test/navigation_handle_observer.h"
#include "content/public/test/no_renderer_crashes_assertion.h"
#include "content/public/test/prerender_test_util.h"
#include "content/public/test/resource_load_observer.h"
#include "content/public/test/test_navigation_observer.h"
#include "content/public/test/test_utils.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/shell/browser/shell_content_browser_client.h"
#include "content/test/content_browser_test_utils_internal.h"
#include "content/test/mock_reduce_accept_language_controller_delegate.h"
#include "content/test/test_content_browser_client.h"
#include "mojo/public/cpp/test_support/test_utils.h"
#include "net/base/features.h"
#include "net/base/ip_endpoint.h"
#include "net/base/network_isolation_key.h"
#include "net/dns/mock_host_resolver.h"
#include "net/test/embedded_test_server/controllable_http_response.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "net/test/embedded_test_server/expectation_handler.h"
#include "partition_alloc/buildflags.h"
#include "services/metrics/public/cpp/ukm_builders.h"
#include "services/network/public/cpp/client_hints.h"
#include "services/network/public/cpp/features.h"
#include "services/network/public/mojom/web_client_hints_types.mojom.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "third_party/blink/public/common/client_hints/client_hints.h"
#include "third_party/blink/public/common/features.h"
#include "third_party/blink/public/common/page/page_zoom.h"
#include "third_party/blink/public/common/user_agent/user_agent_metadata.h"
#include "third_party/blink/public/mojom/frame/fullscreen.mojom.h"
#include "ui/base/clipboard/clipboard_format_type.h"
#include "ui/base/data_transfer_policy/data_transfer_endpoint.h"
#include "ui/color/color_provider_manager.h"
#include "ui/color/color_provider_utils.h"
#include "ui/display/screen.h"
#include "url/gurl.h"
namespace content {
#define SCOPE_TRACED(statement) \
{ \
SCOPED_TRACE(#statement); \
statement; \
}
void ResizeWebContentsView(Shell* shell,
const gfx::Size& size,
bool set_start_page) {
// Resizing the web content directly, independent of the Shell window,
// requires the RenderWidgetHostView to exist. So we do a navigation
// first if |set_start_page| is true.
if (set_start_page)
EXPECT_TRUE(NavigateToURL(shell, GURL(url::kAboutBlankURL)));
shell->ResizeWebContentForTests(size);
}
class WebContentsImplBrowserTest : public ContentBrowserTest {
public:
WebContentsImplBrowserTest() {
scoped_feature_list_.InitAndEnableFeature(
fingerprinting_protection_interventions::features::kCanvasNoise);
}
void SetUp() override {
RenderWidgetHostImpl::DisableResizeAckCheckForTesting();
ContentBrowserTest::SetUp();
}
WebContentsImplBrowserTest(const WebContentsImplBrowserTest&) = delete;
WebContentsImplBrowserTest& operator=(const WebContentsImplBrowserTest&) =
delete;
void SetUpOnMainThread() override {
// Setup the server to allow serving separate sites, so we can perform
// cross-process navigation.
host_resolver()->AddRule("*", "127.0.0.1");
}
bool IsInFullscreen() {
WebContentsImpl* web_contents =
static_cast<WebContentsImpl*>(shell()->web_contents());
return !!web_contents->current_fullscreen_frame_id_;
}
protected:
base::test::ScopedFeatureList scoped_feature_list_;
};
// Starts a new navigation as soon as the current one commits, but does not
// wait for it to complete. This allows us to observe DidStopLoading while
// a pending entry is present.
class NavigateOnCommitObserver : public WebContentsObserver {
public:
NavigateOnCommitObserver(Shell* shell, GURL url)
: WebContentsObserver(shell->web_contents()),
shell_(shell),
url_(url),
done_(false) {}
// WebContentsObserver:
void NavigationEntryCommitted(
const LoadCommittedDetails& load_details) override {
if (!done_) {
done_ = true;
shell_->LoadURL(url_);
// There should be a pending entry.
CHECK(shell_->web_contents()->GetController().GetPendingEntry());
// Now that there is a pending entry, stop the load.
shell_->Stop();
}
}
raw_ptr<Shell> shell_;
GURL url_;
bool done_;
};
class RenderViewSizeDelegate : public WebContentsDelegate {
public:
void set_size_insets(const gfx::Size& size_insets) {
size_insets_ = size_insets;
}
// WebContentsDelegate:
gfx::Size GetSizeForNewRenderView(WebContents* web_contents) override {
gfx::Size size(web_contents->GetContainerBounds().size());
size.Enlarge(size_insets_.width(), size_insets_.height());
return size;
}
private:
gfx::Size size_insets_;
};
class RenderViewSizeObserver : public WebContentsObserver {
public:
RenderViewSizeObserver(Shell* shell, const gfx::Size& wcv_new_size)
: WebContentsObserver(shell->web_contents()),
shell_(shell),
wcv_new_size_(wcv_new_size) {}
// WebContentsObserver:
void RenderFrameCreated(RenderFrameHost* rfh) override {
if (!rfh->GetParent())
rwhv_create_size_ = rfh->GetView()->GetViewBounds().size();
}
void DidStartNavigation(NavigationHandle* navigation_handle) override {
ResizeWebContentsView(shell_, wcv_new_size_, false);
}
gfx::Size rwhv_create_size() const { return rwhv_create_size_; }
private:
raw_ptr<Shell> shell_; // Weak ptr.
gfx::Size wcv_new_size_;
gfx::Size rwhv_create_size_;
};
class LoadingStateChangedDelegate : public WebContentsDelegate {
public:
LoadingStateChangedDelegate() = default;
// WebContentsDelegate:
void LoadingStateChanged(WebContents* contents,
bool should_show_loading_ui) override {
loadingStateChangedCount_++;
if (should_show_loading_ui)
loadingStateShowLoadingUICount_++;
}
int loadingStateChangedCount() const { return loadingStateChangedCount_; }
int loadingStateShowLoadingUICount() const {
return loadingStateShowLoadingUICount_;
}
private:
int loadingStateChangedCount_ = 0;
int loadingStateShowLoadingUICount_ = 0;
};
// Regression test for https://crbug.com/1405036
// Dumping the accessibility tree should not crash, even if it has not received
// an ID through a renderer tree yet.
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
DumpAccessibilityTreeWithoutTreeID) {
ASSERT_TRUE(embedded_test_server()->Start());
TestNavigationObserver load_observer(shell()->web_contents());
EXPECT_TRUE(
NavigateToURL(shell(), embedded_test_server()->GetURL("/title1.html")));
load_observer.Wait();
std::string expected = "-";
std::vector<ui::AXPropertyFilter> property_filters;
EXPECT_EQ(
shell()->web_contents()->DumpAccessibilityTree(false, property_filters),
expected);
}
namespace {
const char kFrameCountUMA[] = "Navigation.MainFrame.FrameCount";
const char kMaxFrameCountUMA[] = "Navigation.MainFrame.MaxFrameCount";
// Class that waits for a particular load to finish in any frame. This happens
// after the commit event.
class LoadFinishedWaiter : public WebContentsObserver {
public:
LoadFinishedWaiter(WebContents* web_contents, const GURL& expected_url)
: WebContentsObserver(web_contents),
expected_url_(expected_url),
run_loop_(new base::RunLoop()) {
EXPECT_TRUE(web_contents != nullptr);
}
void Wait() { run_loop_->Run(); }
private:
void DidFinishLoad(RenderFrameHost* render_frame_host,
const GURL& url) override {
if (url == expected_url_)
run_loop_->Quit();
}
GURL expected_url_;
std::unique_ptr<base::RunLoop> run_loop_;
};
} // namespace
// Ensure that cross-site subframes always notify their parents when they finish
// loading, so that the page eventually reaches DidStopLoading. There was a bug
// where an OOPIF would not notify its parent if (1) it finished loading, but
// (2) later added a subframe that kept the main frame in the loading state, and
// (3) all subframes then finished loading.
// Note that this test makes sense to run with and without OOPIFs.
// See https://crbug.com/822013#c12.
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
DidStopLoadingWithNestedFrames) {
ASSERT_TRUE(embedded_test_server()->Start());
WebContentsImpl* web_contents =
static_cast<WebContentsImpl*>(shell()->web_contents());
// Navigate to an A(B, C) page where B is slow to load. Wait for C to reach
// load stop. A will still be loading due to B.
GURL url_a = embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(b,c)");
GURL url_b = embedded_test_server()->GetURL(
"b.com", "/cross_site_iframe_factory.html?b()");
GURL url_c = embedded_test_server()->GetURL(
"c.com", "/cross_site_iframe_factory.html?c()");
TestNavigationManager delayer_b(web_contents, url_b);
LoadFinishedWaiter load_waiter_c(web_contents, url_c);
shell()->LoadURL(url_a);
EXPECT_TRUE(delayer_b.WaitForRequestStart());
load_waiter_c.Wait();
EXPECT_TRUE(web_contents->IsLoading());
// At this point, C has finished loading and B is stalled. Add a slow D frame
// within C.
GURL url_d = embedded_test_server()->GetURL("d.com", "/title1.html");
FrameTreeNode* subframe_c =
web_contents->GetPrimaryFrameTree().root()->child_at(1);
EXPECT_EQ(url_c, subframe_c->current_url());
TestNavigationManager delayer_d(web_contents, url_d);
const std::string add_d_script = base::StringPrintf(
"var f = document.createElement('iframe');"
"f.src='%s';"
"document.body.appendChild(f);",
url_d.spec().c_str());
EXPECT_TRUE(ExecJs(subframe_c, add_d_script));
EXPECT_TRUE(delayer_d.WaitForRequestStart());
EXPECT_TRUE(web_contents->IsLoading());
// Let B finish and wait for another load stop. A will still be loading due
// to D.
LoadFinishedWaiter load_waiter_b(web_contents, url_b);
ASSERT_TRUE(delayer_b.WaitForNavigationFinished());
load_waiter_b.Wait();
EXPECT_TRUE(web_contents->IsLoading());
// Let D finish. We should get a load stop in the main frame.
LoadFinishedWaiter load_waiter_d(web_contents, url_d);
ASSERT_TRUE(delayer_d.WaitForNavigationFinished());
load_waiter_d.Wait();
EXPECT_TRUE(WaitForLoadStop(web_contents));
EXPECT_FALSE(web_contents->IsLoading());
}
// Test that a renderer-initiated navigation to an invalid URL does not leave
// around a pending entry that could be used in a URL spoof. We test this in
// a browser test because our unit test framework incorrectly calls
// DidStartProvisionalLoadForFrame for in-page navigations.
// See http://crbug.com/280512.
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
ClearNonVisiblePendingOnFail) {
ASSERT_TRUE(embedded_test_server()->Start());
EXPECT_TRUE(
NavigateToURL(shell(), embedded_test_server()->GetURL("/title1.html")));
// Navigate to an invalid URL and make sure it doesn't leave a pending entry.
LoadStopObserver load_observer1(shell()->web_contents());
ASSERT_TRUE(ExecJs(shell(), "window.location.href=\"nonexistent:12121\";"));
load_observer1.Wait();
EXPECT_FALSE(shell()->web_contents()->GetController().GetPendingEntry());
LoadStopObserver load_observer2(shell()->web_contents());
ASSERT_TRUE(ExecJs(shell(), "window.location.href=\"#foo\";"));
load_observer2.Wait();
EXPECT_EQ(embedded_test_server()->GetURL("/title1.html#foo"),
shell()->web_contents()->GetVisibleURL());
}
// Crashes under ThreadSanitizer, http://crbug.com/356758.
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_ANDROID) || defined(THREAD_SANITIZER)
#define MAYBE_GetSizeForNewRenderView DISABLED_GetSizeForNewRenderView
#else
#define MAYBE_GetSizeForNewRenderView DISABLED_GetSizeForNewRenderView
#endif
// Test that RenderViewHost is created and updated at the size specified by
// WebContentsDelegate::GetSizeForNewRenderView().
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
MAYBE_GetSizeForNewRenderView) {
ASSERT_TRUE(embedded_test_server()->Start());
// Create a new server with a different site.
net::EmbeddedTestServer https_server(net::EmbeddedTestServer::TYPE_HTTPS);
https_server.ServeFilesFromSourceDirectory(GetTestDataFilePath());
ASSERT_TRUE(https_server.Start());
std::unique_ptr<RenderViewSizeDelegate> delegate(
new RenderViewSizeDelegate());
shell()->web_contents()->SetDelegate(delegate.get());
ASSERT_TRUE(shell()->web_contents()->GetDelegate() == delegate.get());
// When no size is set, RenderWidgetHostView adopts the size of
// WebContentsView.
EXPECT_TRUE(
NavigateToURL(shell(), embedded_test_server()->GetURL("/title2.html")));
EXPECT_EQ(shell()->web_contents()->GetContainerBounds().size(),
shell()
->web_contents()
->GetRenderWidgetHostView()
->GetViewBounds()
.size());
// When a size is set, RenderWidgetHostView and WebContentsView honor this
// size.
gfx::Size size(300, 300);
gfx::Size size_insets(10, 15);
ResizeWebContentsView(shell(), size, true);
delegate->set_size_insets(size_insets);
EXPECT_TRUE(NavigateToURL(shell(), https_server.GetURL("/")));
size.Enlarge(size_insets.width(), size_insets.height());
EXPECT_EQ(size, shell()
->web_contents()
->GetRenderWidgetHostView()
->GetViewBounds()
.size());
// The web_contents size is set by the embedder, and should not depend on the
// rwhv size. The behavior is correct on OSX, but incorrect on other
// platforms.
gfx::Size exp_wcv_size(300, 300);
#if !BUILDFLAG(IS_MAC)
exp_wcv_size.Enlarge(size_insets.width(), size_insets.height());
#endif
EXPECT_EQ(exp_wcv_size, shell()->web_contents()->GetContainerBounds().size());
// If WebContentsView is resized after RenderWidgetHostView is created but
// before pending navigation entry is committed, both RenderWidgetHostView and
// WebContentsView use the new size of WebContentsView.
gfx::Size init_size(200, 200);
gfx::Size new_size(100, 100);
size_insets = gfx::Size(20, 30);
ResizeWebContentsView(shell(), init_size, true);
delegate->set_size_insets(size_insets);
RenderViewSizeObserver observer(shell(), new_size);
EXPECT_TRUE(
NavigateToURL(shell(), embedded_test_server()->GetURL("/title1.html")));
// RenderWidgetHostView is created at specified size.
init_size.Enlarge(size_insets.width(), size_insets.height());
EXPECT_EQ(init_size, observer.rwhv_create_size());
// Once again, the behavior is correct on OSX. The embedder explicitly sets
// the size to (100,100) during navigation. Both the wcv and the rwhv should
// take on that size.
#if !BUILDFLAG(IS_MAC)
new_size.Enlarge(size_insets.width(), size_insets.height());
#endif
gfx::Size actual_size = shell()
->web_contents()
->GetRenderWidgetHostView()
->GetViewBounds()
.size();
EXPECT_EQ(new_size, actual_size);
EXPECT_EQ(new_size, shell()->web_contents()->GetContainerBounds().size());
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest, SetTitleOnPagehide) {
DisableBackForwardCacheForTesting(shell()->web_contents(),
BackForwardCache::TEST_REQUIRES_NO_CACHING);
GURL url(
"data:text/html,"
"<title>A</title>"
"<body onpagehide=\"document.title = 'B'\"></body>");
ASSERT_TRUE(NavigateToURL(shell(), url));
ASSERT_EQ(1, shell()->web_contents()->GetController().GetEntryCount());
NavigationEntryImpl* entry1 = NavigationEntryImpl::FromNavigationEntry(
shell()->web_contents()->GetController().GetLastCommittedEntry());
SiteInstance* site_instance1 = entry1->site_instance();
EXPECT_EQ(u"A", entry1->GetTitle());
// Force a process switch by going to a privileged page.
GURL web_ui_page(std::string(kChromeUIScheme) + "://" +
std::string(kChromeUIGpuHost));
RenderFrameHostImplWrapper rfh(
shell()->web_contents()->GetPrimaryMainFrame());
rfh->DisableUnloadTimerForTesting();
ASSERT_TRUE(NavigateToURL(shell(), web_ui_page));
// Wait for the page with unload to be deleted.
ASSERT_TRUE(rfh.WaitUntilRenderFrameDeleted());
// Verify that the site instance changed.
NavigationEntryImpl* entry2 = NavigationEntryImpl::FromNavigationEntry(
shell()->web_contents()->GetController().GetLastCommittedEntry());
SiteInstance* site_instance2 = entry2->site_instance();
EXPECT_NE(site_instance1, site_instance2);
// Verify that the title changed.
EXPECT_EQ(2, shell()->web_contents()->GetController().GetEntryCount());
EXPECT_EQ(u"B", entry1->GetTitle());
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest, OpenURLSubframe) {
// Navigate to a page with frames and grab a subframe's FrameTreeNode ID.
ASSERT_TRUE(embedded_test_server()->Start());
EXPECT_TRUE(NavigateToURL(
shell(), embedded_test_server()->GetURL("/frame_tree/top.html")));
WebContentsImpl* wc = static_cast<WebContentsImpl*>(shell()->web_contents());
FrameTreeNode* root = wc->GetPrimaryFrameTree().root();
ASSERT_EQ(3UL, root->child_count());
FrameTreeNodeId frame_tree_node_id = root->child_at(0)->frame_tree_node_id();
EXPECT_TRUE(frame_tree_node_id);
// Navigate with the subframe's FrameTreeNode ID.
const GURL url(embedded_test_server()->GetURL("/title1.html"));
OpenURLParams params(url, Referrer(), frame_tree_node_id,
WindowOpenDisposition::CURRENT_TAB,
ui::PAGE_TRANSITION_LINK, true);
params.initiator_origin = wc->GetPrimaryMainFrame()->GetLastCommittedOrigin();
shell()->web_contents()->OpenURL(params, /*navigation_handle_callback=*/{});
// Make sure the NavigationEntry ends up with the FrameTreeNode ID.
NavigationController* controller = &shell()->web_contents()->GetController();
EXPECT_TRUE(controller->GetPendingEntry());
EXPECT_EQ(frame_tree_node_id, NavigationEntryImpl::FromNavigationEntry(
controller->GetPendingEntry())
->frame_tree_node_id());
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest, OpenURLNonExistentSubframe) {
// Navigate to a page with frames and grab a subframe's FrameTreeNode ID.
ASSERT_TRUE(embedded_test_server()->Start());
EXPECT_TRUE(
NavigateToURL(shell(), embedded_test_server()->GetURL("/title1.html")));
WebContentsImpl* wc = static_cast<WebContentsImpl*>(shell()->web_contents());
// Take a FrameTreeNodeID that doesn't represent any frames.
FrameTreeNodeId frame_tree_node_id = FrameTreeNodeId(100);
ASSERT_FALSE(FrameTreeNode::GloballyFindByID(frame_tree_node_id));
// Navigate with the invalid FrameTreeNode ID.
const GURL url(embedded_test_server()->GetURL("/title2.html"));
OpenURLParams params(url, Referrer(), frame_tree_node_id,
WindowOpenDisposition::CURRENT_TAB,
ui::PAGE_TRANSITION_LINK, true);
params.initiator_origin = wc->GetPrimaryMainFrame()->GetLastCommittedOrigin();
WebContents* new_web_contents = shell()->web_contents()->OpenURL(
params, /*navigation_handle_callback=*/{});
// The navigation should have been ignored.
EXPECT_EQ(new_web_contents, nullptr);
NavigationController* controller = &shell()->web_contents()->GetController();
EXPECT_EQ(controller->GetPendingEntry(), nullptr);
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
AppendingFrameInWebUIDoesNotCrash) {
const GURL kWebUIUrl(GetWebUIURL("gpu"));
const char kJSCodeForAppendingFrame[] =
"document.body.appendChild(document.createElement('iframe'));";
EXPECT_TRUE(NavigateToURL(shell(), kWebUIUrl));
EXPECT_TRUE(content::ExecJs(shell(), kJSCodeForAppendingFrame));
}
// Test that creation of new RenderFrameHost objects sends the correct object
// to the WebContentObservers. See http://crbug.com/347339.
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
RenderFrameCreatedCorrectProcessForObservers) {
static const char kFooCom[] = "foo.com";
GURL::Replacements replace_host;
net::HostPortPair foo_host_port;
GURL cross_site_url;
ASSERT_TRUE(embedded_test_server()->Start());
foo_host_port = embedded_test_server()->host_port_pair();
foo_host_port.set_host(kFooCom);
GURL initial_url(embedded_test_server()->GetURL("/title1.html"));
cross_site_url = embedded_test_server()->GetURL("/title2.html");
replace_host.SetHostStr(kFooCom);
cross_site_url = cross_site_url.ReplaceComponents(replace_host);
// Navigate to the initial URL and capture the RenderFrameHost for later
// comparison.
EXPECT_TRUE(NavigateToURL(shell(), initial_url));
RenderFrameHost* orig_rfh = shell()->web_contents()->GetPrimaryMainFrame();
// Install the observer and navigate cross-site.
RenderFrameHostCreatedObserver observer(shell()->web_contents());
EXPECT_TRUE(NavigateToURL(shell(), cross_site_url));
// The observer should've seen a RenderFrameCreated call for the new frame
// and not the old one.
EXPECT_NE(observer.last_rfh(), orig_rfh);
EXPECT_EQ(observer.last_rfh(),
shell()->web_contents()->GetPrimaryMainFrame());
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
LoadingStateChangedForSameDocumentNavigation) {
ASSERT_TRUE(embedded_test_server()->Start());
std::unique_ptr<LoadingStateChangedDelegate> delegate(
new LoadingStateChangedDelegate());
shell()->web_contents()->SetDelegate(delegate.get());
LoadStopObserver load_observer(shell()->web_contents());
TitleWatcher title_watcher(shell()->web_contents(), u"pushState");
EXPECT_TRUE(NavigateToURL(
shell(), embedded_test_server()->GetURL("/push_state.html")));
load_observer.Wait();
std::u16string title = title_watcher.WaitAndGetTitle();
ASSERT_EQ(title, u"pushState");
// LoadingStateChanged should be called 4 times: start and stop for the
// initial load of push_state.html, and start and stop for
// the "navigation" triggered by history.pushState(). However, the start
// notification for the history.pushState() navigation should set
// should_show_loading_ui to false, as should all stop notifications.
EXPECT_EQ("pushState", shell()->web_contents()->GetLastCommittedURL().ref());
EXPECT_EQ(4, delegate->loadingStateChangedCount());
EXPECT_EQ(1, delegate->loadingStateShowLoadingUICount());
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest, ResourceLoadComplete) {
ResourceLoadObserver observer(shell());
ASSERT_TRUE(embedded_test_server()->Start());
// Load a page with an image and an image.
GURL page_url(embedded_test_server()->GetURL("/page_with_iframe.html"));
base::TimeTicks before = base::TimeTicks::Now();
EXPECT_TRUE(NavigateToURL(shell(), page_url));
base::TimeTicks after = base::TimeTicks::Now();
ASSERT_EQ(3U, observer.resource_load_entries().size());
SCOPE_TRACED(observer.CheckResourceLoaded(
page_url, /*referrer=*/GURL(), "GET",
network::mojom::RequestDestination::kDocument,
FILE_PATH_LITERAL("page_with_iframe.html"), "text/html", "127.0.0.1",
/*was_cached=*/false, /*first_network_request=*/true, before, after));
SCOPE_TRACED(observer.CheckResourceLoaded(
embedded_test_server()->GetURL("/image.jpg"),
/*referrer=*/page_url, "GET", network::mojom::RequestDestination::kImage,
FILE_PATH_LITERAL("image.jpg"), "image/jpeg", "127.0.0.1",
/*was_cached=*/false, /*first_network_request=*/false, before, after));
SCOPE_TRACED(observer.CheckResourceLoaded(
embedded_test_server()->GetURL("/title1.html"),
/*referrer=*/page_url, "GET", network::mojom::RequestDestination::kIframe,
FILE_PATH_LITERAL("title1.html"), "text/html", "127.0.0.1",
/*was_cached=*/false, /*first_network_request=*/false, before, after));
}
// Same as WebContentsImplBrowserTest.ResourceLoadComplete but with resources
// retrieved from the network cache.
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
ResourceLoadCompleteFromNetworkCache) {
ResourceLoadObserver observer(shell());
ASSERT_TRUE(embedded_test_server()->Start());
GURL page_url(
embedded_test_server()->GetURL("/page_with_cached_subresource.html"));
base::TimeTicks before = base::TimeTicks::Now();
EXPECT_TRUE(NavigateToURL(shell(), page_url));
base::TimeTicks after = base::TimeTicks::Now();
GURL resource_url = embedded_test_server()->GetURL("/cachetime");
ASSERT_EQ(2U, observer.resource_load_entries().size());
SCOPE_TRACED(observer.CheckResourceLoaded(
page_url, /*referrer=*/GURL(), "GET",
network::mojom::RequestDestination::kDocument,
/*served_file_name=*/FILE_PATH_LITERAL(""), "text/html", "127.0.0.1",
/*was_cached=*/false,
/*first_network_request=*/true, before, after));
SCOPE_TRACED(observer.CheckResourceLoaded(
resource_url, /*referrer=*/page_url, "GET",
network::mojom::RequestDestination::kScript,
/*served_file_name=*/FILE_PATH_LITERAL(""), "text/html", "127.0.0.1",
/*was_cached=*/false, /*first_network_request=*/false, before, after));
EXPECT_TRUE(observer.resource_load_entries()[1]
.resource_load_info->network_info->network_accessed);
EXPECT_TRUE(observer.memory_cached_loaded_urls().empty());
observer.Reset();
// Loading again should serve the request out of the in-memory cache.
before = base::TimeTicks::Now();
EXPECT_TRUE(NavigateToURL(shell(), page_url));
after = base::TimeTicks::Now();
ASSERT_EQ(1U, observer.resource_load_entries().size());
SCOPE_TRACED(observer.CheckResourceLoaded(
page_url, /*referrer=*/GURL(), "GET",
network::mojom::RequestDestination::kDocument,
/*served_file_name=*/FILE_PATH_LITERAL(""), "text/html", "127.0.0.1",
/*was_cached=*/true, /*first_network_request=*/false, before, after));
ASSERT_EQ(1U, observer.memory_cached_loaded_urls().size());
EXPECT_EQ(resource_url, observer.memory_cached_loaded_urls()[0]);
observer.Reset();
// Kill the renderer process so when the navigate again, it will be a fresh
// renderer with an empty in-memory cache.
ScopedAllowRendererCrashes scoped_allow_renderer_crashes(shell());
EXPECT_FALSE(NavigateToURL(shell(), GetWebUIURL("crash")));
// Reload that URL, the subresource should be served from the network cache.
before = base::TimeTicks::Now();
EXPECT_TRUE(NavigateToURL(shell(), page_url));
after = base::TimeTicks::Now();
ASSERT_EQ(2U, observer.resource_load_entries().size());
SCOPE_TRACED(observer.CheckResourceLoaded(
page_url, /*referrer=*/GURL(), "GET",
network::mojom::RequestDestination::kDocument,
/*served_file_name=*/FILE_PATH_LITERAL(""), "text/html", "127.0.0.1",
/*was_cached=*/true, /*first_network_request=*/true, before, after));
SCOPE_TRACED(observer.CheckResourceLoaded(
resource_url, /*referrer=*/page_url, "GET",
network::mojom::RequestDestination::kScript,
/*served_file_name=*/FILE_PATH_LITERAL(""), "text/html", "127.0.0.1",
/*was_cached=*/true, /*first_network_request=*/false, before, after));
EXPECT_TRUE(observer.memory_cached_loaded_urls().empty());
EXPECT_FALSE(observer.resource_load_entries()[1]
.resource_load_info->network_info->network_accessed);
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
ResourceLoadCompleteFromLocalResource) {
ResourceLoadObserver observer(shell());
ASSERT_TRUE(embedded_test_server()->Start());
EXPECT_TRUE(NavigateToURL(
shell(), GURL(embedded_test_server()->GetURL("/page_with_image.html"))));
ASSERT_EQ(2U, observer.resource_load_entries().size());
EXPECT_TRUE(observer.resource_load_entries()[0]
.resource_load_info->network_info->network_accessed);
EXPECT_TRUE(observer.resource_load_entries()[1]
.resource_load_info->network_info->network_accessed);
observer.Reset();
EXPECT_TRUE(NavigateToURL(shell(), GetWebUIURL("gpu")));
ASSERT_LE(1U, observer.resource_load_entries().size());
for (auto& resource_load_entry : observer.resource_load_entries()) {
EXPECT_FALSE(
resource_load_entry.resource_load_info->network_info->network_accessed);
}
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
ResourceLoadCompleteWithRedirect) {
ResourceLoadObserver observer(shell());
ASSERT_TRUE(embedded_test_server()->Start());
GURL page_destination_url(
embedded_test_server()->GetURL("/page_with_image_redirect.html"));
GURL page_original_url(embedded_test_server()->GetURL(
"/server-redirect?" + page_destination_url.spec()));
EXPECT_TRUE(NavigateToURL(shell(), page_original_url,
page_destination_url /* expected_commit_url */));
ASSERT_EQ(2U, observer.resource_load_entries().size());
const blink::mojom::ResourceLoadInfoPtr& page_load_info =
observer.resource_load_entries()[0].resource_load_info;
EXPECT_EQ(page_destination_url, page_load_info->final_url);
EXPECT_EQ(page_original_url, page_load_info->original_url);
GURL image_destination_url(embedded_test_server()->GetURL("/blank.jpg"));
GURL image_original_url(
embedded_test_server()->GetURL("/server-redirect?blank.jpg"));
const blink::mojom::ResourceLoadInfoPtr& image_load_info =
observer.resource_load_entries()[1].resource_load_info;
EXPECT_EQ(image_destination_url, image_load_info->final_url);
EXPECT_EQ(image_original_url, image_load_info->original_url);
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
ResourceLoadCompleteNetError) {
ResourceLoadObserver observer(shell());
ASSERT_TRUE(embedded_test_server()->Start());
GURL page_url(embedded_test_server()->GetURL("/page_with_image.html"));
GURL image_url(embedded_test_server()->GetURL("/blank.jpg"));
// Load the page without errors.
EXPECT_TRUE(NavigateToURL(shell(), page_url));
const std::vector<ResourceLoadObserver::ResourceLoadEntry>& entries =
observer.resource_load_entries();
ASSERT_EQ(2U, entries.size());
EXPECT_EQ(net::OK, entries[0].resource_load_info->net_error);
EXPECT_EQ(net::OK, entries[1].resource_load_info->net_error);
observer.Reset();
// Load the page and simulate a network error.
content::URLLoaderInterceptor url_interceptor(base::BindLambdaForTesting(
[image_url](content::URLLoaderInterceptor::RequestParams* params) {
if (params->url_request.url != image_url)
return false;
network::URLLoaderCompletionStatus status;
status.error_code = net::ERR_ADDRESS_UNREACHABLE;
params->client->OnComplete(status);
return true;
}));
EXPECT_TRUE(NavigateToURL(shell(), page_url));
ASSERT_EQ(2U, entries.size());
// A ResourceLoadInfo is added when the load for the resource is complete,
// and hence the order is undeterministic.
if (entries[0].resource_load_info->final_url == page_url) {
EXPECT_EQ(net::OK, entries[0].resource_load_info->net_error);
EXPECT_EQ(image_url, entries[1].resource_load_info->final_url);
EXPECT_EQ(net::ERR_ADDRESS_UNREACHABLE,
entries[1].resource_load_info->net_error);
} else {
EXPECT_EQ(image_url, entries[0].resource_load_info->final_url);
EXPECT_EQ(net::ERR_ADDRESS_UNREACHABLE,
entries[0].resource_load_info->net_error);
EXPECT_EQ(page_url, entries[1].resource_load_info->final_url);
EXPECT_EQ(net::OK, entries[1].resource_load_info->net_error);
}
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
ResourceLoadCompleteAlwaysAccessNetwork) {
ResourceLoadObserver observer(shell());
ASSERT_TRUE(embedded_test_server()->Start());
GURL cacheable_url(embedded_test_server()->GetURL("/set-header"));
EXPECT_TRUE(NavigateToURL(shell(), cacheable_url));
ASSERT_EQ(1U, observer.resource_load_entries().size());
EXPECT_FALSE(observer.resource_load_entries()[0]
.resource_load_info->network_info->always_access_network);
observer.Reset();
std::array<std::string, 3> headers = {
"cache-control: no-cache", "cache-control: no-store", "pragma: no-cache"};
for (const std::string& header : headers) {
GURL no_cache_url(embedded_test_server()->GetURL("/set-header?" + header));
EXPECT_TRUE(NavigateToURL(shell(), no_cache_url));
ASSERT_EQ(1U, observer.resource_load_entries().size());
EXPECT_TRUE(observer.resource_load_entries()[0]
.resource_load_info->network_info->always_access_network);
observer.Reset();
}
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
ResourceLoadCompleteWithRedirects) {
ResourceLoadObserver observer(shell());
ASSERT_TRUE(embedded_test_server()->Start());
GURL target_url(embedded_test_server()->GetURL("/title1.html"));
GURL intermediate_url(
embedded_test_server()->GetURL("/server-redirect?" + target_url.spec()));
GURL start_url(embedded_test_server()->GetURL("/server-redirect?" +
intermediate_url.spec()));
EXPECT_TRUE(
NavigateToURL(shell(), start_url, target_url /* expected_commit_url */));
ASSERT_EQ(1U, observer.resource_load_entries().size());
EXPECT_EQ(target_url,
observer.resource_load_entries()[0].resource_load_info->final_url);
ASSERT_EQ(2U, observer.resource_load_entries()[0]
.resource_load_info->redirect_info_chain.size());
EXPECT_EQ(url::Origin::Create(intermediate_url),
observer.resource_load_entries()[0]
.resource_load_info->redirect_info_chain[0]
->origin_of_new_url);
EXPECT_TRUE(observer.resource_load_entries()[0]
.resource_load_info->redirect_info_chain[0]
->network_info->network_accessed);
EXPECT_FALSE(observer.resource_load_entries()[0]
.resource_load_info->redirect_info_chain[0]
->network_info->always_access_network);
EXPECT_EQ(url::Origin::Create(target_url),
observer.resource_load_entries()[0]
.resource_load_info->redirect_info_chain[1]
->origin_of_new_url);
EXPECT_TRUE(observer.resource_load_entries()[0]
.resource_load_info->redirect_info_chain[1]
->network_info->network_accessed);
EXPECT_FALSE(observer.resource_load_entries()[0]
.resource_load_info->redirect_info_chain[1]
->network_info->always_access_network);
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
ResourceLoadCompleteIsMainFrame) {
ResourceLoadObserver observer(shell());
ASSERT_TRUE(embedded_test_server()->Start());
GURL url(embedded_test_server()->GetURL("/page_with_image.html"));
EXPECT_TRUE(NavigateToURL(shell(), url));
const std::vector<ResourceLoadObserver::ResourceLoadEntry>& entries =
observer.resource_load_entries();
ASSERT_EQ(2U, entries.size());
EXPECT_EQ(url, entries[0].resource_load_info->original_url);
EXPECT_EQ(url, entries[0].resource_load_info->final_url);
EXPECT_TRUE(entries[0].resource_is_associated_with_main_frame);
EXPECT_TRUE(entries[1].resource_is_associated_with_main_frame);
observer.Reset();
// Load that same page inside an iframe.
GURL data_url("data:text/html,<iframe src='" + url.spec() + "'></iframe>");
EXPECT_TRUE(NavigateToURL(shell(), data_url));
ASSERT_EQ(3U, entries.size());
EXPECT_EQ(data_url, entries[0].resource_load_info->original_url);
EXPECT_EQ(data_url, entries[0].resource_load_info->final_url);
EXPECT_EQ(url, entries[1].resource_load_info->original_url);
EXPECT_EQ(url, entries[1].resource_load_info->final_url);
EXPECT_TRUE(entries[0].resource_is_associated_with_main_frame);
EXPECT_FALSE(entries[1].resource_is_associated_with_main_frame);
EXPECT_FALSE(entries[2].resource_is_associated_with_main_frame);
}
struct LoadProgressObserver : public WebContentsObserver {
explicit LoadProgressObserver(Shell* shell)
: WebContentsObserver(shell->web_contents()),
did_start_loading(false),
did_stop_loading(false) {}
// WebContentsObserver:
void DidStartLoading() override {
EXPECT_FALSE(did_start_loading);
EXPECT_EQ(0U, progresses.size());
EXPECT_FALSE(did_stop_loading);
did_start_loading = true;
}
void DidStopLoading() override {
EXPECT_TRUE(did_start_loading);
EXPECT_GE(progresses.size(), 1U);
EXPECT_FALSE(did_stop_loading);
did_stop_loading = true;
}
void LoadProgressChanged(double progress) override {
EXPECT_TRUE(did_start_loading);
EXPECT_FALSE(did_stop_loading);
progresses.push_back(progress);
}
bool did_start_loading;
std::vector<double> progresses;
bool did_stop_loading;
};
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest, LoadProgress) {
ASSERT_TRUE(embedded_test_server()->Start());
auto delegate = std::make_unique<LoadProgressObserver>(shell());
EXPECT_TRUE(
NavigateToURL(shell(), embedded_test_server()->GetURL("/title1.html")));
const std::vector<double>& progresses = delegate->progresses;
// All updates should be in order ...
if (std::ranges::adjacent_find(progresses, std::greater<>()) !=
progresses.end()) {
ADD_FAILURE() << "Progress values should be in order: "
<< ::testing::PrintToString(progresses);
}
// ... and the last one should be 1.0, meaning complete.
ASSERT_GE(progresses.size(), 1U)
<< "There should be at least one progress update";
EXPECT_EQ(1.0, *progresses.rbegin());
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest, LoadProgressWithFrames) {
ASSERT_TRUE(embedded_test_server()->Start());
auto delegate = std::make_unique<LoadProgressObserver>(shell());
EXPECT_TRUE(NavigateToURL(
shell(), embedded_test_server()->GetURL("/frame_tree/top.html")));
const std::vector<double>& progresses = delegate->progresses;
// All updates should be in order ...
if (std::ranges::adjacent_find(progresses, std::greater<>()) !=
progresses.end()) {
ADD_FAILURE() << "Progress values should be in order: "
<< ::testing::PrintToString(progresses);
}
// ... and the last one should be 1.0, meaning complete.
ASSERT_GE(progresses.size(), 1U)
<< "There should be at least one progress update";
EXPECT_EQ(1.0, *progresses.rbegin());
}
// Ensure that a new navigation that interrupts a pending one will still fire
// a DidStopLoading. See http://crbug.com/429399.
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
LoadProgressAfterInterruptedNav) {
ASSERT_TRUE(embedded_test_server()->Start());
// Start at a real page.
EXPECT_TRUE(
NavigateToURL(shell(), embedded_test_server()->GetURL("/title1.html")));
// Simulate a navigation that has not completed.
const GURL kURL2 = embedded_test_server()->GetURL("/title2.html");
TestNavigationManager navigation(shell()->web_contents(), kURL2);
auto delegate = std::make_unique<LoadProgressObserver>(shell());
shell()->LoadURL(kURL2);
EXPECT_TRUE(navigation.WaitForResponse());
EXPECT_TRUE(delegate->did_start_loading);
EXPECT_FALSE(delegate->did_stop_loading);
// Also simulate a DidChangeLoadProgress, but not a DidStopLoading.
RenderFrameHostImpl* main_frame = static_cast<RenderFrameHostImpl*>(
shell()->web_contents()->GetPrimaryMainFrame());
main_frame->DidChangeLoadProgress(1.0);
EXPECT_TRUE(delegate->did_start_loading);
EXPECT_FALSE(delegate->did_stop_loading);
// Now interrupt with a new cross-process navigation.
TestNavigationObserver tab_observer(shell()->web_contents(), 1);
GURL url(embedded_test_server()->GetURL("foo.com", "/title2.html"));
shell()->LoadURL(url);
tab_observer.Wait();
EXPECT_EQ(url, shell()->web_contents()->GetLastCommittedURL());
// We should have gotten to DidStopLoading.
EXPECT_TRUE(delegate->did_stop_loading);
}
struct FirstVisuallyNonEmptyPaintObserver : public WebContentsObserver {
explicit FirstVisuallyNonEmptyPaintObserver(Shell* shell)
: WebContentsObserver(shell->web_contents()),
did_fist_visually_non_empty_paint_(false) {}
void DidFirstVisuallyNonEmptyPaint() override {
did_fist_visually_non_empty_paint_ = true;
std::move(on_did_first_visually_non_empty_paint_).Run();
}
void WaitForDidFirstVisuallyNonEmptyPaint() {
if (did_fist_visually_non_empty_paint_)
return;
base::RunLoop run_loop;
on_did_first_visually_non_empty_paint_ = run_loop.QuitClosure();
run_loop.Run();
}
base::OnceClosure on_did_first_visually_non_empty_paint_;
bool did_fist_visually_non_empty_paint_;
};
// See: http://crbug.com/395664
#if BUILDFLAG(IS_ANDROID)
#define MAYBE_FirstVisuallyNonEmptyPaint DISABLED_FirstVisuallyNonEmptyPaint
#else
// http://crbug.com/398471
#define MAYBE_FirstVisuallyNonEmptyPaint DISABLED_FirstVisuallyNonEmptyPaint
#endif
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
MAYBE_FirstVisuallyNonEmptyPaint) {
ASSERT_TRUE(embedded_test_server()->Start());
std::unique_ptr<FirstVisuallyNonEmptyPaintObserver> observer(
new FirstVisuallyNonEmptyPaintObserver(shell()));
EXPECT_TRUE(
NavigateToURL(shell(), embedded_test_server()->GetURL("/title1.html")));
observer->WaitForDidFirstVisuallyNonEmptyPaint();
ASSERT_TRUE(observer->did_fist_visually_non_empty_paint_);
}
namespace {
class WebDisplayModeDelegate : public WebContentsDelegate {
public:
explicit WebDisplayModeDelegate(blink::mojom::DisplayMode mode)
: mode_(mode) {}
~WebDisplayModeDelegate() override = default;
WebDisplayModeDelegate(const WebDisplayModeDelegate&) = delete;
WebDisplayModeDelegate& operator=(const WebDisplayModeDelegate&) = delete;
blink::mojom::DisplayMode GetDisplayMode(const WebContents* source) override {
return mode_;
}
void set_mode(blink::mojom::DisplayMode mode) { mode_ = mode; }
private:
blink::mojom::DisplayMode mode_;
};
} // namespace
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest, ChangeDisplayMode) {
ASSERT_TRUE(embedded_test_server()->Start());
WebDisplayModeDelegate delegate(blink::mojom::DisplayMode::kMinimalUi);
shell()->web_contents()->SetDelegate(&delegate);
EXPECT_TRUE(NavigateToURL(shell(), GURL(url::kAboutBlankURL)));
ASSERT_TRUE(ExecJs(shell(),
"document.title = "
" window.matchMedia('(display-mode:"
" minimal-ui)').matches"));
EXPECT_EQ(u"true", shell()->web_contents()->GetTitle());
delegate.set_mode(blink::mojom::DisplayMode::kFullscreen);
// Simulate widget is entering fullscreen (changing size is enough).
shell()
->web_contents()
->GetPrimaryMainFrame()
->GetRenderViewHost()
->GetWidget()
->SynchronizeVisualProperties();
ASSERT_TRUE(ExecJs(shell(),
"document.title = "
" window.matchMedia('(display-mode:"
" fullscreen)').matches"));
EXPECT_EQ(u"true", shell()->web_contents()->GetTitle());
}
// Observer class used to verify that WebContentsObservers are notified
// when the page scale factor changes.
// See WebContentsImplBrowserTest.ChangePageScale.
class MockPageScaleObserver : public WebContentsObserver {
public:
explicit MockPageScaleObserver(Shell* shell)
: WebContentsObserver(shell->web_contents()),
got_page_scale_update_(false) {
// Once OnPageScaleFactorChanged is called, quit the run loop.
ON_CALL(*this, OnPageScaleFactorChanged(::testing::_))
.WillByDefault(::testing::InvokeWithoutArgs(
this, &MockPageScaleObserver::GotPageScaleUpdate));
}
MOCK_METHOD1(OnPageScaleFactorChanged, void(float page_scale_factor));
void WaitForPageScaleUpdate() {
if (!got_page_scale_update_) {
base::RunLoop run_loop;
on_page_scale_update_ = run_loop.QuitClosure();
run_loop.Run();
}
got_page_scale_update_ = false;
}
private:
void GotPageScaleUpdate() {
got_page_scale_update_ = true;
std::move(on_page_scale_update_).Run();
}
base::OnceClosure on_page_scale_update_;
bool got_page_scale_update_;
};
// When the page scale factor is set in the renderer it should send
// a notification to the browser so that WebContentsObservers are notified.
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest, ChangePageScale) {
ASSERT_TRUE(embedded_test_server()->Start());
EXPECT_TRUE(
NavigateToURL(shell(), embedded_test_server()->GetURL("/title1.html")));
MockPageScaleObserver observer(shell());
::testing::InSequence expect_call_sequence;
shell()->web_contents()->SetPageScale(1.5);
EXPECT_CALL(observer, OnPageScaleFactorChanged(::testing::FloatEq(1.5)));
observer.WaitForPageScaleUpdate();
if (!CanSameSiteMainFrameNavigationsChangeRenderFrameHosts()) {
// Navigate to reset the page scale factor. We'll only get the
// OnPageScaleFactorChanged if we reuse the same RenderFrameHost, which will
// not happen if ProactivelySwapBrowsingInstance or RenderDocument is
// enabled for same-site main frame navigations.
shell()->LoadURL(embedded_test_server()->GetURL("/title2.html"));
EXPECT_CALL(observer, OnPageScaleFactorChanged(::testing::_));
observer.WaitForPageScaleUpdate();
}
}
#if BUILDFLAG(IS_ANDROID)
// Test that when navigating between pages with the same non-one initial scale,
// the browser tracks the correct scale value.
// This test is only relevant for Android, since desktop would always have one
// as the initial scale.
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
SameInitialScaleAcrossNavigations) {
// Scale value comparisons don't need to be precise.
constexpr double kEpsilon = 0.01;
ASSERT_TRUE(embedded_test_server()->Start());
const GURL url(embedded_test_server()->GetURL("/title1.html"));
auto* contents = static_cast<WebContentsImpl*>(shell()->web_contents());
// Navigate to a page with a non-one initial scale, then determine what the
// renderer and browser each think the scale is.
EXPECT_TRUE(NavigateToURL(shell(), url));
double initial_renderer_scale_1 =
EvalJs(contents, "window.visualViewport.scale").ExtractDouble();
double initial_browser_scale_1 =
contents->GetPrimaryPage().GetPageScaleFactor();
// Now navigate to another page and record the scales again. Note that this
// navigation could reuse the RenderFrameHost and in that case the renderer
// will not inform the browser of the scale again. This was the case in
// https://crbug.com/1301879
const auto rfh_id_1 = contents->GetPrimaryMainFrame()->GetGlobalId();
EXPECT_TRUE(NavigateToURL(shell(), url));
const auto rfh_id_2 = contents->GetPrimaryMainFrame()->GetGlobalId();
SCOPED_TRACE(testing::Message()
<< "CanSameSiteMainFrameNavigationsChangeRenderFrameHosts = "
<< CanSameSiteMainFrameNavigationsChangeRenderFrameHosts());
SCOPED_TRACE(testing::Message()
<< "Did change RenderFrameHost? " << (rfh_id_1 != rfh_id_2));
double initial_renderer_scale_2 =
EvalJs(contents, "window.visualViewport.scale").ExtractDouble();
double initial_browser_scale_2 =
contents->GetPrimaryPage().GetPageScaleFactor();
// Ensure both pages are scaled to the same non-one value.
ASSERT_LT(initial_renderer_scale_1, 1.0 - kEpsilon);
ASSERT_NEAR(initial_renderer_scale_1, initial_renderer_scale_2, kEpsilon);
// Test that the browser and renderer agree on the scale.
EXPECT_NEAR(initial_browser_scale_1, initial_renderer_scale_1, kEpsilon);
EXPECT_NEAR(initial_browser_scale_2, initial_renderer_scale_2, kEpsilon);
}
#endif // BUILDFLAG(IS_ANDROID)
// Test that a direct navigation to a view-source URL works.
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest, ViewSourceDirectNavigation) {
ASSERT_TRUE(embedded_test_server()->Start());
const GURL kUrl(embedded_test_server()->GetURL("/simple_page.html"));
const GURL kViewSourceURL(kViewSourceScheme + std::string(":") + kUrl.spec());
EXPECT_TRUE(NavigateToURL(shell(), kViewSourceURL));
// Displayed view-source URLs don't include the scheme of the effective URL if
// the effective URL is HTTP. (e.g. view-source:example.com is displayed
// instead of view-source:http://example.com).
EXPECT_EQ(base::ASCIIToUTF16(std::string("view-source:") + kUrl.host() + ":" +
kUrl.port() + kUrl.path()),
shell()->web_contents()->GetTitle());
EXPECT_TRUE(shell()
->web_contents()
->GetController()
.GetLastCommittedEntry()
->IsViewSourceMode());
}
// Test that window.open to a view-source URL is blocked.
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
ViewSourceWindowOpen_ShouldBeBlocked) {
ASSERT_TRUE(embedded_test_server()->Start());
const GURL kUrl(embedded_test_server()->GetURL("/simple_page.html"));
const GURL kViewSourceURL(kViewSourceScheme + std::string(":") + kUrl.spec());
EXPECT_TRUE(NavigateToURL(shell(), kUrl));
WebContentsConsoleObserver console_observer(shell()->web_contents());
console_observer.SetPattern(
"Not allowed to load local resource: view-source:*");
EXPECT_TRUE(ExecJs(shell()->web_contents(),
"window.open('" + kViewSourceURL.spec() + "');"));
ASSERT_TRUE(console_observer.Wait());
// Original page shouldn't navigate away, no new tab should be opened.
EXPECT_EQ(kUrl, shell()->web_contents()->GetLastCommittedURL());
EXPECT_EQ(1u, Shell::windows().size());
}
// Test that a content initiated navigation to a view-source URL is blocked.
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
ViewSourceRedirect_ShouldBeBlocked) {
ASSERT_TRUE(embedded_test_server()->Start());
const GURL kUrl(embedded_test_server()->GetURL("/simple_page.html"));
const GURL kViewSourceURL(kViewSourceScheme + std::string(":") + kUrl.spec());
EXPECT_TRUE(NavigateToURL(shell(), kUrl));
WebContentsConsoleObserver console_observer(shell()->web_contents());
console_observer.SetPattern(
"Not allowed to load local resource: view-source:*");
EXPECT_TRUE(ExecJs(shell()->web_contents(),
"window.location = '" + kViewSourceURL.spec() + "';"));
ASSERT_TRUE(console_observer.Wait());
// Original page shouldn't navigate away.
EXPECT_EQ(kUrl, shell()->web_contents()->GetLastCommittedURL());
EXPECT_FALSE(shell()
->web_contents()
->GetController()
.GetLastCommittedEntry()
->IsViewSourceMode());
}
// Test that view source mode for a webui page can be opened.
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest, ViewSourceWebUI) {
const std::string kUrl = "view-source:" + GetWebUIURLString(kChromeUIGpuHost);
// To ensure that NavigateToURL succeeds, append a slash to the view-source:
// URL, since the slash would be appended anyway as part of the navigation.
const GURL kGURL(kUrl + "/");
EXPECT_TRUE(NavigateToURL(shell(), kGURL));
EXPECT_EQ(base::ASCIIToUTF16(kUrl), shell()->web_contents()->GetTitle());
EXPECT_TRUE(shell()
->web_contents()
->GetController()
.GetLastCommittedEntry()
->IsViewSourceMode());
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest, NewNamedWindow) {
ASSERT_TRUE(embedded_test_server()->Start());
GURL url = embedded_test_server()->GetURL("/click-noreferrer-links.html");
EXPECT_TRUE(NavigateToURL(shell(), url));
{
ShellAddedObserver new_shell_observer;
// Open a new, named window.
EXPECT_TRUE(ExecJs(shell(), "window.open('about:blank','new_window');"));
Shell* new_shell = new_shell_observer.GetShell();
EXPECT_TRUE(WaitForLoadStop(new_shell->web_contents()));
EXPECT_EQ("new_window",
static_cast<WebContentsImpl*>(new_shell->web_contents())
->GetPrimaryFrameTree()
.root()
->frame_name());
EXPECT_EQ(true, EvalJs(new_shell, "window.name == 'new_window';"));
}
{
ShellAddedObserver new_shell_observer;
// Test clicking a target=foo link.
EXPECT_EQ(true, EvalJs(shell(), "clickSameSiteTargetedLink();"));
Shell* new_shell = new_shell_observer.GetShell();
EXPECT_TRUE(WaitForLoadStop(new_shell->web_contents()));
EXPECT_EQ("foo", static_cast<WebContentsImpl*>(new_shell->web_contents())
->GetPrimaryFrameTree()
.root()
->frame_name());
}
}
// Test that HasOriginalOpener() tracks provenance through closed WebContentses.
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
HasOriginalOpenerTracksThroughClosedWebContents) {
const GURL blank_url = GURL("about:blank");
Shell* shell1 = shell();
EXPECT_TRUE(NavigateToURL(shell1, blank_url));
Shell* shell2 = OpenPopup(shell1, blank_url, "window2");
Shell* shell3 = OpenPopup(shell2, blank_url, "window3");
EXPECT_EQ(
shell2->web_contents(),
shell3->web_contents()->GetFirstWebContentsInLiveOriginalOpenerChain());
EXPECT_EQ(
shell1->web_contents(),
shell2->web_contents()->GetFirstWebContentsInLiveOriginalOpenerChain());
shell2->Close();
EXPECT_EQ(
shell1->web_contents(),
shell3->web_contents()->GetFirstWebContentsInLiveOriginalOpenerChain());
}
// Test that if a BeforeUnload dialog is destroyed due to the commit of a
// cross-site navigation, it will not reset the loading state.
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
NoResetOnBeforeUnloadCanceledOnCommit) {
ASSERT_TRUE(embedded_test_server()->Start());
const GURL kStartURL(
embedded_test_server()->GetURL("/hang_before_unload.html"));
const GURL kCrossSiteURL(
embedded_test_server()->GetURL("bar.com", "/title1.html"));
// Navigate to a first web page with a BeforeUnload event listener.
EXPECT_TRUE(NavigateToURL(shell(), kStartURL));
// Start a cross-site navigation that will not commit for the moment.
// This intentionally does not trigger a BeforeUnload dialog because the
// main frame has never had user activation.
TestNavigationManager cross_site_delayer(shell()->web_contents(),
kCrossSiteURL);
shell()->LoadURL(kCrossSiteURL);
EXPECT_TRUE(cross_site_delayer.WaitForRequestStart());
// Disable beforeunload timer to prevent flakiness.
PrepContentsForBeforeUnloadTest(shell()->web_contents());
// Click on a link in the page. This will show the BeforeUnload dialog.
// Ensure the dialog is not dismissed, which will cause it to still be
// present when the cross-site navigation later commits.
// Note: the javascript function executed will not do the link click but
// schedule it for afterwards. Since the BeforeUnload event is synchronous,
// clicking on the link right away would cause the ExecJs to never
// return.
SetShouldProceedOnBeforeUnload(shell(), false, false);
AppModalDialogWaiter dialog_waiter(shell());
EXPECT_TRUE(ExecJs(shell(), "clickLinkSoon()"));
dialog_waiter.Wait();
// Have the cross-site navigation commit. The main RenderFrameHost should
// still be loading after that.
ASSERT_TRUE(cross_site_delayer.WaitForNavigationFinished());
EXPECT_TRUE(shell()->web_contents()->IsLoading());
}
namespace {
void NavigateToDataURLAndCheckForTerminationDisabler(
Shell* shell,
const std::string& html,
bool expect_unload,
bool expect_beforeunload,
bool expect_pagehide,
bool expect_visibilitychange) {
EXPECT_TRUE(NavigateToURL(shell, GURL("data:text/html," + html)));
RenderFrameHostImpl* rfh = static_cast<RenderFrameHostImpl*>(
shell->web_contents()->GetPrimaryMainFrame());
EXPECT_EQ(expect_unload || expect_beforeunload || expect_pagehide ||
expect_visibilitychange,
shell->web_contents()->NeedToFireBeforeUnloadOrUnloadEvents());
EXPECT_EQ(expect_unload,
rfh->GetSuddenTerminationDisablerState(
blink::mojom::SuddenTerminationDisablerType::kUnloadHandler));
EXPECT_EQ(
expect_beforeunload,
rfh->GetSuddenTerminationDisablerState(
blink::mojom::SuddenTerminationDisablerType::kBeforeUnloadHandler));
EXPECT_EQ(expect_pagehide,
rfh->GetSuddenTerminationDisablerState(
blink::mojom::SuddenTerminationDisablerType::kPageHideHandler));
EXPECT_EQ(expect_visibilitychange,
rfh->GetSuddenTerminationDisablerState(
blink::mojom::SuddenTerminationDisablerType::
kVisibilityChangeHandler));
}
} // namespace
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
SuddenTerminationDisablerNone) {
const std::string NO_HANDLERS_HTML = "<html><body>foo</body></html>";
NavigateToDataURLAndCheckForTerminationDisabler(
shell(), NO_HANDLERS_HTML, false /* expect_unload */,
false /* expect_beforeunload */, false /* expect_pagehide */,
false /* expect_visibilitychange */);
}
IN_PROC_BROWSER_TEST_F(
WebContentsImplBrowserTest,
SuddenTerminationDisablerNoneProcessTerminationDisallowed) {
const std::string NO_HANDLERS_HTML = "<html><body>foo</body></html>";
// The WebContents termination disabler should be independent of the
// RenderProcessHost termination disabler, as process termination can depend
// on more than the presence of a beforeunload/unload handler.
shell()
->web_contents()
->GetPrimaryMainFrame()
->GetProcess()
->SetSuddenTerminationAllowed(false);
NavigateToDataURLAndCheckForTerminationDisabler(
shell(), NO_HANDLERS_HTML, false /* expect_unload */,
false /* expect_beforeunload */, false /* expect_pagehide */,
false /* expect_visibilitychange */);
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
SuddenTerminationDisablerOnUnload) {
const std::string UNLOAD_HTML =
"<html><body><script>window.onunload=function(e) {}</script>"
"</body></html>";
NavigateToDataURLAndCheckForTerminationDisabler(
shell(), UNLOAD_HTML, true /* expect_unload */,
false /* expect_beforeunload */, false /* expect_pagehide */,
false /* expect_visibilitychange */);
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
SuddenTerminationDisablerOnPagehide) {
const std::string PAGEHIDE_HTML =
"<html><body><script>window.onpagehide=function(e) {}</script>"
"</body></html>";
NavigateToDataURLAndCheckForTerminationDisabler(
shell(), PAGEHIDE_HTML, false /* expect_unload */,
false /* expect_beforeunload */, true /* expect_pagehide */,
false /* expect_visibilitychange */);
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
SuddenTerminationDisablerOnVisibilityChangeDocument) {
const std::string VISIBILITYCHANGE_HTML =
"<html><body><script>"
"document.addEventListener('visibilitychange', (e) => {});"
"</script></body></html>";
NavigateToDataURLAndCheckForTerminationDisabler(
shell(), VISIBILITYCHANGE_HTML, false /* expect_unload */,
false /* expect_beforeunload */, false /* expect_pagehide */,
true /* expect_visibilitychange */);
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
SuddenTerminationDisablerOnVisibilityChangeWindow) {
const std::string VISIBILITYCHANGE_HTML =
"<html><body><script>"
"window.addEventListener('visibilitychange', (e) => {});"
"</script></body></html>";
NavigateToDataURLAndCheckForTerminationDisabler(
shell(), VISIBILITYCHANGE_HTML, false /* expect_unload */,
false /* expect_beforeunload */, false /* expect_pagehide */,
true /* expect_visibilitychange */);
}
IN_PROC_BROWSER_TEST_F(
WebContentsImplBrowserTest,
SuddenTerminationDisablerOnVisibilityChangeRemoveDocumentListener) {
const std::string VISIBILITYCHANGE_HTML =
"<html><body><script>"
"function handleVisibilityChange(e) {}"
"window.addEventListener('visibilitychange', handleVisibilityChange);"
"document.addEventListener('visibilitychange', handleVisibilityChange);"
"document.removeEventListener('visibilitychange', "
"handleVisibilityChange);"
"</script></body></html>";
NavigateToDataURLAndCheckForTerminationDisabler(
shell(), VISIBILITYCHANGE_HTML, false /* expect_unload */,
false /* expect_beforeunload */, false /* expect_pagehide */,
true /* expect_visibilitychange */);
}
IN_PROC_BROWSER_TEST_F(
WebContentsImplBrowserTest,
SuddenTerminationDisablerOnVisibilityChangeRemoveWindowListener) {
const std::string VISIBILITYCHANGE_HTML =
"<html><body><script>"
"function handleVisibilityChange(e) {}"
"window.onvisibilitychange = handleVisibilityChange;"
"document.onvisibilitychange = handleVisibilityChange;"
"window.removeEventListener('visibilitychange', handleVisibilityChange);"
"</script></body></html>";
NavigateToDataURLAndCheckForTerminationDisabler(
shell(), VISIBILITYCHANGE_HTML, false /* expect_unload */,
false /* expect_beforeunload */, false /* expect_pagehide */,
true /* expect_visibilitychange */);
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
SuddenTerminationDisablerOnBeforeUnload) {
const std::string BEFORE_UNLOAD_HTML =
"<html><body><script>window.onbeforeunload=function(e) {}</script>"
"</body></html>";
NavigateToDataURLAndCheckForTerminationDisabler(
shell(), BEFORE_UNLOAD_HTML, false /* expect_unload */,
true /* expect_beforeunload */, false /* expect_pagehide */,
false /* expect_visibilitychange */);
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
SuddenTerminationDisablerAllThenNavigate) {
const std::string ALL_HANDLERS_HTML =
"<html><body><script>window.onunload=function(e) {};"
"window.onpagehide=function(e) {};"
"document.onvisibilitychange=function(e) {}; "
"window.onbeforeunload=function(e) {}</script>"
"</body></html>";
NavigateToDataURLAndCheckForTerminationDisabler(
shell(), ALL_HANDLERS_HTML, true /* expect_unload */,
true /* expect_beforeunload */, true /* expect_pagehide */,
true /* expect_visibilitychange*/);
// After navigation to empty page, the values should be reset to false.
NavigateToDataURLAndCheckForTerminationDisabler(
shell(), "", false /* expect_unload */, false /* expect_beforeunload */,
false /* expect_pagehide */, false /* expect_visibilitychange */);
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
SuddenTerminationDisablerAllThenRemove) {
const std::string ALL_HANDLERS_ADDED_THEN_REMOVED_HTML =
"<html><body><script>"
"function handleEverything(e) {}"
"window.addEventListener('unload', handleEverything);"
"window.addEventListener('beforeunload', handleEverything);"
"window.addEventListener('pagehide', handleEverything);"
"window.addEventListener('visibilitychange', handleEverything);"
"document.addEventListener('visibilitychange', handleEverything);"
"window.removeEventListener('unload', handleEverything);"
"window.removeEventListener('beforeunload', handleEverything);"
"window.removeEventListener('pagehide', handleEverything);"
"window.removeEventListener('visibilitychange', handleEverything);"
"document.removeEventListener('visibilitychange', handleEverything);"
"</script></body></html>";
// After the handlers were added, they got deleted, so we should treat them as
// non-existent in the end.
NavigateToDataURLAndCheckForTerminationDisabler(
shell(), ALL_HANDLERS_ADDED_THEN_REMOVED_HTML, false /* expect_unload */,
false /* expect_beforeunload */, false /* expect_pagehide */,
false /* expect_visibilitychange */);
}
IN_PROC_BROWSER_TEST_F(
WebContentsImplBrowserTest,
SuddenTerminationDisablerWhenTabIsHiddenOnVisibilityChange) {
auto* web_contents = static_cast<WebContentsImpl*>(shell()->web_contents());
const std::string VISIBILITYCHANGE_HTML =
"<html><body><script>document.onvisibilitychange=function(e) {}</script>"
"</body></html>";
NavigateToDataURLAndCheckForTerminationDisabler(
shell(), VISIBILITYCHANGE_HTML, false /* expect_unload */,
false /* expect_beforeunload */, false /* expect_pagehide */,
true /* expect_visibilitychange */);
web_contents->UpdateWebContentsVisibility(Visibility::VISIBLE);
EXPECT_TRUE(shell()->web_contents()->NeedToFireBeforeUnloadOrUnloadEvents());
// The visibilitychange handler won't block sudden termination if the tab is
// already hidden.
web_contents->UpdateWebContentsVisibility(Visibility::HIDDEN);
EXPECT_TRUE(
static_cast<WebContentsImpl*>(shell()->web_contents())->IsHidden());
EXPECT_FALSE(shell()->web_contents()->NeedToFireBeforeUnloadOrUnloadEvents());
// The visibilitychange handler will block sudden termination if the tab
// becomes visible again.
web_contents->UpdateWebContentsVisibility(Visibility::VISIBLE);
EXPECT_TRUE(shell()->web_contents()->NeedToFireBeforeUnloadOrUnloadEvents());
// The visibilitychange handler won't block sudden termination if the tab is
// occluded (because we treat it as hidden), unless when occlusion is
// disabled, in which case we treat it the same as being visible.
const bool occlusion_is_disabled =
base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDisableBackgroundingOccludedWindowsForTesting);
web_contents->UpdateWebContentsVisibility(Visibility::OCCLUDED);
EXPECT_EQ(occlusion_is_disabled,
shell()->web_contents()->NeedToFireBeforeUnloadOrUnloadEvents());
}
class TestWCDelegateForDialogsAndFullscreen : public JavaScriptDialogManager,
public WebContentsDelegate {
public:
explicit TestWCDelegateForDialogsAndFullscreen(WebContentsImpl* web_contents)
: web_contents_(web_contents) {
old_delegate_ = web_contents_->GetDelegate();
web_contents_->SetDelegate(this);
}
~TestWCDelegateForDialogsAndFullscreen() override {
web_contents_->SetDelegate(old_delegate_);
}
TestWCDelegateForDialogsAndFullscreen(
const TestWCDelegateForDialogsAndFullscreen&) = delete;
TestWCDelegateForDialogsAndFullscreen& operator=(
const TestWCDelegateForDialogsAndFullscreen&) = delete;
void WillWaitForDialog() { waiting_for_ = kDialog; }
void WillWaitForNewContents() { waiting_for_ = kNewContents; }
void WillWaitForFullscreenEnter() { waiting_for_ = kFullscreenEnter; }
void WillWaitForFullscreenExit() { waiting_for_ = kFullscreenExit; }
void WillWaitForFullscreenOption() { waiting_for_ = kFullscreenOptions; }
void Wait() {
run_loop_->Run();
run_loop_ = std::make_unique<base::RunLoop>();
}
std::string last_message() { return last_message_; }
WebContents* last_popup() { return popups_.back().get(); }
// WebContentsDelegate
JavaScriptDialogManager* GetJavaScriptDialogManager(
WebContents* source) override {
return this;
}
void EnterFullscreenModeForTab(
RenderFrameHost* requesting_frame,
const blink::mojom::FullscreenOptions& options) override {
fullscreen_mode_ = WebContents::FromRenderFrameHost(requesting_frame)
->IsBeingVisiblyCaptured()
? FullscreenMode::kPseudoContent
: FullscreenMode::kContent;
fullscreen_options_ = options;
if (waiting_for_ == kFullscreenEnter) {
waiting_for_ = kNothing;
run_loop_->Quit();
}
}
void FullscreenStateChangedForTab(
RenderFrameHost* requesting_frame,
const blink::mojom::FullscreenOptions& options) override {
fullscreen_options_ = options;
if (waiting_for_ == kFullscreenOptions) {
waiting_for_ = kNothing;
run_loop_->Quit();
}
}
void ExitFullscreenModeForTab(WebContents*) override {
fullscreen_mode_ = FullscreenMode::kWindowed;
fullscreen_options_ = blink::mojom::FullscreenOptions();
if (waiting_for_ == kFullscreenExit) {
waiting_for_ = kNothing;
run_loop_->Quit();
}
}
bool IsFullscreenForTabOrPending(const WebContents* web_contents) override {
return fullscreen_mode_ == FullscreenMode::kContent ||
fullscreen_mode_ == FullscreenMode::kPseudoContent;
}
FullscreenState GetFullscreenState(
const WebContents* web_contents) const override {
FullscreenState state;
state.target_mode = fullscreen_mode_;
state.target_display_id = fullscreen_options_.display_id;
return state;
}
const blink::mojom::FullscreenOptions& fullscreen_options() {
return fullscreen_options_;
}
WebContents* AddNewContents(
WebContents* source,
std::unique_ptr<WebContents> new_contents,
const GURL& target_url,
WindowOpenDisposition disposition,
const blink::mojom::WindowFeatures& window_features,
bool user_gesture,
bool* was_blocked) override {
popups_.push_back(std::move(new_contents));
if (waiting_for_ == kNewContents) {
waiting_for_ = kNothing;
run_loop_->Quit();
}
return nullptr;
}
// JavaScriptDialogManager
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 {
last_message_ = base::UTF16ToUTF8(message_text);
*did_suppress_message = true;
if (waiting_for_ == kDialog) {
waiting_for_ = kNothing;
run_loop_->Quit();
}
}
void RunBeforeUnloadDialog(WebContents* web_contents,
RenderFrameHost* render_frame_host,
bool is_reload,
DialogClosedCallback callback) override {
std::move(callback).Run(true, std::u16string());
if (waiting_for_ == kDialog) {
waiting_for_ = kNothing;
run_loop_->Quit();
}
}
bool HandleJavaScriptDialog(WebContents* web_contents,
bool accept,
const std::u16string* prompt_override) override {
return true;
}
void CancelDialogs(WebContents* web_contents, bool reset_state) override {}
private:
raw_ptr<WebContentsImpl> web_contents_;
raw_ptr<WebContentsDelegate> old_delegate_;
enum {
kNothing,
kDialog,
kNewContents,
kFullscreenEnter,
kFullscreenExit,
kFullscreenOptions,
} waiting_for_ = kNothing;
std::string last_message_;
FullscreenMode fullscreen_mode_ = FullscreenMode::kWindowed;
blink::mojom::FullscreenOptions fullscreen_options_;
std::vector<std::unique_ptr<WebContents>> popups_;
std::unique_ptr<base::RunLoop> run_loop_ = std::make_unique<base::RunLoop>();
};
class MockFileSelectListener : public FileChooserImpl::FileSelectListenerImpl {
public:
MockFileSelectListener() : FileChooserImpl::FileSelectListenerImpl(nullptr) {
SetListenerFunctionCalledTrueForTesting();
}
void FileSelected(std::vector<blink::mojom::FileChooserFileInfoPtr> files,
const base::FilePath& base_dir,
blink::mojom::FileChooserParams::Mode mode) override {}
void FileSelectionCanceled() override { cancelled_ = true; }
bool cancelled() const { return cancelled_; }
private:
~MockFileSelectListener() override = default;
bool cancelled_ = false;
};
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
JavaScriptDialogsInMainAndSubframes) {
WebContentsImpl* wc = static_cast<WebContentsImpl*>(shell()->web_contents());
TestWCDelegateForDialogsAndFullscreen test_delegate(wc);
ASSERT_TRUE(embedded_test_server()->Start());
EXPECT_TRUE(NavigateToURL(
shell(), embedded_test_server()->GetURL("a.com", "/title1.html")));
EXPECT_TRUE(WaitForLoadStop(wc));
FrameTreeNode* root = wc->GetPrimaryFrameTree().root();
ASSERT_EQ(0U, root->child_count());
std::string script =
"var iframe = document.createElement('iframe');"
"document.body.appendChild(iframe);";
EXPECT_TRUE(ExecJs(root->current_frame_host(), script));
EXPECT_TRUE(WaitForLoadStop(shell()->web_contents()));
ASSERT_EQ(1U, root->child_count());
FrameTreeNode* frame = root->child_at(0);
ASSERT_NE(nullptr, frame);
GURL::Replacements clear_port;
clear_port.ClearPort();
// A dialog from the main frame.
std::string alert_location = "alert(document.location)";
test_delegate.WillWaitForDialog();
EXPECT_TRUE(ExecJs(root->current_frame_host(), alert_location));
test_delegate.Wait();
EXPECT_EQ(GURL("http://a.com/title1.html"),
GURL(test_delegate.last_message()).ReplaceComponents(clear_port));
test_delegate.WillWaitForDialog();
EXPECT_TRUE(ExecJs(frame->current_frame_host(), alert_location));
test_delegate.Wait();
EXPECT_EQ("about:blank", test_delegate.last_message());
// These is a different origin iframe, so alerts won't work if the feature
// is enabled. Ideally we would test they don't show, but there is no way
// to check for a lack of dialog window.
if (!base::FeatureList::IsEnabled(
features::kSuppressDifferentOriginSubframeJSDialogs)) {
// A dialog from the subframe.
// Navigate the subframe cross-site.
EXPECT_TRUE(NavigateToURLFromRenderer(
frame, embedded_test_server()->GetURL("b.com", "/title2.html")));
EXPECT_TRUE(WaitForLoadStop(wc));
// A dialog from the subframe.
test_delegate.WillWaitForDialog();
EXPECT_TRUE(ExecJs(frame->current_frame_host(), alert_location));
test_delegate.Wait();
EXPECT_EQ(GURL("http://b.com/title2.html"),
GURL(test_delegate.last_message()).ReplaceComponents(clear_port));
}
// Navigate the subframe to the same origin as the main frame; ensure
// dialogs work.
// Navigate the subframe cross-site.
GURL same_origin_url =
embedded_test_server()->GetURL("a.com", "/title2.html");
EXPECT_TRUE(NavigateToURLFromRenderer(frame, same_origin_url));
EXPECT_TRUE(WaitForLoadStop(wc));
test_delegate.WillWaitForDialog();
EXPECT_TRUE(ExecJs(frame->current_frame_host(), alert_location));
test_delegate.Wait();
EXPECT_EQ(same_origin_url.spec(), test_delegate.last_message());
// A dialog from the main frame.
test_delegate.WillWaitForDialog();
EXPECT_TRUE(ExecJs(root->current_frame_host(), alert_location));
test_delegate.Wait();
EXPECT_EQ(GURL("http://a.com/title1.html"),
GURL(test_delegate.last_message()).ReplaceComponents(clear_port));
// Navigate the top frame cross-site; ensure that dialogs work.
EXPECT_TRUE(NavigateToURL(
shell(), embedded_test_server()->GetURL("c.com", "/title3.html")));
EXPECT_TRUE(WaitForLoadStop(wc));
test_delegate.WillWaitForDialog();
EXPECT_TRUE(ExecJs(root->current_frame_host(), alert_location));
test_delegate.Wait();
EXPECT_EQ(GURL("http://c.com/title3.html"),
GURL(test_delegate.last_message()).ReplaceComponents(clear_port));
// Navigate back; ensure that dialogs work.
wc->GetController().GoBack();
EXPECT_TRUE(WaitForLoadStop(wc));
test_delegate.WillWaitForDialog();
EXPECT_TRUE(ExecJs(root->current_frame_host(), alert_location));
test_delegate.Wait();
EXPECT_EQ(GURL("http://a.com/title1.html"),
GURL(test_delegate.last_message()).ReplaceComponents(clear_port));
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
JavaScriptDialogsNormalizeText) {
WebContentsImpl* wc = static_cast<WebContentsImpl*>(shell()->web_contents());
TestWCDelegateForDialogsAndFullscreen test_delegate(wc);
GURL url("about:blank");
EXPECT_TRUE(NavigateToURL(shell(), url));
// A dialog with mixed linebreaks.
std::string alert = "alert('1\\r2\\r\\n3\\n4')";
test_delegate.WillWaitForDialog();
EXPECT_TRUE(ExecJs(wc, alert));
test_delegate.Wait();
EXPECT_EQ("1\n2\n3\n4", test_delegate.last_message());
}
class WebContentsImplBrowserTestWithDifferentOriginSubframeDialogSuppression
: public WebContentsImplBrowserTest {
public:
void SetUp() override {
scoped_feature_list_.Reset();
scoped_feature_list_.InitAndEnableFeature(
features::kSuppressDifferentOriginSubframeJSDialogs);
WebContentsImplBrowserTest::SetUp();
}
};
IN_PROC_BROWSER_TEST_F(
WebContentsImplBrowserTestWithDifferentOriginSubframeDialogSuppression,
OriginTrialDisablesSuppression) {
// Generated with tools/origin_trials/generate_token.py --expire-days 5000
// http://allowdialogs.test:9999
// DisableDifferentOriginSubframeDialogSuppression
std::string origin_trial_token =
"AwcVbxsLRzn8IXBNaeCrK7amKs211vWkv5oCYo+gssujKeltEtcIaQD+O9hWO+"
"GT3WtKUFhEA30+QuqyU3TUvQkAAAB/"
"eyJvcmlnaW4iOiAiaHR0cDovL2FsbG93ZGlhbG9ncy50ZXN0Ojk5OTkiLCAiZmVhdHVyZSI6"
"ICJEaXNhYmxlRGlmZmVyZW50T3JpZ2luU3ViZnJhbWVEaWFsb2dTdXBwcmVzc2lvbiIsICJl"
"eHBpcnkiOiAyMDU0NzU5MTcyfQ==";
GURL origin_trial_url = GURL("http://allowdialogs.test:9999");
WebContentsImpl* wc = static_cast<WebContentsImpl*>(shell()->web_contents());
TestWCDelegateForDialogsAndFullscreen test_delegate(wc);
ASSERT_TRUE(embedded_test_server()->Start());
EXPECT_TRUE(NavigateToURL(
shell(), embedded_test_server()->GetURL("a.com", "/title1.html")));
EXPECT_TRUE(WaitForLoadStop(wc));
FrameTreeNode* root = wc->GetPrimaryFrameTree().root();
ASSERT_EQ(0U, root->child_count());
std::string script =
"var iframe = document.createElement('iframe');"
"document.body.appendChild(iframe);";
EXPECT_TRUE(ExecJs(root->current_frame_host(), script));
EXPECT_TRUE(WaitForLoadStop(shell()->web_contents()));
ASSERT_EQ(1U, root->child_count());
FrameTreeNode* frame = root->child_at(0);
ASSERT_NE(nullptr, frame);
// We need to use a URLLoaderInterceptor for the subframe since origin trial
// is origin bound, and embedded test server randomizes ports.
URLLoaderInterceptor interceptor(base::BindLambdaForTesting(
[&](URLLoaderInterceptor::RequestParams* params) {
if (params->url_request.url != origin_trial_url)
return false;
URLLoaderInterceptor::WriteResponse(
"HTTP/1.1 200 OK\n"
"Content-type: text/html\n"
"Origin-Trial: " +
origin_trial_token + "\n\n",
"", params->client.get());
return true;
}));
// A dialog from the subframe.
// Navigate the subframe to the site with the origin trial meta tag.
EXPECT_TRUE(NavigateToURLFromRenderer(frame, origin_trial_url));
EXPECT_TRUE(WaitForLoadStop(wc));
// A dialog from the subframe, which should show even though different origin
// subframe dialog suppression is enabled, since the origin trial overrides
// it.
std::string alert_location = "alert(document.location)";
test_delegate.WillWaitForDialog();
EXPECT_TRUE(ExecJs(frame->current_frame_host(), alert_location));
test_delegate.Wait();
EXPECT_EQ(origin_trial_url, GURL(test_delegate.last_message()));
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
CreateWebContentsWithRendererProcess) {
ASSERT_TRUE(embedded_test_server()->Start());
WebContents* base_web_contents = shell()->web_contents();
ASSERT_TRUE(base_web_contents);
WebContents::CreateParams create_params(
base_web_contents->GetBrowserContext());
create_params.desired_renderer_state =
WebContents::CreateParams::kInitializeAndWarmupRendererProcess;
std::unique_ptr<WebContents> web_contents(WebContents::Create(create_params));
ASSERT_TRUE(web_contents);
// There is no navigation (to about:blank or something like that).
EXPECT_FALSE(web_contents->IsLoading());
// The WebContents have an associated main frame and a renderer process that
// has either already launched (or is in the process of being launched).
ASSERT_TRUE(web_contents->GetPrimaryMainFrame());
EXPECT_TRUE(web_contents->GetPrimaryMainFrame()->IsRenderFrameLive());
EXPECT_TRUE(web_contents->GetController().IsInitialBlankNavigation());
RenderProcessHost* process =
web_contents->GetPrimaryMainFrame()->GetProcess();
int renderer_id = process->GetDeprecatedID();
ASSERT_TRUE(process);
EXPECT_TRUE(process->IsInitializedAndNotDead());
// Navigate the WebContents.
GURL url(embedded_test_server()->GetURL("c.com", "/title3.html"));
TestNavigationObserver same_tab_observer(web_contents.get());
NavigationController::LoadURLParams params(url);
params.transition_type = ui::PageTransitionFromInt(
ui::PAGE_TRANSITION_TYPED | ui::PAGE_TRANSITION_FROM_ADDRESS_BAR);
web_contents->GetController().LoadURLWithParams(params);
same_tab_observer.Wait();
EXPECT_TRUE(same_tab_observer.last_navigation_succeeded());
// Check that pre-warmed process is used.
EXPECT_EQ(process, web_contents->GetPrimaryMainFrame()->GetProcess());
EXPECT_EQ(
renderer_id,
web_contents->GetPrimaryMainFrame()->GetProcess()->GetDeprecatedID());
EXPECT_EQ(1, web_contents->GetController().GetEntryCount());
NavigationEntry* entry =
web_contents->GetController().GetLastCommittedEntry();
ASSERT_TRUE(entry);
EXPECT_EQ(url, entry->GetURL());
}
// Regression test for https://crbug.com/840409.
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
CreateWebContentsWithoutRendererProcess) {
ASSERT_TRUE(embedded_test_server()->Start());
WebContents* base_web_contents = shell()->web_contents();
ASSERT_TRUE(base_web_contents);
for (int i = 1; i <= 2; i++) {
SCOPED_TRACE(testing::Message() << "Iteration #" << i);
WebContents::CreateParams create_params(
base_web_contents->GetBrowserContext());
create_params.desired_renderer_state =
WebContents::CreateParams::kNoRendererProcess;
std::unique_ptr<WebContents> web_contents(
WebContents::Create(create_params));
ASSERT_TRUE(web_contents);
base::RunLoop().RunUntilIdle();
// There is no navigation (to about:blank or something like that) yet.
EXPECT_FALSE(web_contents->IsLoading());
// The WebContents have an associated main frame and a RenderProcessHost
// object, but no actual OS process has been launched yet.
ASSERT_TRUE(web_contents->GetPrimaryMainFrame());
EXPECT_FALSE(web_contents->GetPrimaryMainFrame()->IsRenderFrameLive());
EXPECT_TRUE(web_contents->GetController().IsInitialBlankNavigation());
RenderProcessHost* process =
web_contents->GetPrimaryMainFrame()->GetProcess();
int renderer_id = process->GetDeprecatedID();
ASSERT_TRUE(process);
EXPECT_FALSE(process->IsInitializedAndNotDead());
EXPECT_EQ(base::kNullProcessHandle, process->GetProcess().Handle());
// Navigate the WebContents.
GURL url(embedded_test_server()->GetURL("c.com", "/title3.html"));
TestNavigationObserver same_tab_observer(web_contents.get());
NavigationController::LoadURLParams params(url);
params.transition_type = ui::PageTransitionFromInt(
ui::PAGE_TRANSITION_TYPED | ui::PAGE_TRANSITION_FROM_ADDRESS_BAR);
web_contents->GetController().LoadURLWithParams(params);
same_tab_observer.Wait();
EXPECT_TRUE(same_tab_observer.last_navigation_succeeded());
// The process should be launched now.
EXPECT_TRUE(process->IsInitializedAndNotDead());
EXPECT_NE(base::kNullProcessHandle, process->GetProcess().Handle());
// Check that the RenderProcessHost and its ID didn't change.
EXPECT_EQ(process, web_contents->GetPrimaryMainFrame()->GetProcess());
EXPECT_EQ(
renderer_id,
web_contents->GetPrimaryMainFrame()->GetProcess()->GetDeprecatedID());
// Verify that the navigation succeeded.
EXPECT_EQ(1, web_contents->GetController().GetEntryCount());
NavigationEntry* entry =
web_contents->GetController().GetLastCommittedEntry();
ASSERT_TRUE(entry);
EXPECT_EQ(url, entry->GetURL());
}
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
NavigatingToWebUIUsesPreWarmedProcess) {
GURL web_ui_url(std::string(kChromeUIScheme) + "://" +
std::string(kChromeUIGpuHost));
ASSERT_TRUE(embedded_test_server()->Start());
WebContents* base_web_contents = shell()->web_contents();
ASSERT_TRUE(base_web_contents);
WebContents::CreateParams create_params(
base_web_contents->GetBrowserContext());
create_params.desired_renderer_state =
WebContents::CreateParams::kInitializeAndWarmupRendererProcess;
std::unique_ptr<WebContents> web_contents(WebContents::Create(create_params));
ASSERT_TRUE(web_contents);
// There is no navigation (to about:blank or something like that).
EXPECT_FALSE(web_contents->IsLoading());
ASSERT_TRUE(web_contents->GetPrimaryMainFrame());
EXPECT_TRUE(web_contents->GetPrimaryMainFrame()->IsRenderFrameLive());
EXPECT_TRUE(web_contents->GetController().IsInitialBlankNavigation());
int renderer_id =
web_contents->GetPrimaryMainFrame()->GetProcess()->GetDeprecatedID();
TestNavigationObserver same_tab_observer(web_contents.get(), 1);
NavigationController::LoadURLParams params(web_ui_url);
params.transition_type = ui::PageTransitionFromInt(
ui::PAGE_TRANSITION_TYPED | ui::PAGE_TRANSITION_FROM_ADDRESS_BAR);
web_contents->GetController().LoadURLWithParams(params);
same_tab_observer.Wait();
// Check that pre-warmed process was used. This is possible because the
// initial RenderFrameHost is allowed to be reused for WebUI, even if it has a
// live RenderFrame, as long as its SiteInstance is unassigned and its process
// is unused.
EXPECT_EQ(
renderer_id,
web_contents->GetPrimaryMainFrame()->GetProcess()->GetDeprecatedID());
EXPECT_EQ(1, web_contents->GetController().GetEntryCount());
NavigationEntry* entry =
web_contents->GetController().GetLastCommittedEntry();
ASSERT_TRUE(entry);
EXPECT_EQ(web_ui_url, entry->GetURL());
}
namespace {
class DownloadImageObserver {
public:
MOCK_METHOD5(OnFinishDownloadImage,
void(int id,
int status_code,
const GURL& image_url,
const std::vector<SkBitmap>& bitmap,
const std::vector<gfx::Size>& sizes));
~DownloadImageObserver() = default;
};
void DownloadImageTestInternal(Shell* shell,
const GURL& image_url,
int expected_http_status,
int expected_number_of_images) {
using ::testing::_;
using ::testing::InvokeWithoutArgs;
using ::testing::SizeIs;
// Set up everything.
DownloadImageObserver download_image_observer;
scoped_refptr<MessageLoopRunner> loop_runner = new MessageLoopRunner();
// Set up expectation and stub.
EXPECT_CALL(download_image_observer,
OnFinishDownloadImage(_, expected_http_status, _,
SizeIs(expected_number_of_images), _));
ON_CALL(download_image_observer, OnFinishDownloadImage(_, _, _, _, _))
.WillByDefault(
InvokeWithoutArgs(loop_runner.get(), &MessageLoopRunner::Quit));
shell->LoadURL(GURL("about:blank"));
shell->web_contents()->DownloadImage(
image_url, false, gfx::Size(), 1024, false,
base::BindOnce(&DownloadImageObserver::OnFinishDownloadImage,
base::Unretained(&download_image_observer)));
// Wait for response.
loop_runner->Run();
}
void ExpectNoValidImageCallback(base::OnceClosure quit_closure,
int id,
int status_code,
const GURL& image_url,
const std::vector<SkBitmap>& bitmap,
const std::vector<gfx::Size>& sizes) {
EXPECT_EQ(200, status_code);
EXPECT_TRUE(bitmap.empty());
EXPECT_TRUE(sizes.empty());
std::move(quit_closure).Run();
}
void ExpectSingleValidImageCallback(base::OnceClosure quit_closure,
int expected_width,
int expected_height,
int id,
int status_code,
const GURL& image_url,
const std::vector<SkBitmap>& bitmap,
const std::vector<gfx::Size>& sizes) {
EXPECT_EQ(200, status_code);
ASSERT_EQ(bitmap.size(), 1u);
EXPECT_EQ(bitmap[0].width(), expected_width);
EXPECT_EQ(bitmap[0].height(), expected_height);
ASSERT_EQ(sizes.size(), 1u);
EXPECT_EQ(sizes[0].width(), expected_width);
EXPECT_EQ(sizes[0].height(), expected_height);
std::move(quit_closure).Run();
}
} // anonymous namespace
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest, DownloadImage_HttpImage) {
ASSERT_TRUE(embedded_test_server()->Start());
const GURL kImageUrl = embedded_test_server()->GetURL("/single_face.jpg");
DownloadImageTestInternal(shell(), kImageUrl, 200, 1);
}
// Disabled due to flakiness: https://crbug.com/1124349.
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
DISABLED_DownloadImage_Deny_FileImage) {
ASSERT_TRUE(embedded_test_server()->Start());
shell()->LoadURL(embedded_test_server()->GetURL("/simple_page.html"));
const GURL kImageUrl = GetTestUrl("", "single_face.jpg");
DownloadImageTestInternal(shell(), kImageUrl, 0, 0);
}
// Disabled due to flakiness: https://crbug.com/1124349.
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
DISABLED_DownloadImage_Allow_FileImage) {
shell()->LoadURL(GetTestUrl("", "simple_page.html"));
const GURL kImageUrl = GetTestUrl("", "image.jpg");
DownloadImageTestInternal(shell(), kImageUrl, 0, 0);
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest, DownloadImage_NoValidImage) {
ASSERT_TRUE(embedded_test_server()->Start());
const GURL kImageUrl = embedded_test_server()->GetURL("/invalid.ico");
shell()->LoadURL(GURL("about:blank"));
base::RunLoop run_loop;
shell()->web_contents()->DownloadImage(
kImageUrl, false, gfx::Size(), 2, false,
base::BindOnce(&ExpectNoValidImageCallback, run_loop.QuitClosure()));
run_loop.Run();
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest, DownloadImage_DataImage) {
const GURL kImageUrl = GURL(
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHE"
"lEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==");
DownloadImageTestInternal(shell(), kImageUrl, 0, 1);
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
DownloadImage_InvalidDataImage) {
const GURL kImageUrl = GURL("data:image/png;invalid");
DownloadImageTestInternal(shell(), kImageUrl, 0, 0);
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest, DownloadImage_DataImageSVG) {
const GURL kImageUrl(
"data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' "
"width='64' height='64'></svg>");
DownloadImageTestInternal(shell(), kImageUrl, 0, 1);
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
DownloadImage_PreferredSize) {
ASSERT_TRUE(embedded_test_server()->Start());
const GURL kImageUrl = embedded_test_server()->GetURL("/rgb.svg");
shell()->LoadURL(GURL("about:blank"));
base::RunLoop run_loop;
shell()->web_contents()->DownloadImage(
kImageUrl, false, gfx::Size(30, 30), 1024, false,
base::BindOnce(&ExpectSingleValidImageCallback, run_loop.QuitClosure(),
30, 30));
run_loop.Run();
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
DownloadImage_PreferredSizeZero) {
ASSERT_TRUE(embedded_test_server()->Start());
const GURL kImageUrl = embedded_test_server()->GetURL("/rgb.svg");
shell()->LoadURL(GURL("about:blank"));
base::RunLoop run_loop;
shell()->web_contents()->DownloadImage(
kImageUrl, false, gfx::Size(), 1024, false,
base::BindOnce(&ExpectSingleValidImageCallback, run_loop.QuitClosure(),
90, 90));
run_loop.Run();
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
DownloadImage_PreferredSizeClampedByMaxSize) {
ASSERT_TRUE(embedded_test_server()->Start());
const GURL kImageUrl = embedded_test_server()->GetURL("/rgb.svg");
shell()->LoadURL(GURL("about:blank"));
base::RunLoop run_loop;
shell()->web_contents()->DownloadImage(
kImageUrl, false, gfx::Size(60, 60), 30, false,
base::BindOnce(&ExpectSingleValidImageCallback, run_loop.QuitClosure(),
30, 30));
run_loop.Run();
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
DownloadImage_PreferredWidthClampedByMaxSize) {
ASSERT_TRUE(embedded_test_server()->Start());
const GURL kImageUrl = embedded_test_server()->GetURL("/rgb.svg");
shell()->LoadURL(GURL("about:blank"));
base::RunLoop run_loop;
shell()->web_contents()->DownloadImage(
kImageUrl, false, gfx::Size(60, 30), 30, false,
base::BindOnce(&ExpectSingleValidImageCallback, run_loop.QuitClosure(),
30, 15));
run_loop.Run();
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
DownloadImage_PreferredHeightClampedByMaxSize) {
ASSERT_TRUE(embedded_test_server()->Start());
const GURL kImageUrl = embedded_test_server()->GetURL("/rgb.svg");
shell()->LoadURL(GURL("about:blank"));
base::RunLoop run_loop;
shell()->web_contents()->DownloadImage(
kImageUrl, false, gfx::Size(30, 60), 30, false,
base::BindOnce(&ExpectSingleValidImageCallback, run_loop.QuitClosure(),
15, 30));
run_loop.Run();
}
namespace {
void ExpectTwoValidImageCallback(base::OnceClosure quit_closure,
const std::vector<gfx::Size>& expected_sizes,
int id,
int status_code,
const GURL& image_url,
const std::vector<SkBitmap>& bitmap,
const std::vector<gfx::Size>& sizes) {
EXPECT_EQ(200, status_code);
ASSERT_EQ(bitmap.size(), expected_sizes.size());
ASSERT_EQ(sizes.size(), expected_sizes.size());
for (size_t i = 0; i < expected_sizes.size(); ++i) {
EXPECT_EQ(gfx::Size(bitmap[i].width(), bitmap[i].height()),
expected_sizes[i]);
EXPECT_EQ(sizes[i], expected_sizes[i]);
}
std::move(quit_closure).Run();
}
} // anonymous namespace
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
DownloadImage_MultipleImagesNoMaxSize) {
ASSERT_TRUE(embedded_test_server()->Start());
const GURL kImageUrl =
embedded_test_server()->GetURL("/icon-with-two-entries.ico");
shell()->LoadURL(GURL("about:blank"));
base::RunLoop run_loop;
std::vector<gfx::Size> expected_sizes{{16, 16}, {32, 32}};
shell()->web_contents()->DownloadImage(
kImageUrl, false, gfx::Size(), 0, false,
base::BindOnce(&ExpectTwoValidImageCallback, run_loop.QuitClosure(),
expected_sizes));
run_loop.Run();
}
class PointerLockDelegate : public WebContentsDelegate {
public:
// WebContentsDelegate:
void RequestPointerLock(WebContents* web_contents,
bool user_gesture,
bool last_unlocked_by_target) override {
request_pointer_lock_called_ = true;
}
bool request_pointer_lock_called_ = false;
};
// TODO(crbug.com/41422519): This test is flaky.
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
DISABLED_RenderWidgetDeletedWhileMouseLockPending) {
ASSERT_TRUE(embedded_test_server()->Start());
std::unique_ptr<PointerLockDelegate> delegate(new PointerLockDelegate());
shell()->web_contents()->SetDelegate(delegate.get());
ASSERT_TRUE(shell()->web_contents()->GetDelegate() == delegate.get());
EXPECT_TRUE(NavigateToURL(
shell(), embedded_test_server()->GetURL("a.com", "/title1.html")));
// Try to request pointer lock. WebContentsDelegate should get a notification.
ASSERT_TRUE(ExecJs(shell(),
"window.domAutomationController.send(document.body."
"requestPointerLock());"));
EXPECT_TRUE(delegate.get()->request_pointer_lock_called_);
// Make sure that the renderer didn't get the pointer lock, since the
// WebContentsDelegate didn't approve the notification.
EXPECT_EQ(true, EvalJs(shell(), "document.pointerLockElement == null;"));
// Try to request the pointer lock again. Since there's a pending request in
// WebContentsDelelgate, the WebContents shouldn't ask again.
delegate.get()->request_pointer_lock_called_ = false;
ASSERT_TRUE(ExecJs(shell(),
"window.domAutomationController.send(document.body."
"requestPointerLock());"));
EXPECT_FALSE(delegate.get()->request_pointer_lock_called_);
// Force a cross-process navigation so that the RenderWidgetHost is deleted.
EXPECT_TRUE(NavigateToURL(
shell(), embedded_test_server()->GetURL("b.com", "/title1.html")));
// Make sure the WebContents cleaned up the previous pending request. A new
// request should be forwarded to the WebContentsDelegate.
delegate.get()->request_pointer_lock_called_ = false;
ASSERT_TRUE(ExecJs(shell(),
"window.domAutomationController.send(document.body."
"requestPointerLock());"));
EXPECT_TRUE(delegate.get()->request_pointer_lock_called_);
}
// Checks that user agent override string is only used when it's overridden.
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest, UserAgentOverride) {
ASSERT_TRUE(embedded_test_server()->Start());
const std::string kHeaderPath =
std::string("/echoheader?") + net::HttpRequestHeaders::kUserAgent;
const GURL kUrl(embedded_test_server()->GetURL(kHeaderPath));
const std::string kUserAgentOverride = "foo";
EXPECT_TRUE(NavigateToURL(shell(), kUrl));
EXPECT_NE(kUserAgentOverride,
EvalJs(shell()->web_contents(), "document.body.textContent;"));
shell()->web_contents()->SetUserAgentOverride(
blink::UserAgentOverride::UserAgentOnly("foo"), false);
EXPECT_TRUE(NavigateToURL(shell(), kUrl));
EXPECT_NE(kUserAgentOverride,
EvalJs(shell()->web_contents(), "document.body.textContent;"));
shell()
->web_contents()
->GetController()
.GetLastCommittedEntry()
->SetIsOverridingUserAgent(true);
TestNavigationObserver tab_observer(shell()->web_contents(), 1);
shell()->web_contents()->GetController().Reload(ReloadType::NORMAL, false);
tab_observer.Wait();
EXPECT_EQ(kUserAgentOverride,
EvalJs(shell()->web_contents(), "document.body.textContent;"));
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
UserAgentOverrideDuringDeferredNavigation) {
// Validates that when a deferred navigation is pending (e.g. in the case of
// Android WebView popups), we respect any user agent overrides that are set
// to apply to new tabs during this time.
ASSERT_TRUE(embedded_test_server()->Start());
const std::string kHeaderPath =
base::StrCat({"/echoheader?", net::HttpRequestHeaders::kUserAgent});
const GURL kUrl(embedded_test_server()->GetURL(kHeaderPath));
const std::string kUserAgentOverride = "foo";
shell()->set_delay_popup_contents_delegate_for_testing(true);
EXPECT_TRUE(NavigateToURL(shell(), kUrl));
// Make a popup.
Shell* new_shell = nullptr;
WebContents* new_contents = nullptr;
{
ShellAddedObserver new_shell_observer;
// Set `noopener` to force a deferred navigation (setting
// `delayed_load_url_params_` rather than triggering the navigation from the
// renderer).
std::string popup_script = JsReplace("window.open($1,'','noopener')", kUrl);
EXPECT_TRUE(ExecJs(shell(), popup_script));
new_shell = new_shell_observer.GetShell();
new_contents = new_shell->web_contents();
// Delaying popup holds the initial load of `url`.
EXPECT_TRUE(WaitForLoadStop(new_contents));
EXPECT_TRUE(new_contents->GetController()
.GetLastCommittedEntry()
->IsInitialEntry());
}
EXPECT_TRUE(
static_cast<WebContentsImpl*>(new_contents)->delayed_load_url_params_);
EXPECT_EQ(static_cast<WebContentsImpl*>(new_contents)
->delayed_load_url_params_->override_user_agent,
NavigationController::UA_OVERRIDE_FALSE);
// After the popup has been created - but before the navigation is made -
// override the UA, akin to AwSettings application of user agent overrides.
new_contents->SetUserAgentOverride(
blink::UserAgentOverride::UserAgentOnly("foo"), true);
// Validate that the pending request has been updated.
EXPECT_EQ(static_cast<WebContentsImpl*>(new_contents)
->delayed_load_url_params_->override_user_agent,
NavigationController::UA_OVERRIDE_TRUE);
// Resume loading by setting the delegate (via
// `set_delay_popup_contents_delegate_for_testing()`).
EXPECT_FALSE(new_contents->GetDelegate());
new_contents->SetDelegate(new_shell);
new_contents->ResumeLoadingCreatedWebContents();
EXPECT_TRUE(WaitForLoadStop(new_contents));
// Ensure that the override was properly set, even when a navigation was
// enqueued.
EXPECT_EQ(kUserAgentOverride,
EvalJs(new_contents, "document.body.textContent;"));
}
// Verifies the user-agent string may be changed in DidStartNavigation().
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
SetUserAgentOverrideFromDidStartNavigation) {
net::test_server::ExpectationHandler handler(embedded_test_server());
ASSERT_TRUE(embedded_test_server()->Start());
base::test::TestFuture<net::test_server::HttpRequest> request_future;
handler.OnRequest("/test.html")
.RespondWith("text/html; charset=utf-8", "<html>")
.SetValue(request_future);
const std::string user_agent_override = "foo";
UserAgentInjector injector(shell()->web_contents(), user_agent_override);
shell()->web_contents()->GetController().LoadURLWithParams(
NavigationController::LoadURLParams(
embedded_test_server()->GetURL("/test.html")));
EXPECT_EQ(user_agent_override, request_future.Get().headers.at(
net::HttpRequestHeaders::kUserAgent));
EXPECT_TRUE(WaitForLoadStop(shell()->web_contents()));
EXPECT_EQ(user_agent_override,
EvalJs(shell()->web_contents(), "navigator.userAgent;"));
}
// Used by SetIsOverridingUserAgent(), adding assertions unique to it.
class NoEntryUserAgentInjector : public UserAgentInjector {
public:
NoEntryUserAgentInjector(WebContents* web_contents,
const std::string& user_agent)
: UserAgentInjector(web_contents, user_agent) {}
// WebContentsObserver:
void DidStartNavigation(NavigationHandle* navigation_handle) override {
UserAgentInjector::DidStartNavigation(navigation_handle);
// DidStartNavigation() should only be called once for this test.
ASSERT_FALSE(was_did_start_navigation_called_);
was_did_start_navigation_called_ = true;
// This test expects to exercise the code where thee NavigationRequest is
// created before the NavigationEntry.
EXPECT_EQ(
0, static_cast<NavigationRequest*>(navigation_handle)->nav_entry_id());
}
private:
bool was_did_start_navigation_called_ = false;
};
// Verifies the user-agent string may be changed for a NavigationRequest whose
// NavigationEntry is created after the NavigationRequest is.
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
SetIsOverridingUserAgentNoEntry) {
net::test_server::ExpectationHandler handler(embedded_test_server());
// Pre-register responses for specific URL
handler.OnRequest("/test.html").RespondWith("text/html", "<html>");
ASSERT_TRUE(embedded_test_server()->Start());
shell()->web_contents()->GetController().LoadURLWithParams(
NavigationController::LoadURLParams(
embedded_test_server()->GetURL("/test.html")));
EXPECT_TRUE(WaitForLoadStop(shell()->web_contents()));
handler.OnRequest("/test2.html").RespondWith("text/html", "<html>");
shell()->web_contents()->GetController().LoadURLWithParams(
NavigationController::LoadURLParams(
embedded_test_server()->GetURL("/test2.html")));
EXPECT_TRUE(WaitForLoadStop(shell()->web_contents()));
const std::string user_agent_override = "foo";
NoEntryUserAgentInjector injector(shell()->web_contents(),
user_agent_override);
// This tests executes two JS statements. The second statement (reload())
// results in a particular NavigationEntry being created. This only works
// if there is an IPC to the renderer, which was historically always called,
// but now only called if a before-unload handler is present. Force the extra
// IPC by making RenderFrameHost believe there is a before-unload handler.
static_cast<RenderFrameHostImpl*>(
shell()->web_contents()->GetPrimaryMainFrame())
->SuddenTerminationDisablerChanged(
true,
blink::mojom::SuddenTerminationDisablerType::kBeforeUnloadHandler);
// This triggers creating a NavigationRequest without a NavigationEntry. More
// specifically back() triggers creating a pending entry, and because back()
// does not complete, the reload() call results in a NavigationRequest with no
// NavigationEntry.
EXPECT_TRUE(
ExecJs(shell()->web_contents(), "history.back(); location.reload();"));
base::test::TestFuture<net::test_server::HttpRequest> request_future;
// Override the previous behavior for the path "/test.html" to also call
// GetSequenceBoundCallback().Run() on `request_future` with the HttpRequest
// object.
handler.OnRequest("/test2.html")
.RespondWith("text/html", "<html>")
.SetValue(request_future);
EXPECT_TRUE(WaitForLoadStop(shell()->web_contents()));
EXPECT_EQ(user_agent_override, request_future.Get().headers.at(
net::HttpRequestHeaders::kUserAgent));
auto* controller = &(shell()->web_contents()->GetController());
EXPECT_EQ(1, controller->GetLastCommittedEntryIndex());
EXPECT_TRUE(shell()
->web_contents()
->GetController()
.GetLastCommittedEntry()
->GetIsOverridingUserAgent());
EXPECT_EQ(user_agent_override,
EvalJs(shell()->web_contents(), "navigator.userAgent;"));
}
class WebContentsImplBrowserTestClientHintsEnabled
: public WebContentsImplBrowserTest {
public:
void SetUp() override {
scoped_feature_list_.Reset();
WebContentsImplBrowserTest::SetUp();
}
};
// Verifies client hints are updated when the user-agent is changed in
// DidStartNavigation().
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTestClientHintsEnabled,
SetUserAgentOverrideFromDidStartNavigation) {
MockClientHintsControllerDelegate client_hints_controller_delegate(
content::GetShellUserAgentMetadata());
ShellContentBrowserClient::Get()
->browser_context()
->set_client_hints_controller_delegate(&client_hints_controller_delegate);
net::test_server::ExpectationHandler handler(embedded_test_server());
ASSERT_TRUE(embedded_test_server()->Start());
blink::UserAgentOverride ua_override;
ua_override.ua_string_override = "x";
ua_override.ua_metadata_override.emplace();
ua_override.ua_metadata_override->brand_version_list.emplace_back("x", "y");
ua_override.ua_metadata_override->brand_full_version_list.emplace_back("x1",
"y1");
ua_override.ua_metadata_override->mobile = true;
base::test::TestFuture<net::test_server::HttpRequest> request_future;
handler.OnRequest("/test.html")
.RespondWith("text/html; charset=utf-8", "<html>")
.SetValue(request_future);
UserAgentInjector injector(shell()->web_contents(), ua_override);
shell()->web_contents()->GetController().LoadURLWithParams(
NavigationController::LoadURLParams(
embedded_test_server()->GetURL("/test.html")));
EXPECT_TRUE(WaitForLoadStop(shell()->web_contents()));
const std::string mobile_id = network::GetClientHintToNameMap().at(
network::mojom::WebClientHintsType::kUAMobile);
const net::test_server::HttpRequest& request = request_future.Get();
ASSERT_TRUE(base::Contains(request.headers, mobile_id));
// "?!" corresponds to "mobile=true".
EXPECT_EQ("?1", request.headers.at(mobile_id));
ShellContentBrowserClient::Get()
->browser_context()
->set_client_hints_controller_delegate(nullptr);
}
// Verifies client hints are updated when the user-agent is changed in
// DidStartNavigation().
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTestClientHintsEnabled,
SetUserAgentOverrideWithAcceptCHRestart) {
net::EmbeddedTestServer http2_server(
net::EmbeddedTestServer::TYPE_HTTPS,
net::test_server::HttpConnection::Protocol::kHttp2);
MockClientHintsControllerDelegate client_hints_controller_delegate(
content::GetShellUserAgentMetadata());
ShellContentBrowserClient::Get()
->browser_context()
->set_client_hints_controller_delegate(&client_hints_controller_delegate);
std::vector<std::string> accept_ch_tokens;
for (const auto& pair : network::GetClientHintToNameMap())
accept_ch_tokens.push_back(pair.second);
http2_server.SetAlpsAcceptCH("", base::JoinString(accept_ch_tokens, ","));
http2_server.ServeFilesFromSourceDirectory("content/test/data");
base::RunLoop run_loop;
http2_server.RegisterRequestMonitor(base::BindRepeating(
[](base::RunLoop* run_loop,
const net::test_server::HttpRequest& request) {
for (auto header : request.headers)
LOG(INFO) << header.first << ": " << header.second;
if (request.relative_url.compare("/empty.html") == 0) {
EXPECT_EQ(request.headers.at("User-Agent"), "x");
run_loop->Quit();
}
},
&run_loop));
auto handle = http2_server.StartAndReturnHandle();
blink::UserAgentOverride ua_override;
ua_override.ua_string_override = "x";
// Do NOT set `ua_metadata_override`, so the UA-CH headers are *removed*
ua_override.ua_metadata_override = std::nullopt;
UserAgentInjector injector(shell()->web_contents(), ua_override);
EXPECT_TRUE(NavigateToURL(shell(), http2_server.GetURL("/empty.html")));
run_loop.Run();
// This test fails if the browser hangs
ShellContentBrowserClient::Get()
->browser_context()
->set_client_hints_controller_delegate(nullptr);
}
class WebContentsImplBrowserTestReduceAcceptLanguageOn
: public WebContentsImplBrowserTest {
public:
void SetUp() override {
scoped_feature_list_.Reset();
scoped_feature_list_.InitWithFeatures(
{network::features::kReduceAcceptLanguage}, {});
WebContentsImplBrowserTest::SetUp();
}
void VerifyAcceptLanguageHeader(net::EmbeddedTestServer& http_server) {
ReduceAcceptLanguageControllerDelegate* delegate =
ShellContentBrowserClient::Get()
->browser_context()
->GetReduceAcceptLanguageControllerDelegate();
ASSERT_EQ(delegate->GetUserAcceptLanguages(),
std::vector<std::string>({"en-us", "en"}));
http_server.ServeFilesFromSourceDirectory("content/test/data");
base::RunLoop run_loop;
http_server.RegisterRequestMonitor(base::BindRepeating(
[](base::RunLoop* run_loop,
const net::test_server::HttpRequest& request) {
if (request.relative_url.compare("/empty.html") == 0) {
// Default mock user language is "en-us,en", see
// content/shell/browser/shell_content_browser_client.h
ASSERT_EQ(request.headers.at("Accept-Language"), "en-us,en;q=0.9");
run_loop->Quit();
}
},
&run_loop));
auto handle = http_server.StartAndReturnHandle();
EXPECT_TRUE(NavigateToURL(shell(), http_server.GetURL("/empty.html")));
run_loop.Run();
}
void VerifyPersistAndGetReduceAcceptLanguage(
const GURL& url,
const std::string& persist_lang,
const std::optional<std::string>& expect_lang) {
ReduceAcceptLanguageControllerDelegate* delegate =
ShellContentBrowserClient::Get()
->browser_context()
->GetReduceAcceptLanguageControllerDelegate();
url::Origin origin = url::Origin::Create(url);
delegate->PersistReducedLanguage(origin, persist_lang);
const std::optional<std::string>& language =
delegate->GetReducedLanguage(origin);
EXPECT_EQ(expect_lang, language);
delegate->ClearReducedLanguage(origin);
EXPECT_FALSE(delegate->GetReducedLanguage(origin).has_value());
}
};
// Verifies accept-language are updated when DidStartNavigation().
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTestReduceAcceptLanguageOn,
HttpsReduceAcceptLanguageInNavigation) {
net::EmbeddedTestServer http2_server(
net::EmbeddedTestServer::TYPE_HTTPS,
net::test_server::HttpConnection::Protocol::kHttp2);
VerifyAcceptLanguageHeader(http2_server);
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTestReduceAcceptLanguageOn,
HttpReduceAcceptLanguageInNavigation) {
net::EmbeddedTestServer http_server_http(net::EmbeddedTestServer::TYPE_HTTP);
VerifyAcceptLanguageHeader(http_server_http);
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTestReduceAcceptLanguageOn,
PersistAndGetReduceAcceptLanguage) {
std::string test_lang("en-us");
VerifyPersistAndGetReduceAcceptLanguage(/*url=*/GURL("https://example.com/"),
/*persist_lang=*/test_lang,
/*expect_lang=*/test_lang);
VerifyPersistAndGetReduceAcceptLanguage(/*url=*/GURL("http://example.com/"),
/*persist_lang=*/test_lang,
/*expect_lang=*/test_lang);
VerifyPersistAndGetReduceAcceptLanguage(/*url=*/GURL("ws://example.com/"),
/*persist_lang=*/test_lang,
/*expect_lang=*/std::nullopt);
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
DialogsFromJavaScriptEndFullscreen) {
WebContentsImpl* wc = static_cast<WebContentsImpl*>(shell()->web_contents());
TestWCDelegateForDialogsAndFullscreen test_delegate(wc);
GURL url("about:blank");
EXPECT_TRUE(NavigateToURL(shell(), url));
// alert
wc->EnterFullscreenMode(wc->GetPrimaryMainFrame(), {});
EXPECT_TRUE(wc->IsFullscreen());
std::string script = "alert('hi')";
test_delegate.WillWaitForDialog();
EXPECT_TRUE(ExecJs(wc, script));
test_delegate.Wait();
EXPECT_FALSE(wc->IsFullscreen());
// confirm
wc->EnterFullscreenMode(wc->GetPrimaryMainFrame(), {});
EXPECT_TRUE(wc->IsFullscreen());
script = "confirm('hi')";
test_delegate.WillWaitForDialog();
EXPECT_TRUE(ExecJs(wc, script));
test_delegate.Wait();
EXPECT_FALSE(wc->IsFullscreen());
// prompt
wc->EnterFullscreenMode(wc->GetPrimaryMainFrame(), {});
EXPECT_TRUE(wc->IsFullscreen());
script = "prompt('hi')";
test_delegate.WillWaitForDialog();
EXPECT_TRUE(ExecJs(wc, script));
test_delegate.Wait();
EXPECT_FALSE(wc->IsFullscreen());
// beforeunload
wc->EnterFullscreenMode(wc->GetPrimaryMainFrame(), {});
EXPECT_TRUE(wc->IsFullscreen());
// Disable the hang monitor (otherwise there will be a race between the
// beforeunload dialog and the beforeunload hang timer) and give the page a
// gesture to allow dialogs.
wc->GetPrimaryMainFrame()->DisableBeforeUnloadHangMonitorForTesting();
wc->GetPrimaryMainFrame()->ExecuteJavaScriptWithUserGestureForTests(
std::u16string(), base::NullCallback(), ISOLATED_WORLD_ID_GLOBAL);
script = "window.onbeforeunload=function(e){ return 'x' };";
EXPECT_TRUE(ExecJs(wc, script));
test_delegate.WillWaitForDialog();
EXPECT_TRUE(NavigateToURL(shell(), url));
test_delegate.Wait();
EXPECT_FALSE(wc->IsFullscreen());
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
DialogsFromJavaScriptEndFullscreenEvenInInnerWC) {
WebContentsImpl* top_contents =
static_cast<WebContentsImpl*>(shell()->web_contents());
TestWCDelegateForDialogsAndFullscreen top_test_delegate(top_contents);
GURL url("about:blank");
EXPECT_TRUE(NavigateToURL(shell(), url));
FrameTreeNode* root = top_contents->GetPrimaryFrameTree().root();
ASSERT_EQ(0U, root->child_count());
std::string script =
"var iframe = document.createElement('iframe');"
"document.body.appendChild(iframe);";
EXPECT_TRUE(ExecJs(root->current_frame_host(), script));
EXPECT_TRUE(WaitForLoadStop(shell()->web_contents()));
ASSERT_EQ(1U, root->child_count());
RenderFrameHost* frame = root->child_at(0)->current_frame_host();
ASSERT_NE(nullptr, frame);
WebContentsImpl* inner_contents =
static_cast<WebContentsImpl*>(CreateAndAttachInnerContents(frame));
TestWCDelegateForDialogsAndFullscreen inner_test_delegate(inner_contents);
// A dialog from the inner WebContents should make the outer contents lose
// fullscreen.
top_contents->EnterFullscreenMode(top_contents->GetPrimaryMainFrame(), {});
EXPECT_TRUE(top_contents->IsFullscreen());
script = "alert('hi')";
inner_test_delegate.WillWaitForDialog();
EXPECT_TRUE(ExecJs(inner_contents, script));
inner_test_delegate.Wait();
EXPECT_FALSE(top_contents->IsFullscreen());
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest, FileChooserEndsFullscreen) {
WebContentsImpl* wc = static_cast<WebContentsImpl*>(shell()->web_contents());
TestWCDelegateForDialogsAndFullscreen test_delegate(wc);
GURL url("about:blank");
EXPECT_TRUE(NavigateToURL(shell(), url));
wc->EnterFullscreenMode(wc->GetPrimaryMainFrame(), {});
EXPECT_TRUE(wc->IsFullscreen());
auto [chooser, remote] =
FileChooserImpl::CreateForTesting(wc->GetPrimaryMainFrame());
wc->RunFileChooser(chooser->GetWeakPtr(), wc->GetPrimaryMainFrame(),
base::MakeRefCounted<MockFileSelectListener>(),
blink::mojom::FileChooserParams());
EXPECT_FALSE(wc->IsFullscreen());
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
PopupsFromJavaScriptEndFullscreen) {
WebContentsImpl* wc = static_cast<WebContentsImpl*>(shell()->web_contents());
TestWCDelegateForDialogsAndFullscreen test_delegate(wc);
GURL url("about:blank");
EXPECT_TRUE(NavigateToURL(shell(), url));
// popup
wc->EnterFullscreenMode(wc->GetPrimaryMainFrame(), {});
EXPECT_TRUE(wc->IsFullscreen());
std::string script = "window.open('', '', 'width=200,height=100')";
test_delegate.WillWaitForNewContents();
EXPECT_TRUE(ExecJs(wc, script));
test_delegate.Wait();
EXPECT_FALSE(wc->IsFullscreen());
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
PopupsFromJavaScriptDoNotEndFullscreenWithinTab) {
WebContentsImpl* wc = static_cast<WebContentsImpl*>(shell()->web_contents());
TestWCDelegateForDialogsAndFullscreen test_delegate(wc);
GURL url("about:blank");
EXPECT_TRUE(NavigateToURL(shell(), url));
// capture
base::ScopedClosureRunner capture_closure =
wc->IncrementCapturerCount(gfx::Size(), /*stay_hidden=*/false,
/*stay_awake=*/false, /*is_activity=*/true);
EXPECT_TRUE(wc->IsBeingVisiblyCaptured());
// popup
wc->EnterFullscreenMode(wc->GetPrimaryMainFrame(), {});
EXPECT_TRUE(wc->IsFullscreen());
EXPECT_EQ(wc->GetDelegate()->GetFullscreenState(wc).target_mode,
FullscreenMode::kPseudoContent);
std::string script = "window.open('', '', 'width=200,height=100')";
test_delegate.WillWaitForNewContents();
EXPECT_TRUE(ExecJs(wc, script));
test_delegate.Wait();
EXPECT_TRUE(wc->IsFullscreen());
capture_closure.RunAndReset();
}
// Tests that if a popup is opened, a WebContents *up* the opener chain is
// kicked out of fullscreen.
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
PopupsOfPopupsFromJavaScriptEndFullscreen) {
WebContentsImpl* wc = static_cast<WebContentsImpl*>(shell()->web_contents());
TestWCDelegateForDialogsAndFullscreen test_delegate(wc);
GURL url("about:blank");
EXPECT_TRUE(NavigateToURL(shell(), url));
// Make a popup.
std::string popup_script = "window.open('', '', 'width=200,height=100')";
test_delegate.WillWaitForNewContents();
EXPECT_TRUE(ExecJs(wc, popup_script));
test_delegate.Wait();
WebContentsImpl* popup =
static_cast<WebContentsImpl*>(test_delegate.last_popup());
// Put the original page into fullscreen.
wc->EnterFullscreenMode(wc->GetPrimaryMainFrame(), {});
EXPECT_TRUE(wc->IsFullscreen());
// Have the popup open a popup.
TestWCDelegateForDialogsAndFullscreen popup_test_delegate(popup);
popup_test_delegate.WillWaitForNewContents();
EXPECT_TRUE(ExecJs(popup, popup_script));
popup_test_delegate.Wait();
// Ensure the original page, being in the opener chain, loses fullscreen.
EXPECT_FALSE(wc->IsFullscreen());
}
// Tests that if a popup is opened, a WebContents *down* the opener chain is
// kicked out of fullscreen.
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
PopupsFromJavaScriptEndFullscreenDownstream) {
WebContentsImpl* wc = static_cast<WebContentsImpl*>(shell()->web_contents());
TestWCDelegateForDialogsAndFullscreen test_delegate(wc);
GURL url("about:blank");
EXPECT_TRUE(NavigateToURL(shell(), url));
// Make a popup.
std::string popup_script = "window.open('', '', 'width=200,height=100')";
test_delegate.WillWaitForNewContents();
EXPECT_TRUE(ExecJs(wc, popup_script));
test_delegate.Wait();
WebContentsImpl* popup =
static_cast<WebContentsImpl*>(test_delegate.last_popup());
// Put the popup into fullscreen.
TestWCDelegateForDialogsAndFullscreen popup_test_delegate(popup);
popup->EnterFullscreenMode(popup->GetPrimaryMainFrame(), {});
EXPECT_TRUE(popup->IsFullscreen());
// Have the original page open a new popup.
test_delegate.WillWaitForNewContents();
EXPECT_TRUE(ExecJs(wc, popup_script));
test_delegate.Wait();
// Ensure the popup, being downstream from the opener, loses fullscreen.
EXPECT_FALSE(popup->IsFullscreen());
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
FocusFromJavaScriptEndsFullscreen) {
WebContentsImpl* wc = static_cast<WebContentsImpl*>(shell()->web_contents());
TestWCDelegateForDialogsAndFullscreen test_delegate(wc);
GURL url("about:blank");
EXPECT_TRUE(NavigateToURL(shell(), url));
// Make a popup.
std::string script =
"window.FocusFromJavaScriptEndsFullscreen = "
"window.open('', '', 'width=200,height=100')";
test_delegate.WillWaitForNewContents();
EXPECT_TRUE(ExecJs(wc, script));
test_delegate.Wait();
// Put the main contents into fullscreen ...
wc->EnterFullscreenMode(wc->GetPrimaryMainFrame(), {});
EXPECT_TRUE(wc->IsFullscreen());
// ... and ensure that a call to window.focus() from it causes loss of
// ... fullscreen.
script = "window.FocusFromJavaScriptEndsFullscreen.focus()";
test_delegate.WillWaitForFullscreenExit();
EXPECT_TRUE(ExecJs(wc, script));
test_delegate.Wait();
EXPECT_FALSE(wc->IsFullscreen());
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
FileChooserBlockedFromHiddenWebContents) {
ASSERT_TRUE(embedded_test_server()->Start());
shell()->set_hold_file_chooser();
EXPECT_TRUE(NavigateToURL(shell(), GURL("about:blank")));
WebContentsImpl* wc = static_cast<WebContentsImpl*>(shell()->web_contents());
wc->WasHidden();
EXPECT_EQ(shell()->web_contents()->GetVisibility(), Visibility::HIDDEN);
auto [chooser, remote] =
FileChooserImpl::CreateForTesting(wc->GetPrimaryMainFrame());
auto file_select_listener = base::MakeRefCounted<MockFileSelectListener>();
wc->RunFileChooser(chooser->GetWeakPtr(), wc->GetPrimaryMainFrame(),
file_select_listener, blink::mojom::FileChooserParams());
EXPECT_TRUE(file_select_listener->cancelled());
EXPECT_EQ(shell()->run_file_chooser_count(), 0u);
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
EnumerateDirectoryBlockedFromHiddenWebContents) {
ASSERT_TRUE(embedded_test_server()->Start());
shell()->set_hold_file_chooser();
EXPECT_TRUE(NavigateToURL(shell(), GURL("about:blank")));
WebContentsImpl* wc = static_cast<WebContentsImpl*>(shell()->web_contents());
wc->WasHidden();
EXPECT_EQ(shell()->web_contents()->GetVisibility(), Visibility::HIDDEN);
auto [chooser, remote] =
FileChooserImpl::CreateForTesting(wc->GetPrimaryMainFrame());
auto file_select_listener = base::MakeRefCounted<MockFileSelectListener>();
wc->EnumerateDirectory(chooser->GetWeakPtr(), wc->GetPrimaryMainFrame(),
file_select_listener, base::FilePath());
EXPECT_TRUE(file_select_listener->cancelled());
EXPECT_EQ(shell()->run_file_chooser_count(), 0u);
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
NewWindowBlockedForActiveFileChooser) {
ASSERT_TRUE(embedded_test_server()->Start());
shell()->set_hold_file_chooser();
GURL url = embedded_test_server()->GetURL("/click-noreferrer-links.html");
EXPECT_TRUE(NavigateToURL(shell(), url));
WebContentsImpl* wc = static_cast<WebContentsImpl*>(shell()->web_contents());
auto [chooser, remote] =
FileChooserImpl::CreateForTesting(wc->GetPrimaryMainFrame());
auto file_select_listener = base::MakeRefCounted<MockFileSelectListener>();
wc->RunFileChooser(chooser->GetWeakPtr(), wc->GetPrimaryMainFrame(),
file_select_listener, blink::mojom::FileChooserParams());
EXPECT_FALSE(file_select_listener->cancelled());
// Open a new, named window.
WebContentsConsoleObserver console_observer(shell()->web_contents());
console_observer.SetPattern(
"window.open blocked due to active file chooser.");
EXPECT_TRUE(ExecJs(shell(), "window.open('about:blank','new_window');"));
ASSERT_TRUE(console_observer.Wait());
EXPECT_EQ(url, shell()->web_contents()->GetLastCommittedURL());
EXPECT_EQ(1u, Shell::windows().size());
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
FrameDetachInCopyDoesNotCrash) {
ASSERT_TRUE(embedded_test_server()->Start());
EXPECT_TRUE(NavigateToURL(
shell(),
embedded_test_server()->GetURL("a.com", "/detach_frame_in_copy.html")));
WebContentsImpl* web_contents =
static_cast<WebContentsImpl*>(shell()->web_contents());
// Focus the child frame before sending it a copy command: the child frame
// will detach itself upon getting a 'copy' event.
ASSERT_TRUE(ExecJs(web_contents, "window[0].focus();"));
FrameTreeNode* root = web_contents->GetPrimaryFrameTree().root();
ASSERT_EQ(root->child_at(0),
web_contents->GetPrimaryFrameTree().GetFocusedFrame());
shell()->web_contents()->Copy();
TitleWatcher title_watcher(web_contents, u"done");
std::u16string title = title_watcher.WaitAndGetTitle();
ASSERT_EQ(title, u"done");
}
class UpdateTargetURLWaiter : public WebContentsDelegate {
public:
explicit UpdateTargetURLWaiter(WebContents* web_contents) {
web_contents->SetDelegate(this);
}
UpdateTargetURLWaiter(const UpdateTargetURLWaiter&) = delete;
UpdateTargetURLWaiter& operator=(const UpdateTargetURLWaiter&) = delete;
const GURL& WaitForUpdatedTargetURL() {
if (updated_target_url_.has_value())
return updated_target_url_.value();
runner_ = new MessageLoopRunner();
runner_->Run();
return updated_target_url_.value();
}
private:
void UpdateTargetURL(WebContents* source, const GURL& url) override {
updated_target_url_ = url;
if (runner_.get())
runner_->QuitClosure().Run();
}
std::optional<GURL> updated_target_url_;
scoped_refptr<MessageLoopRunner> runner_;
};
// Verifies that focusing a link in a cross-site frame will correctly tell
// WebContentsDelegate to show a link status bubble. This is a regression test
// for https://crbug.com/807776.
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest, UpdateTargetURL) {
// Navigate to a test page.
ASSERT_TRUE(embedded_test_server()->Start());
WebContentsImpl* web_contents =
static_cast<WebContentsImpl*>(shell()->web_contents());
GURL url = embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(b)");
EXPECT_TRUE(NavigateToURL(shell(), url));
FrameTreeNode* subframe =
web_contents->GetPrimaryFrameTree().root()->child_at(0);
GURL subframe_url =
embedded_test_server()->GetURL("b.com", "/simple_links.html");
EXPECT_TRUE(NavigateToURLFromRenderer(subframe, subframe_url));
// Focusing the link should fire the UpdateTargetURL notification.
UpdateTargetURLWaiter target_url_waiter(web_contents);
EXPECT_TRUE(
ExecJs(subframe, "document.getElementById('cross_site_link').focus();"));
EXPECT_EQ(GURL("http://foo.com/title2.html"),
target_url_waiter.WaitForUpdatedTargetURL());
}
namespace {
class LoadStateWaiter : public WebContentsDelegate {
public:
explicit LoadStateWaiter(content::WebContents* contents)
: web_contents_(contents) {
contents->SetDelegate(this);
}
~LoadStateWaiter() override = default;
LoadStateWaiter(const LoadStateWaiter&) = delete;
LoadStateWaiter& operator=(const LoadStateWaiter&) = delete;
// Waits until the WebContents changes its LoadStateHost to |host|.
void Wait(net::LoadState load_state, const std::u16string& host) {
waiting_host_ = host;
waiting_state_ = load_state;
if (!LoadStateMatches(web_contents_)) {
base::RunLoop run_loop;
quit_closure_ = run_loop.QuitClosure();
run_loop.Run();
DCHECK(LoadStateMatches(web_contents_));
}
}
// WebContentsDelegate:
void NavigationStateChanged(WebContents* source,
InvalidateTypes changed_flags) override {
if (!quit_closure_)
return;
if (!(changed_flags & INVALIDATE_TYPE_LOAD))
return;
if (LoadStateMatches(source))
std::move(quit_closure_).Run();
}
private:
bool LoadStateMatches(content::WebContents* contents) {
DCHECK(contents == web_contents_);
return waiting_host_ == contents->GetLoadStateHost() &&
waiting_state_ == contents->GetLoadState().state;
}
base::OnceClosure quit_closure_;
raw_ptr<content::WebContents> web_contents_ = nullptr;
std::u16string waiting_host_;
net::LoadState waiting_state_;
};
} // namespace
// TODO(csharrison,mmenke): Beef up testing of LoadState a little. In
// particular, check upload progress and check the LoadState param.
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest, DISABLED_UpdateLoadState) {
std::u16string a_host = url_formatter::IDNToUnicode("a.com");
std::u16string b_host = url_formatter::IDNToUnicode("b.com");
std::u16string paused_host = url_formatter::IDNToUnicode("paused.com");
// Controlled responses for image requests made in the test. They will
// alternate being the "most interesting" for the purposes of notifying the
// WebContents.
auto a_response =
std::make_unique<net::test_server::ControllableHttpResponse>(
embedded_test_server(), "/a_img");
auto b_response =
std::make_unique<net::test_server::ControllableHttpResponse>(
embedded_test_server(), "/b_img");
LoadStateWaiter waiter(shell()->web_contents());
ASSERT_TRUE(embedded_test_server()->Start());
EXPECT_TRUE(NavigateToURL(
shell(), embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(b)")));
WebContentsImpl* web_contents =
static_cast<WebContentsImpl*>(shell()->web_contents());
FrameTreeNode* a_frame = web_contents->GetPrimaryFrameTree().root();
FrameTreeNode* b_frame = a_frame->child_at(0);
// Start loading the respective resources in each frame.
auto load_resource = [](FrameTreeNode* frame, const std::string url) {
const char kLoadResourceScript[] = R"(
var img = new Image();
img.src = '%s';
document.body.appendChild(img);
)";
std::string script = base::StringPrintf(kLoadResourceScript, url.c_str());
EXPECT_TRUE(ExecJs(frame, script));
};
// There should be no outgoing requests, so the load state should be empty.
waiter.Wait(net::LOAD_STATE_IDLE, std::u16string());
// The |frame_pauser| pauses the navigation after every step. It will only
// finish by calling WaitForNavigationFinished or ResumeNavigation.
GURL paused_url(embedded_test_server()->GetURL("paused.com", "/title1.html"));
TestNavigationManager frame_pauser(web_contents, paused_url);
const char kLoadFrameScript[] = R"(
var frame = document.createElement('iframe');
frame.src = "%s";
document.body.appendChild(frame);
)";
EXPECT_TRUE(
ExecJs(web_contents,
base::StringPrintf(kLoadFrameScript, paused_url.spec().c_str())));
// Wait for the response to be ready, but never finish it.
EXPECT_TRUE(frame_pauser.WaitForResponse());
EXPECT_FALSE(frame_pauser.was_successful());
// Note: the pausing only works for the non-network service path because of
// http://crbug.com/791049.
waiter.Wait(net::LOAD_STATE_IDLE, std::u16string());
load_resource(a_frame, "/a_img");
a_response->WaitForRequest();
waiter.Wait(net::LOAD_STATE_WAITING_FOR_RESPONSE, a_host);
// Start loading b_img and have it pass a_img by providing one byte of data.
load_resource(b_frame, "/b_img");
b_response->WaitForRequest();
const char kPartialResponse[] = "HTTP/1.1 200 OK\r\n\r\nx";
b_response->Send(kPartialResponse);
waiter.Wait(net::LOAD_STATE_READING_RESPONSE, b_host);
// Finish b_img and expect that a_img is back to being most interesting.
b_response->Done();
waiter.Wait(net::LOAD_STATE_WAITING_FOR_RESPONSE, a_host);
// Advance and finish a_img.
a_response->Send(kPartialResponse);
waiter.Wait(net::LOAD_STATE_READING_RESPONSE, a_host);
a_response->Done();
}
namespace {
// Watches if all title changes in the WebContents match the expected title
// changes, in the order given.
class TitleChecker : public WebContentsDelegate {
public:
explicit TitleChecker(content::WebContents* contents,
std::queue<std::u16string> expected_title_changes)
: web_contents_(contents),
expected_title_changes_(expected_title_changes) {
contents->SetDelegate(this);
}
~TitleChecker() override = default;
TitleChecker(const LoadStateWaiter&) = delete;
TitleChecker& operator=(const TitleChecker&) = delete;
// Waits until the WebContents has gone through all the titles in
// `expected_title_changes_`.
void WaitForAllTitles() {
if (expected_title_changes_.empty())
return;
base::RunLoop run_loop;
quit_closure_ = run_loop.QuitClosure();
run_loop.Run();
}
// WebContentsDelegate:
void NavigationStateChanged(WebContents* source,
InvalidateTypes changed_flags) override {
// We only care about title changes.
if (!(changed_flags & INVALIDATE_TYPE_TITLE))
return;
// See if this title change is the next thing on the queue.
DCHECK(!expected_title_changes_.empty());
DCHECK_EQ(expected_title_changes_.front(), source->GetTitle());
expected_title_changes_.pop();
// If `expected_title_changes_` is empty, we have gone through all the
// expected title changes.
if (quit_closure_ && expected_title_changes_.empty())
std::move(quit_closure_).Run();
}
private:
base::OnceClosure quit_closure_;
raw_ptr<content::WebContents> web_contents_ = nullptr;
std::queue<std::u16string> expected_title_changes_;
};
} // namespace
// Tests that restoring a NavigationEntry on a new tab restores the title
// correctly after the page is parsed again, and that the empty title update
// from the initial empty document created by the new tab won't affect anything
// (won't change the restored NavigationEntry's title or the WebContents' title)
// as the tab is not on the initial NavigationEntry.
// Regression test for https://crbug.com/1275392.
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest, TitleUpdateOnRestore) {
ASSERT_TRUE(embedded_test_server()->Start());
GURL main_url = embedded_test_server()->GetURL("foo.com", "/title2.html");
std::u16string main_title = u"Title Of Awesomeness";
std::u16string main_url_as_title = url_formatter::FormatUrl(main_url);
WebContentsImpl* web_contents =
static_cast<WebContentsImpl*>(shell()->web_contents());
// Before any navigation is initiated, the WebContents starts with an empty
// title.
EXPECT_EQ(u"", web_contents->GetTitle());
// Set up all the expected title change in the original WebContents.
std::queue<std::u16string> original_expected_title_changes;
// The first "title change" is not an actual title change, it's triggered by a
// INVALIDATE_TYPE_ALL NotifyNavigationStateChanged call from
// NavigationControllerImpl::DiscardNonCommittedEntries().
original_expected_title_changes.push(u"");
// When the navigation to `main_url` commits, the document title is not set
// yet, so we use the URL as the title.
original_expected_title_changes.push(main_url_as_title);
// Finally, after the committed `main_url` document finished parsing, the
// final title is set.
original_expected_title_changes.push(main_title);
TitleChecker original_web_contents_title_checker(
web_contents, original_expected_title_changes);
// Navigate to the page with the expected title.
ASSERT_TRUE(NavigateToURL(shell(), main_url));
original_web_contents_title_checker.WaitForAllTitles();
EXPECT_EQ(main_title, web_contents->GetTitle());
// Create a NavigationEntry with the same PageState and title as the last
// committed entry. We are simulating the condition where the restore has
// started, but the empty title update from the initial empty document created
// when the new tab is created came later. When this happens, we already have
// the restored entry as the "last committed entry" and uses the entry's title
// (or URL) as the WebContents title. The initial empty document's title
// update is not for the restored entry, so we should not use it to overwrite
// the title of the restored entry and the WebContents.
NavigationControllerImpl& controller = web_contents->GetController();
std::unique_ptr<NavigationEntryImpl> restored_entry =
NavigationEntryImpl::FromNavigationEntry(
NavigationController::CreateNavigationEntry(
main_url, Referrer(), /* initiator_origin= */ std::nullopt,
/* initiator_base_url= */ std::nullopt,
ui::PAGE_TRANSITION_RELOAD, false, std::string(),
controller.GetBrowserContext(),
nullptr /* blob_url_loader_factory */));
NavigationEntryRestoreContextImpl context;
restored_entry->SetPageState(
controller.GetLastCommittedEntry()->GetPageState(), &context);
restored_entry->SetTitle(controller.GetLastCommittedEntry()->GetTitle());
// Create a new tab.
Shell* new_shell = Shell::CreateNewWindow(controller.GetBrowserContext(),
GURL(), nullptr, gfx::Size());
WebContentsImpl* new_contents =
static_cast<WebContentsImpl*>(new_shell->web_contents());
// Before the restore is initiated, the WebContents starts with an empty
// title.
EXPECT_EQ(u"", new_contents->GetTitle());
// Set up all the expected title change in the new WebContents.
std::queue<std::u16string> new_expected_title_changes;
// Similar to the original WebContents' case above, the first "title change"
// is not an actual title change, but instead triggered by a
// INVALIDATE_TYPE_ALL NotifyNavigationStateChanged call from
// NavigationControllerImpl::DiscardNonCommittedEntries(). For the
// original WebContents' case we expect an empty title because there's no
// entries and GetNavigationEntryForTitle() returns null. However, in the new
// WebContents we already have the restored entry, so we will use the entry's
// title.
new_expected_title_changes.push(main_title);
// When the navigation to `main_url` commits, we also got another "update"
// that is not really a title change, but it is triggered by a
// INVALIDATE_TYPE_ALL NotifyNavigationStateChanged call from
// NavigationControllerImpl::NotifyNavigationEntryCommitted().
new_expected_title_changes.push(main_title);
// Finally, after the committed `main_url` document finished parsing again,
// the final title is set, but since the title didn't actually change, no
// "title change" call was dispatched.
TitleChecker new_web_contents_title_checker(new_contents,
new_expected_title_changes);
// Restore the new entry in the new tab.
std::vector<std::unique_ptr<NavigationEntry>> entries;
entries.push_back(std::move(restored_entry));
FrameTreeNode* new_root = new_contents->GetPrimaryFrameTree().root();
NavigationControllerImpl& new_controller = new_contents->GetController();
new_controller.Restore(entries.size() - 1, RestoreType::kRestored, &entries);
ASSERT_EQ(0u, entries.size());
// Load the restored entry.
{
TestNavigationObserver restore_observer(new_contents);
new_controller.LoadIfNecessary();
restore_observer.Wait();
}
// Test that the URL and title are restored correctly.
new_web_contents_title_checker.WaitForAllTitles();
EXPECT_EQ(main_url, new_root->current_url());
EXPECT_EQ(main_title, new_contents->GetTitle());
}
namespace {
class OutgoingSetRendererPrefsMojoWatcher {
public:
explicit OutgoingSetRendererPrefsMojoWatcher(RenderViewHostImpl* rvh)
: rvh_(rvh), outgoing_message_seen_(false) {
rvh_->SetWillSendRendererPreferencesCallbackForTesting(base::BindRepeating(
&OutgoingSetRendererPrefsMojoWatcher::OnRendererPreferencesSent,
base::Unretained(this)));
}
~OutgoingSetRendererPrefsMojoWatcher() {
rvh_->SetWillSendRendererPreferencesCallbackForTesting(
base::RepeatingCallback<void(const blink::RendererPreferences&)>());
}
void WaitForIPC() {
if (outgoing_message_seen_)
return;
run_loop_ = std::make_unique<base::RunLoop>();
run_loop_->Run();
run_loop_.reset();
}
const blink::RendererPreferences& renderer_preferences() const {
return renderer_preferences_;
}
private:
void OnRendererPreferencesSent(
const blink::RendererPreferences& preferences) {
outgoing_message_seen_ = true;
renderer_preferences_ = preferences;
if (run_loop_)
run_loop_->Quit();
}
raw_ptr<RenderViewHostImpl> rvh_;
bool outgoing_message_seen_;
std::unique_ptr<base::RunLoop> run_loop_;
blink::RendererPreferences renderer_preferences_;
};
} // namespace
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest, SyncRendererPrefs) {
ASSERT_TRUE(embedded_test_server()->Start());
WebContentsImpl* web_contents =
static_cast<WebContentsImpl*>(shell()->web_contents());
// Navigate to a site with two iframes in different origins.
GURL url = embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(b,c)");
EXPECT_TRUE(NavigateToURL(shell(), url));
// Retrieve an arbitrary renderer preference.
blink::RendererPreferences* renderer_preferences =
web_contents->GetMutableRendererPrefs();
const bool use_custom_colors_old = renderer_preferences->use_custom_colors;
// Retrieve all unique render view hosts.
std::vector<RenderViewHostImpl*> render_view_hosts;
for (FrameTreeNode* frame_tree_node :
web_contents->GetPrimaryFrameTree().Nodes()) {
RenderViewHostImpl* render_view_host = static_cast<RenderViewHostImpl*>(
frame_tree_node->current_frame_host()->GetRenderViewHost());
ASSERT_NE(nullptr, render_view_host);
DLOG(INFO) << "render_view_host=" << render_view_host;
// Multiple frame hosts can be associated to the same RenderViewHost.
if (!base::Contains(render_view_hosts, render_view_host)) {
render_view_hosts.push_back(render_view_host);
}
}
// Set up watchers for SetRendererPreferences message being sent from unique
// render process hosts.
std::vector<std::unique_ptr<OutgoingSetRendererPrefsMojoWatcher>>
mojo_watchers;
for (auto* render_view_host : render_view_hosts) {
mojo_watchers.push_back(
std::make_unique<OutgoingSetRendererPrefsMojoWatcher>(
render_view_host));
// Make sure the Mojo watchers have the same default value for the arbitrary
// preference.
EXPECT_EQ(use_custom_colors_old,
mojo_watchers.back()->renderer_preferences().use_custom_colors);
}
// Change the arbitrary renderer preference.
const bool use_custom_colors_new = !use_custom_colors_old;
renderer_preferences->use_custom_colors = use_custom_colors_new;
web_contents->SyncRendererPrefs();
// Ensure Mojo messages are sent to each frame.
for (auto& mojo_watcher : mojo_watchers) {
mojo_watcher->WaitForIPC();
EXPECT_EQ(use_custom_colors_new,
mojo_watcher->renderer_preferences().use_custom_colors);
}
renderer_preferences->use_custom_colors = use_custom_colors_old;
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest, SetPageFrozen) {
EXPECT_TRUE(embedded_test_server()->Start());
GURL test_url = embedded_test_server()->GetURL("/pause_schedule_task.html");
EXPECT_TRUE(NavigateToURL(shell(), test_url));
EXPECT_TRUE(WaitForLoadStop(shell()->web_contents()));
int text_length;
while (true) {
text_length =
EvalJs(shell(), "document.getElementById('textfield').value.length")
.ExtractInt();
// Wait until |text_length| exceed 0.
if (text_length > 0)
break;
}
// Freeze the blink page.
shell()->web_contents()->WasHidden();
shell()->web_contents()->SetPageFrozen(true);
// Make the javascript work.
for (int i = 0; i < 10; i++) {
text_length =
EvalJs(shell(), "document.getElementById('textfield').value.length")
.ExtractInt();
}
// Check if |next_text_length| is equal to |text_length|.
int next_text_length =
EvalJs(shell(), "document.getElementById('textfield').value.length")
.ExtractInt();
EXPECT_EQ(text_length, next_text_length);
// Wake the frozen page up.
shell()->web_contents()->WasHidden();
shell()->web_contents()->SetPageFrozen(false);
// Wait for an amount of time in order to give the javascript time to
// work again. If the javascript doesn't work again, the test will fail due to
// the time out.
while (true) {
next_text_length =
EvalJs(shell(), "document.getElementById('textfield').value.length")
.ExtractInt();
if (next_text_length > text_length)
break;
}
// Check if |next_text_length| exceeds |text_length| because the blink
// schedule tasks have resumed.
next_text_length =
EvalJs(shell(), "document.getElementById('textfield').value.length")
.ExtractInt();
EXPECT_GT(next_text_length, text_length);
}
// Checks that UnfreezableFrameMsg IPCs are executed even when the page is
// frozen.
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest, FrozenAndUnfrozenIPC) {
EXPECT_TRUE(embedded_test_server()->Start());
GURL url_a(embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(b,c)"));
EXPECT_TRUE(NavigateToURL(shell(), url_a));
EXPECT_TRUE(WaitForLoadStop(shell()->web_contents()));
RenderFrameHostImpl* rfh_a =
static_cast<WebContentsImpl*>(shell()->web_contents())
->GetPrimaryFrameTree()
.root()
->current_frame_host();
RenderFrameHostImpl* rfh_b = rfh_a->child_at(0)->current_frame_host();
RenderFrameHostImpl* rfh_c = rfh_a->child_at(1)->current_frame_host();
RenderFrameDeletedObserver delete_rfh_b(rfh_b);
RenderFrameDeletedObserver delete_rfh_c(rfh_c);
// Delete an iframe when the page is active(not frozen), which should succeed.
rfh_b->GetMojomFrameInRenderer()->Delete(
mojom::FrameDeleteIntention::kNotMainFrame);
delete_rfh_b.WaitUntilDeleted();
EXPECT_TRUE(delete_rfh_b.deleted());
EXPECT_FALSE(delete_rfh_c.deleted());
// Freeze the blink page.
shell()->web_contents()->WasHidden();
shell()->web_contents()->SetPageFrozen(true);
// Try to delete an iframe, and succeeds because the message is unfreezable.
rfh_c->GetMojomFrameInRenderer()->Delete(
mojom::FrameDeleteIntention::kNotMainFrame);
delete_rfh_c.WaitUntilDeleted();
EXPECT_TRUE(delete_rfh_c.deleted());
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
SuppressedPopupWindowBrowserNavResumeLoad) {
// This test verifies a suppressed pop up that requires navigation from
// browser side works with a delegate that delays navigations of pop ups.
base::FilePath test_data_dir;
CHECK(base::PathService::Get(base::DIR_SRC_TEST_DATA_ROOT, &test_data_dir));
base::FilePath simple_links_path =
test_data_dir.Append(GetTestDataFilePath())
.Append(FILE_PATH_LITERAL("simple_links.html"));
GURL url("file://" + simple_links_path.AsUTF8Unsafe());
shell()->set_delay_popup_contents_delegate_for_testing(true);
EXPECT_TRUE(NavigateToURL(shell(), url));
Shell* new_shell = nullptr;
WebContents* new_contents = nullptr;
{
ShellAddedObserver new_shell_observer;
EXPECT_TRUE(ExecJs(shell(), "clickLinkToSelfNoOpener();"));
new_shell = new_shell_observer.GetShell();
new_contents = new_shell->web_contents();
// Delaying popup holds the initial load of |url|.
EXPECT_TRUE(WaitForLoadStop(new_contents));
EXPECT_TRUE(new_contents->GetController()
.GetLastCommittedEntry()
->IsInitialEntry());
EXPECT_NE(url, new_contents->GetLastCommittedURL());
}
EXPECT_FALSE(new_contents->GetDelegate());
new_contents->SetDelegate(new_shell);
EXPECT_TRUE(
static_cast<WebContentsImpl*>(new_contents)->delayed_load_url_params_);
new_contents->ResumeLoadingCreatedWebContents();
EXPECT_TRUE(WaitForLoadStop(new_contents));
EXPECT_EQ(url, new_contents->GetLastCommittedURL());
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
PopupWindowBrowserNavResumeLoad) {
// This test verifies a pop up that requires navigation from browser side
// works with a delegate that delays navigations of pop ups.
// Create a file: scheme non-suppressed pop up from a file: scheme page will
// be blocked and wait for the renderer to signal.
base::FilePath test_data_dir;
CHECK(base::PathService::Get(base::DIR_SRC_TEST_DATA_ROOT, &test_data_dir));
base::FilePath simple_links_path =
test_data_dir.Append(GetTestDataFilePath())
.Append(FILE_PATH_LITERAL("simple_links.html"));
GURL url("file://" + simple_links_path.AsUTF8Unsafe());
shell()->set_delay_popup_contents_delegate_for_testing(true);
EXPECT_TRUE(NavigateToURL(shell(), url));
Shell* new_shell = nullptr;
WebContents* new_contents = nullptr;
{
ShellAddedObserver new_shell_observer;
EXPECT_TRUE(ExecJs(shell(), "clickLinkToSelf();"));
new_shell = new_shell_observer.GetShell();
new_contents = new_shell->web_contents();
// Delaying popup holds the initial load of |url|.
EXPECT_TRUE(WaitForLoadStop(new_contents));
EXPECT_TRUE(new_contents->GetController()
.GetLastCommittedEntry()
->IsInitialEntry());
EXPECT_NE(url, new_contents->GetLastCommittedURL());
}
EXPECT_FALSE(new_contents->GetDelegate());
new_contents->SetDelegate(new_shell);
EXPECT_FALSE(
static_cast<WebContentsImpl*>(new_contents)->delayed_load_url_params_);
EXPECT_FALSE(
static_cast<WebContentsImpl*>(new_contents)->delayed_open_url_params_);
EXPECT_TRUE(static_cast<WebContentsImpl*>(new_contents)->is_resume_pending_);
new_contents->ResumeLoadingCreatedWebContents();
EXPECT_TRUE(WaitForLoadStop(new_contents));
EXPECT_EQ(url, new_contents->GetLastCommittedURL());
}
namespace {
class FullscreenWebContentsObserver : public WebContentsObserver {
public:
FullscreenWebContentsObserver(WebContents* web_contents,
RenderFrameHost* wanted_rfh)
: WebContentsObserver(web_contents), wanted_rfh_(wanted_rfh) {}
FullscreenWebContentsObserver(const FullscreenWebContentsObserver&) = delete;
FullscreenWebContentsObserver& operator=(
const FullscreenWebContentsObserver&) = delete;
// WebContentsObserver override.
void DidAcquireFullscreen(RenderFrameHost* rfh) override {
EXPECT_EQ(wanted_rfh_, rfh);
EXPECT_FALSE(found_value_);
if (rfh == wanted_rfh_) {
found_value_ = true;
run_loop_.Quit();
}
}
void Wait() {
if (!found_value_)
run_loop_.Run();
}
private:
base::RunLoop run_loop_;
bool found_value_ = false;
raw_ptr<RenderFrameHost, AcrossTasksDanglingUntriaged> wanted_rfh_;
};
} // namespace
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest, NotifyFullscreenAcquired) {
ASSERT_TRUE(embedded_test_server()->Start());
WebContentsImpl* web_contents =
static_cast<WebContentsImpl*>(shell()->web_contents());
TestWCDelegateForDialogsAndFullscreen test_delegate(web_contents);
GURL url = embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(b{allowfullscreen})");
EXPECT_TRUE(NavigateToURL(shell(), url));
RenderFrameHostImpl* main_frame = web_contents->GetPrimaryMainFrame();
RenderFrameHostImpl* child_frame =
static_cast<RenderFrameHostImpl*>(ChildFrameAt(main_frame, 0));
std::set<raw_ptr<RenderFrameHostImpl, SetExperimental>> fullscreen_frames;
EXPECT_EQ(fullscreen_frames, web_contents->fullscreen_frames_);
EXPECT_FALSE(IsInFullscreen());
// Make the top page fullscreen.
{
FullscreenWebContentsObserver observer(web_contents, main_frame);
EXPECT_TRUE(ExecJs(main_frame, "document.body.webkitRequestFullscreen();"));
observer.Wait();
}
fullscreen_frames.insert(main_frame);
EXPECT_EQ(fullscreen_frames, web_contents->fullscreen_frames_);
EXPECT_EQ(main_frame->GetGlobalId(),
web_contents->current_fullscreen_frame_id_);
// Make the child frame fullscreen.
{
FullscreenWebContentsObserver observer(web_contents, child_frame);
EXPECT_TRUE(
ExecJs(child_frame, "document.body.webkitRequestFullscreen();"));
observer.Wait();
}
fullscreen_frames.insert(child_frame);
EXPECT_EQ(fullscreen_frames, web_contents->fullscreen_frames_);
EXPECT_EQ(child_frame->GetGlobalId(),
web_contents->current_fullscreen_frame_id_);
// Exit fullscreen on the child frame.
// This will not work with --site-per-process until crbug.com/617369
// is fixed.
if (!SiteIsolationPolicy::UseDedicatedProcessesForAllSites()) {
{
FullscreenWebContentsObserver observer(web_contents, main_frame);
EXPECT_TRUE(ExecJs(child_frame, "document.webkitExitFullscreen();"));
observer.Wait();
}
fullscreen_frames.erase(child_frame);
EXPECT_EQ(fullscreen_frames, web_contents->fullscreen_frames_);
EXPECT_EQ(main_frame->GetGlobalId(),
web_contents->current_fullscreen_frame_id_);
}
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest, RejectFullscreenIfBlocked) {
WebContentsImpl* web_contents =
static_cast<WebContentsImpl*>(shell()->web_contents());
TestWCDelegateForDialogsAndFullscreen test_delegate(web_contents);
GURL url("about:blank");
EXPECT_TRUE(NavigateToURL(shell(), url));
RenderFrameHostImpl* main_frame = web_contents->GetPrimaryMainFrame();
EXPECT_TRUE(
ExecJs(main_frame,
"document.body.onfullscreenchange = "
"function (event) { document.title = 'onfullscreenchange' };"));
EXPECT_TRUE(
ExecJs(main_frame,
"document.body.onfullscreenerror = "
"function (event) { document.title = 'onfullscreenerror' };"));
TitleWatcher title_watcher(web_contents, u"onfullscreenchange");
title_watcher.AlsoWaitForTitle(u"onfullscreenerror");
// While the |fullscreen_block| is in scope, fullscreen should fail with an
// error.
base::ScopedClosureRunner fullscreen_block =
web_contents->ForSecurityDropFullscreen(
/*display_id=*/display::kInvalidDisplayId);
EXPECT_TRUE(ExecJs(main_frame, "document.body.requestFullscreen();",
EXECUTE_SCRIPT_NO_RESOLVE_PROMISES));
std::u16string title = title_watcher.WaitAndGetTitle();
ASSERT_EQ(title, u"onfullscreenerror");
}
// Regression test for https://crbug.com/855018.
// RenderFrameHostImpls exit fullscreen as soon as they are unloaded.
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest, FullscreenAfterFrameUnload) {
ASSERT_TRUE(embedded_test_server()->Start());
WebContentsImpl* web_contents =
static_cast<WebContentsImpl*>(shell()->web_contents());
GURL url_a = embedded_test_server()->GetURL("a.com", "/title1.html");
GURL url_b = embedded_test_server()->GetURL("b.com", "/title1.html");
// 1) Navigate. There is initially no fullscreen frame.
EXPECT_TRUE(NavigateToURL(shell(), url_a));
RenderFrameHostImpl* main_frame =
static_cast<RenderFrameHostImpl*>(web_contents->GetPrimaryMainFrame());
EXPECT_EQ(0u, web_contents->fullscreen_frames_.size());
// 2) Make it fullscreen.
FullscreenWebContentsObserver observer(web_contents, main_frame);
EXPECT_TRUE(ExecJs(main_frame, "document.body.webkitRequestFullscreen();"));
observer.Wait();
EXPECT_EQ(1u, web_contents->fullscreen_frames_.size());
// 3) Navigate cross origin. Act as if the old frame was very slow delivering
// the unload ack and stayed in pending deletion for a while. Even if the
// frame is still present, it must be removed from the list of frame in
// fullscreen immediately.
auto unload_ack_filter = base::BindRepeating([] { return true; });
main_frame->SetUnloadACKCallbackForTesting(unload_ack_filter);
main_frame->DisableUnloadTimerForTesting();
EXPECT_TRUE(NavigateToURL(shell(), url_b));
EXPECT_EQ(0u, web_contents->fullscreen_frames_.size());
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
NotifyFullscreenAcquired_Navigate) {
ASSERT_TRUE(embedded_test_server()->Start());
WebContentsImpl* web_contents =
static_cast<WebContentsImpl*>(shell()->web_contents());
TestWCDelegateForDialogsAndFullscreen test_delegate(web_contents);
test_delegate.WillWaitForFullscreenExit();
GURL url = embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(b{allowfullscreen})");
EXPECT_TRUE(NavigateToURL(shell(), url));
RenderFrameHostImpl* main_frame = web_contents->GetPrimaryMainFrame();
RenderFrameHostImpl* child_frame =
static_cast<RenderFrameHostImpl*>(ChildFrameAt(main_frame, 0));
std::set<raw_ptr<RenderFrameHostImpl, SetExperimental>> nodes;
EXPECT_EQ(nodes, web_contents->fullscreen_frames_);
EXPECT_FALSE(IsInFullscreen());
// Make the top page fullscreen.
{
FullscreenWebContentsObserver observer(web_contents, main_frame);
EXPECT_TRUE(ExecJs(main_frame, "document.body.webkitRequestFullscreen();"));
observer.Wait();
}
nodes.insert(main_frame);
EXPECT_EQ(nodes, web_contents->fullscreen_frames_);
EXPECT_EQ(main_frame->GetGlobalId(),
web_contents->current_fullscreen_frame_id_);
// Make the child frame fullscreen.
{
FullscreenWebContentsObserver observer(web_contents, child_frame);
EXPECT_TRUE(
ExecJs(child_frame, "document.body.webkitRequestFullscreen();"));
observer.Wait();
}
nodes.insert(child_frame);
EXPECT_EQ(nodes, web_contents->fullscreen_frames_);
EXPECT_EQ(child_frame->GetGlobalId(),
web_contents->current_fullscreen_frame_id_);
// Perform a cross origin navigation on the main frame.
EXPECT_TRUE(
NavigateToURL(shell(), embedded_test_server()->GetURL(
"c.com", "/cross_site_iframe_factory.html")));
EXPECT_EQ(0u, web_contents->fullscreen_frames_.size());
EXPECT_FALSE(IsInFullscreen());
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
NotifyFullscreenAcquired_SameOrigin) {
ASSERT_TRUE(embedded_test_server()->Start());
WebContentsImpl* web_contents =
static_cast<WebContentsImpl*>(shell()->web_contents());
TestWCDelegateForDialogsAndFullscreen test_delegate(web_contents);
GURL url = embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(a{allowfullscreen})");
EXPECT_TRUE(NavigateToURL(shell(), url));
RenderFrameHostImpl* main_frame = web_contents->GetPrimaryMainFrame();
RenderFrameHostImpl* child_frame =
static_cast<RenderFrameHostImpl*>(ChildFrameAt(main_frame, 0));
std::set<raw_ptr<RenderFrameHostImpl, SetExperimental>> fullscreen_frames;
EXPECT_EQ(fullscreen_frames, web_contents->fullscreen_frames_);
EXPECT_FALSE(IsInFullscreen());
// Make the top page fullscreen.
{
FullscreenWebContentsObserver observer(web_contents, main_frame);
EXPECT_TRUE(ExecJs(main_frame, "document.body.webkitRequestFullscreen();"));
observer.Wait();
}
fullscreen_frames.insert(main_frame);
EXPECT_EQ(fullscreen_frames, web_contents->fullscreen_frames_);
EXPECT_EQ(main_frame->GetGlobalId(),
web_contents->current_fullscreen_frame_id_);
// Make the child frame fullscreen.
{
FullscreenWebContentsObserver observer(web_contents, child_frame);
EXPECT_TRUE(
ExecJs(child_frame, "document.body.webkitRequestFullscreen();"));
observer.Wait();
}
fullscreen_frames.insert(child_frame);
EXPECT_EQ(fullscreen_frames, web_contents->fullscreen_frames_);
EXPECT_EQ(child_frame->GetGlobalId(),
web_contents->current_fullscreen_frame_id_);
// Exit fullscreen on the child frame.
{
FullscreenWebContentsObserver observer(web_contents, main_frame);
EXPECT_TRUE(ExecJs(child_frame, "document.webkitExitFullscreen();"));
observer.Wait();
}
fullscreen_frames.erase(child_frame);
EXPECT_EQ(fullscreen_frames, web_contents->fullscreen_frames_);
EXPECT_EQ(main_frame->GetGlobalId(),
web_contents->current_fullscreen_frame_id_);
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest, PropagateFullscreenOptions) {
ASSERT_TRUE(embedded_test_server()->Start());
WebContentsImpl* web_contents =
static_cast<WebContentsImpl*>(shell()->web_contents());
TestWCDelegateForDialogsAndFullscreen test_delegate(web_contents);
GURL url = embedded_test_server()->GetURL("a.com", "/page_with_iframe.html");
EXPECT_TRUE(NavigateToURL(web_contents, url));
RenderFrameHostImpl* main_frame = web_contents->GetPrimaryMainFrame();
EXPECT_FALSE(IsInFullscreen());
// Make the top page fullscreen with system navigation ui.
{
test_delegate.WillWaitForFullscreenEnter();
TitleWatcher title_watcher(web_contents, u"main_fullscreen_fulfilled");
EXPECT_TRUE(ExecJs(
main_frame,
"document.body.requestFullscreen({ navigationUI: 'show' }).then(() => "
"{document.title = 'main_fullscreen_fulfilled'});"));
test_delegate.Wait();
std::u16string title = title_watcher.WaitAndGetTitle();
ASSERT_EQ(title, u"main_fullscreen_fulfilled");
}
EXPECT_TRUE(test_delegate.fullscreen_options().prefers_navigation_bar);
RenderFrameHostImpl* child_frame =
static_cast<RenderFrameHostImpl*>(ChildFrameAt(main_frame, 0));
// Make the child frame fullscreen without system navigation ui.
{
test_delegate.WillWaitForFullscreenOption();
TitleWatcher title_watcher(web_contents, u"child_fullscreen_fulfilled");
EXPECT_TRUE(ExecJs(
child_frame,
"document.body.requestFullscreen({ navigationUI: 'hide' }).then(() => "
"{parent.document.title = 'child_fullscreen_fulfilled'});"));
test_delegate.Wait();
std::u16string title = title_watcher.WaitAndGetTitle();
ASSERT_EQ(title, u"child_fullscreen_fulfilled");
}
EXPECT_FALSE(test_delegate.fullscreen_options().prefers_navigation_bar);
// Exit fullscreen on the child frame and restore system navigation ui for the
// top page.
{
test_delegate.WillWaitForFullscreenOption();
EXPECT_TRUE(ExecJs(
main_frame,
"document.body.onfullscreenchange = "
"function (event) { document.title = 'main_in_fullscreen_again' };"));
TitleWatcher title_watcher(web_contents, u"main_in_fullscreen_again");
EXPECT_TRUE(ExecJs(child_frame, "document.exitFullscreen();"));
test_delegate.Wait();
std::u16string title = title_watcher.WaitAndGetTitle();
ASSERT_EQ(title, u"main_in_fullscreen_again");
}
EXPECT_TRUE(test_delegate.fullscreen_options().prefers_navigation_bar);
}
// Tests that when toggling EnterFullscreen/ExitFullscreen that each state
// properly synchronizes with the Renderer, fulfilling the Promises. Even when
// there has been no layout changes, such as when the Renderer is already
// embedded in a fullscreen context, with no OS nor Browser control insets.
//
// Also confirms that each state change does not block the subsequent one.
// Finally on Android, which supports full browser ScreenOrientation locks, that
// we can successfully apply the lock.
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest, ToggleFullscreen) {
ASSERT_TRUE(embedded_test_server()->Start());
WebContentsImpl* web_contents =
static_cast<WebContentsImpl*>(shell()->web_contents());
TestWCDelegateForDialogsAndFullscreen test_delegate(web_contents);
GURL url = embedded_test_server()->GetURL("a.com", "/page_with_iframe.html");
EXPECT_TRUE(NavigateToURL(web_contents, url));
RenderFrameHostImpl* main_frame = web_contents->GetPrimaryMainFrame();
EXPECT_FALSE(IsInFullscreen());
// Make the top page fullscreen with system navigation ui.
{
test_delegate.WillWaitForFullscreenEnter();
TitleWatcher title_watcher(web_contents, u"main_fullscreen_fulfilled");
EXPECT_TRUE(ExecJs(
main_frame,
"document.body.requestFullscreen({ navigationUI: 'show' }).then(() => "
"{document.title = 'main_fullscreen_fulfilled'});"));
test_delegate.Wait();
std::u16string title = title_watcher.WaitAndGetTitle();
ASSERT_EQ(title, u"main_fullscreen_fulfilled");
}
EXPECT_TRUE(IsInFullscreen());
// Full document orientation lock is only available on Android.
#if BUILDFLAG(IS_ANDROID)
{
TitleWatcher title_watcher(web_contents, u"portrait_lock_fulfilled");
EXPECT_TRUE(ExecJs(main_frame,
"screen.orientation.lock('portrait').then(() => "
"{document.title = 'portrait_lock_fulfilled'});"));
std::u16string title = title_watcher.WaitAndGetTitle();
ASSERT_EQ(title, u"portrait_lock_fulfilled");
}
#endif
// Exiting fullscreen should update the title. This should not block
// subsequent request to re-enter fullscreen.
{
test_delegate.WillWaitForFullscreenExit();
TitleWatcher title_watcher(web_contents, u"main_exit_fullscreen_fulfilled");
EXPECT_TRUE(
ExecJs(main_frame,
"document.exitFullscreen().then(() => "
"{document.title = 'main_exit_fullscreen_fulfilled'});"));
test_delegate.Wait();
std::u16string title = title_watcher.WaitAndGetTitle();
ASSERT_EQ(title, u"main_exit_fullscreen_fulfilled");
}
// Make the top page fullscreen with system navigation ui.
{
test_delegate.WillWaitForFullscreenEnter();
TitleWatcher title_watcher(web_contents, u"main_fullscreen_fulfilled");
EXPECT_TRUE(ExecJs(
main_frame,
"document.body.requestFullscreen({ navigationUI: 'show' }).then(() => "
"{document.title = 'main_fullscreen_fulfilled'});"));
test_delegate.Wait();
std::u16string title = title_watcher.WaitAndGetTitle();
ASSERT_EQ(title, u"main_fullscreen_fulfilled");
}
}
class MockDidOpenRequestedURLObserver : public WebContentsObserver {
public:
explicit MockDidOpenRequestedURLObserver(Shell* shell)
: WebContentsObserver(shell->web_contents()) {}
MockDidOpenRequestedURLObserver(const MockDidOpenRequestedURLObserver&) =
delete;
MockDidOpenRequestedURLObserver& operator=(
const MockDidOpenRequestedURLObserver&) = delete;
MOCK_METHOD8(DidOpenRequestedURL,
void(WebContents* new_contents,
RenderFrameHost* source_render_frame_host,
const GURL& url,
const Referrer& referrer,
WindowOpenDisposition disposition,
ui::PageTransition transition,
bool started_from_context_menu,
bool renderer_initiated));
};
// Test WebContentsObserver::DidOpenRequestedURL for ctrl-click-ed links.
// This is a regression test for https://crbug.com/864736 (although it also
// covers slightly more ground than just the |is_renderer_initiated| value).
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest, CtrlClickSubframeLink) {
ASSERT_TRUE(embedded_test_server()->Start());
// Load a page with a subframe link.
GURL main_url(
embedded_test_server()->GetURL("/ctrl-click-subframe-link.html"));
EXPECT_TRUE(NavigateToURL(shell(), main_url));
// Start intercepting the DidOpenRequestedURL callback.
MockDidOpenRequestedURLObserver mock_observer(shell());
WebContents* new_web_contents1 = nullptr;
RenderFrameHost* subframe =
ChildFrameAt(shell()->web_contents()->GetPrimaryMainFrame(), 0);
EXPECT_CALL(mock_observer,
DidOpenRequestedURL(
::testing::_, // new_contents (captured via SaveArg below)
subframe, // source_render_frame_host
embedded_test_server()->GetURL("/title1.html"),
::testing::Field(&Referrer::url, main_url),
WindowOpenDisposition::NEW_FOREGROUND_TAB,
::testing::Truly([](ui::PageTransition arg) {
return ui::PageTransitionCoreTypeIs(
arg, ui::PAGE_TRANSITION_LINK);
}),
false, // started_from_context_menu
true)) // is_renderer_initiated
.WillOnce(testing::SaveArg<0>(&new_web_contents1));
// Simulate a ctrl click on the link and ask GMock to verify that the
// MockDidOpenRequestedURLObserver got called with the expected args.
WebContentsAddedObserver new_web_contents_observer;
EXPECT_TRUE(
ExecJs(shell(), "window.domAutomationController.send(ctrlClickLink());"));
WebContents* new_web_contents2 = new_web_contents_observer.GetWebContents();
EXPECT_TRUE(testing::Mock::VerifyAndClearExpectations(&mock_observer));
EXPECT_EQ(new_web_contents1, new_web_contents2);
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest, SetVisibilityBeforeLoad) {
ASSERT_TRUE(embedded_test_server()->Start());
GURL url(embedded_test_server()->GetURL("/hello.html"));
WebContents* attached_web_contents = shell()->web_contents();
// Create a WebContents detached from native windows so that visibility of
// the WebContents is fully controlled by the app.
WebContents::CreateParams create_params(
attached_web_contents->GetBrowserContext());
std::unique_ptr<WebContents> web_contents =
WebContents::Create(create_params);
EXPECT_EQ(Visibility::VISIBLE, web_contents->GetVisibility());
web_contents->WasHidden();
EXPECT_EQ(Visibility::HIDDEN, web_contents->GetVisibility());
EXPECT_TRUE(NavigateToURL(web_contents.get(), url));
EXPECT_TRUE(EvalJs(web_contents.get(), "document.hidden").ExtractBool());
}
// This test verifies that if we attach an inner WebContents that has
// descendants in the WebContentsTree, that the descendants also have their
// views registered with the top-level WebContents' InputEventRouter. This
// ensures the descendants will receive events that should be routed to them.
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
AttachNestedInnerWebContents) {
ASSERT_TRUE(embedded_test_server()->Start());
const GURL url_a(embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(a)"));
const GURL url_b(embedded_test_server()->GetURL(
"b.com", "/cross_site_iframe_factory.html?b(b)"));
ASSERT_TRUE(NavigateToURL(shell(), url_a));
auto* root_web_contents =
static_cast<WebContentsImpl*>(shell()->web_contents());
// Create a child WebContents but don't attach it to the root contents yet.
WebContents::CreateParams inner_params(
root_web_contents->GetBrowserContext());
std::unique_ptr<WebContents> child_contents_ptr =
WebContents::Create(inner_params);
WebContents* child_contents = child_contents_ptr.get();
// Navigate the child to a page with a subframe, at which we will attach the
// grandchild.
ASSERT_TRUE(NavigateToURL(child_contents, url_b));
// Create and attach grandchild to child.
std::unique_ptr<WebContents> grandchild_contents_ptr =
WebContents::Create(inner_params);
WebContents* grandchild_contents = grandchild_contents_ptr.get();
RenderFrameHost* child_contents_subframe =
ChildFrameAt(child_contents->GetPrimaryMainFrame(), 0);
ASSERT_TRUE(child_contents_subframe);
child_contents->AttachInnerWebContents(std::move(grandchild_contents_ptr),
child_contents_subframe,
/*is_full_page=*/false);
// At this point the child hasn't been attached to the root.
{
auto* root_view = static_cast<RenderWidgetHostViewBase*>(
root_web_contents->GetRenderWidgetHostView());
ASSERT_TRUE(root_view);
auto* root_event_router = root_web_contents->GetInputEventRouter();
EXPECT_EQ(1U, root_event_router->RegisteredViewCountForTesting());
EXPECT_TRUE(root_event_router->IsViewInMap(root_view));
}
// Attach child+grandchild subtree to root.
RenderFrameHost* root_contents_subframe =
ChildFrameAt(root_web_contents->GetPrimaryMainFrame(), 0);
ASSERT_TRUE(root_contents_subframe);
root_web_contents->AttachInnerWebContents(std::move(child_contents_ptr),
root_contents_subframe,
/*is_full_page=*/false);
// Verify views registered for both child and grandchild.
{
auto* root_view = static_cast<RenderWidgetHostViewBase*>(
root_web_contents->GetRenderWidgetHostView());
auto* child_view = static_cast<RenderWidgetHostViewBase*>(
child_contents->GetRenderWidgetHostView());
auto* grandchild_view = static_cast<RenderWidgetHostViewBase*>(
grandchild_contents->GetRenderWidgetHostView());
ASSERT_TRUE(root_view);
ASSERT_TRUE(child_view);
ASSERT_TRUE(grandchild_view);
auto* root_event_router = root_web_contents->GetInputEventRouter();
EXPECT_EQ(3U, root_event_router->RegisteredViewCountForTesting());
EXPECT_TRUE(root_event_router->IsViewInMap(root_view));
EXPECT_TRUE(root_event_router->IsViewInMap(child_view));
EXPECT_TRUE(root_event_router->IsViewInMap(grandchild_view));
auto* text_input_manager = root_web_contents->GetTextInputManager();
ASSERT_TRUE(text_input_manager);
EXPECT_EQ(3U, text_input_manager->GetRegisteredViewsCountForTesting());
EXPECT_TRUE(text_input_manager->IsRegistered(root_view));
EXPECT_TRUE(text_input_manager->IsRegistered(child_view));
EXPECT_TRUE(text_input_manager->IsRegistered(grandchild_view));
}
}
// Non-regression test for crbug.com/336843455.
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest, InnerWebContentsVisibility) {
ASSERT_TRUE(embedded_test_server()->Start());
GURL url_a(embedded_test_server()->GetURL("a.com", "/page_with_iframe.html"));
GURL url_b(embedded_test_server()->GetURL("b.com", "/title1.html"));
EXPECT_TRUE(NavigateToURL(shell(), url_a));
auto* root_contents = static_cast<WebContentsImpl*>(shell()->web_contents());
WebContentsImpl* inner_contents =
static_cast<WebContentsImpl*>(CreateAndAttachInnerContents(
ChildFrameAt(root_contents->GetPrimaryMainFrame(), 0)));
ASSERT_TRUE(NavigateToURLFromRenderer(inner_contents, url_b));
root_contents->WasShown();
EXPECT_EQ(Visibility::VISIBLE, root_contents->GetVisibility());
EXPECT_EQ(PageVisibilityState::kVisible,
root_contents->GetPrimaryMainFrame()->GetVisibilityState());
EXPECT_EQ(Visibility::VISIBLE, inner_contents->GetVisibility());
root_contents->WasHidden();
EXPECT_EQ(Visibility::HIDDEN, root_contents->GetVisibility());
EXPECT_EQ(PageVisibilityState::kHidden,
root_contents->GetPrimaryMainFrame()->GetVisibilityState());
EXPECT_EQ(Visibility::HIDDEN, inner_contents->GetVisibility());
}
// Not supported on Android. Android assumes that WebContentsViewAndroid is
// always the view of a WebContents, whereas an inner WebContents has a
// WebContentsViewChildFrame as its view.
#if !BUILDFLAG(IS_ANDROID)
class UnownedInnerWebContentsBrowserTest : public WebContentsImplBrowserTest {
private:
base::test::ScopedFeatureList scoped_feature_list_{
features::kAttachUnownedInnerWebContents};
};
IN_PROC_BROWSER_TEST_F(UnownedInnerWebContentsBrowserTest,
AttachUnownedInnerWebContents) {
ASSERT_TRUE(embedded_test_server()->Start());
const GURL outer_url(
embedded_test_server()->GetURL("outer.com", "/page_with_iframe.html"));
const GURL inner_url(
embedded_test_server()->GetURL("inner.com", "/title1.html"));
const GURL another_url(
embedded_test_server()->GetURL("inner.com", "/title2.html"));
// Setup outer WebContents
ASSERT_TRUE(NavigateToURL(shell(), outer_url));
WebContentsImpl* outer_wc =
static_cast<WebContentsImpl*>(shell()->web_contents());
RenderFrameHostImpl* iframe_rfh = static_cast<RenderFrameHostImpl*>(
ChildFrameAt(outer_wc->GetPrimaryMainFrame(), 0));
ASSERT_TRUE(iframe_rfh);
FrameTreeNode* outer_iframe_node = iframe_rfh->frame_tree_node();
// Setup inner WebContents
WebContents::CreateParams inner_params(
shell()->web_contents()->GetBrowserContext());
std::unique_ptr<WebContents> inner_wc = WebContents::Create(inner_params);
WebContentsImpl* inner_wc_impl =
static_cast<WebContentsImpl*>(inner_wc.get());
ASSERT_TRUE(NavigateToURL(inner_wc.get(), inner_url));
// Verify initial state (no attachment)
EXPECT_EQ(nullptr, inner_wc->GetOuterWebContents());
EXPECT_TRUE(inner_wc_impl->GetOuterDelegateFrameTreeNodeId().is_null());
// Attach inner WC to outer WC's iframe.
base::RunLoop run_loop;
iframe_rfh->SetUnloadACKCallbackForTesting(base::BindLambdaForTesting([&]() {
run_loop.Quit();
return false;
}));
outer_wc->AttachUnownedInnerWebContents(
UnownedInnerWebContentsClient::GetPassKeyForTesting(),
inner_wc.get(), iframe_rfh);
// The outer RFH was unloaded while attaching the inner WC. The RFH was marked
// as offline by the asynchronous UnloadACK().
run_loop.Run();
EXPECT_FALSE(iframe_rfh->IsRenderFrameLive());
// Verify that the connection is established.
EXPECT_EQ(outer_wc, inner_wc->GetOuterWebContents());
EXPECT_EQ(outer_wc->GetPrimaryMainFrame(),
inner_wc->GetOuterWebContentsFrame());
EXPECT_EQ(outer_iframe_node->frame_tree_node_id(),
inner_wc_impl->GetOuterDelegateFrameTreeNodeId());
EXPECT_TRUE(outer_iframe_node->render_manager()
->is_attaching_inner_delegate());
EXPECT_EQ(
outer_wc->GetPrimaryMainFrame(),
inner_wc->GetPrimaryMainFrame()->GetParentOrOuterDocumentOrEmbedder());
EXPECT_EQ(nullptr,
inner_wc->GetPrimaryMainFrame()->GetParentOrOuterDocument());
EXPECT_TRUE(base::Contains(CollectAllRenderFrameHosts(outer_wc),
inner_wc->GetPrimaryMainFrame()));
EXPECT_TRUE(base::Contains(outer_wc->GetInnerWebContents(), inner_wc.get()));
// Verify that the inner WebContents can navigate while attached.
EXPECT_TRUE(NavigateToURL(inner_wc.get(), another_url));
EXPECT_EQ(u"Title Of Awesomeness", inner_wc->GetTitle());
// Destroy the inner WebContents and verify it's removed from the outer
// WebContents.
inner_wc.reset();
EXPECT_TRUE(outer_wc->GetInnerWebContents().empty());
EXPECT_FALSE(outer_iframe_node->render_manager()
->is_attaching_inner_delegate());
}
// Test detaching an unowned inner WebContents.
IN_PROC_BROWSER_TEST_F(UnownedInnerWebContentsBrowserTest,
DetachUnownedInnerWebContents) {
ASSERT_TRUE(embedded_test_server()->Start());
const GURL outer_url(
embedded_test_server()->GetURL("outer.com", "/page_with_iframe.html"));
const GURL inner_url(
embedded_test_server()->GetURL("inner.com", "/title1.html"));
// Setup outer and inner WebContents, and attach them (unowned)
ASSERT_TRUE(NavigateToURL(shell(), outer_url));
WebContentsImpl* outer_wc =
static_cast<WebContentsImpl*>(shell()->web_contents());
RenderFrameHostImpl* iframe_rfh = static_cast<RenderFrameHostImpl*>(
ChildFrameAt(outer_wc->GetPrimaryMainFrame(), 0));
ASSERT_TRUE(iframe_rfh);
WebContents::CreateParams inner_params(
shell()->web_contents()->GetBrowserContext());
std::unique_ptr<WebContents> inner_wc = WebContents::Create(inner_params);
WebContentsImpl* inner_wc_impl =
static_cast<WebContentsImpl*>(inner_wc.get());
ASSERT_TRUE(NavigateToURL(inner_wc.get(), inner_url));
outer_wc->AttachUnownedInnerWebContents(
UnownedInnerWebContentsClient::GetPassKeyForTesting(),
inner_wc.get(), iframe_rfh);
ASSERT_EQ(outer_wc, inner_wc->GetOuterWebContents());
// Detach the inner WebContents
outer_wc->DetachUnownedInnerWebContents(
UnownedInnerWebContentsClient::GetPassKeyForTesting(),
inner_wc.get());
// Verify that the connection is broken.
EXPECT_EQ(nullptr, inner_wc->GetOuterWebContents());
EXPECT_TRUE(inner_wc_impl->GetOuterDelegateFrameTreeNodeId().is_null());
EXPECT_FALSE(base::Contains(outer_wc->GetInnerWebContents(), inner_wc.get()));
EXPECT_EQ(
nullptr,
inner_wc->GetPrimaryMainFrame()->GetParentOrOuterDocumentOrEmbedder());
EXPECT_FALSE(base::Contains(CollectAllRenderFrameHosts(outer_wc),
inner_wc->GetPrimaryMainFrame()));
EXPECT_FALSE(iframe_rfh->frame_tree_node()->render_manager()
->is_attaching_inner_delegate());
// Verify inner WebContents still exists and is functional (e.g. can navigate)
EXPECT_FALSE(inner_wc->IsBeingDestroyed());
EXPECT_TRUE(NavigateToURL(inner_wc.get(), embedded_test_server()->GetURL(
"inner.com", "/title2.html")));
EXPECT_EQ(u"Title Of Awesomeness", inner_wc->GetTitle());
// Verify that the iframe can navigate to a different URL with OOPIF pages.
const GURL oopif_url(
embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(b(a),b)"));
EXPECT_TRUE(NavigateFrameToURL(iframe_rfh->frame_tree_node(), oopif_url));
}
IN_PROC_BROWSER_TEST_F(UnownedInnerWebContentsBrowserTest,
DetachThenReattachUnownedInnerWebContents) {
ASSERT_TRUE(embedded_test_server()->Start());
const GURL outer_url(
embedded_test_server()->GetURL("outer.com", "/page_with_iframe.html"));
const GURL inner_url(
embedded_test_server()->GetURL("inner.com", "/title1.html"));
// Setup outer and inner WebContents, and attach them (unowned)
ASSERT_TRUE(NavigateToURL(shell(), outer_url));
WebContentsImpl* outer_wc =
static_cast<WebContentsImpl*>(shell()->web_contents());
RenderFrameHostImpl* iframe_rfh = static_cast<RenderFrameHostImpl*>(
ChildFrameAt(outer_wc->GetPrimaryMainFrame(), 0));
ASSERT_TRUE(iframe_rfh);
WebContents::CreateParams inner_params(
shell()->web_contents()->GetBrowserContext());
std::unique_ptr<WebContents> inner_wc = WebContents::Create(inner_params);
// Attach the inner WebContents
ASSERT_TRUE(NavigateToURL(inner_wc.get(), inner_url));
outer_wc->AttachUnownedInnerWebContents(
UnownedInnerWebContentsClient::GetPassKeyForTesting(),
inner_wc.get(), iframe_rfh);
ASSERT_EQ(outer_wc, inner_wc->GetOuterWebContents());
// Detach and then reattach the inner WebContents
outer_wc->DetachUnownedInnerWebContents(
UnownedInnerWebContentsClient::GetPassKeyForTesting(),
inner_wc.get());
ASSERT_EQ(nullptr, inner_wc->GetOuterWebContents());
outer_wc->AttachUnownedInnerWebContents(
UnownedInnerWebContentsClient::GetPassKeyForTesting(),
inner_wc.get(), iframe_rfh);
ASSERT_EQ(outer_wc, inner_wc->GetOuterWebContents());
}
IN_PROC_BROWSER_TEST_F(UnownedInnerWebContentsBrowserTest,
DetachUnownedInnerWebContentsWithOOPIF) {
ASSERT_TRUE(embedded_test_server()->Start());
const GURL outer_url(
embedded_test_server()->GetURL("a.com", "/page_with_iframe.html"));
const GURL inner_url(
embedded_test_server()->GetURL(
"a.com", "/cross_site_iframe_factory.html?a(b(a),b)"));
// Setup outer WebContents
ASSERT_TRUE(NavigateToURL(shell(), outer_url));
WebContentsImpl* outer_wc =
static_cast<WebContentsImpl*>(shell()->web_contents());
RenderFrameHostImpl* iframe_rfh = static_cast<RenderFrameHostImpl*>(
ChildFrameAt(outer_wc->GetPrimaryMainFrame(), 0));
ASSERT_TRUE(iframe_rfh);
// Setup inner WebContents
WebContents::CreateParams inner_params(
shell()->web_contents()->GetBrowserContext());
std::unique_ptr<WebContents> inner_wc = WebContents::Create(inner_params);
ASSERT_TRUE(NavigateToURL(inner_wc.get(), inner_url));
// Attach the inner WebContents
outer_wc->AttachUnownedInnerWebContents(
UnownedInnerWebContentsClient::GetPassKeyForTesting(),
inner_wc.get(), iframe_rfh);
ASSERT_EQ(outer_wc, inner_wc->GetOuterWebContents());
// Verify RenderFrameHost is created for the inner WebContents
RenderFrameHost* rfh_a = inner_wc->GetPrimaryMainFrame();
ASSERT_TRUE(rfh_a);
RenderFrameHost* rfh_b1 = ChildFrameAt(rfh_a, 0);
ASSERT_TRUE(rfh_b1);
RenderFrameHost* rfh_a_nested = ChildFrameAt(rfh_b1, 0);
ASSERT_TRUE(rfh_a_nested);
RenderFrameHost* rfh_b2 = ChildFrameAt(rfh_a, 1);
ASSERT_TRUE(rfh_b2);
// Get the RenderWidgetHostView for a subframe RFH by going through the
// RenderFrameProxyHost.
auto GetRWHVForSubFrameRFHViaProxy = [](RenderFrameHost* outer_rfh) {
return static_cast<RenderFrameHostImpl*>(outer_rfh)
->frame_tree_node()
->render_manager()
->GetProxyToParent()
->cross_process_frame_connector()
->get_view_for_testing();
};
// Verify that only RVHs in the main frame's SiteInstance have a RWHV.
EXPECT_TRUE(rfh_a->GetRenderViewHost()->GetWidget()->GetView());
EXPECT_FALSE(rfh_b1->GetRenderViewHost()->GetWidget()->GetView());
EXPECT_TRUE(rfh_b1->GetView());
EXPECT_EQ(GetRWHVForSubFrameRFHViaProxy(rfh_b1),
rfh_b1->GetView());
EXPECT_TRUE(rfh_a_nested->GetRenderViewHost()->GetWidget()->GetView());
EXPECT_FALSE(rfh_b2->GetRenderViewHost()->GetWidget()->GetView());
EXPECT_TRUE(rfh_b2->GetView());
EXPECT_EQ(GetRWHVForSubFrameRFHViaProxy(rfh_b2),
rfh_b2->GetView());
// Detach the inner WebContents
outer_wc->DetachUnownedInnerWebContents(
UnownedInnerWebContentsClient::GetPassKeyForTesting(),
inner_wc.get());
ASSERT_EQ(nullptr, inner_wc->GetOuterWebContents());
// Verify that the inner WebContents's RFHs are still alive.
EXPECT_TRUE(rfh_a->IsRenderFrameLive());
EXPECT_TRUE(rfh_b1->IsRenderFrameLive());
EXPECT_TRUE(rfh_a_nested->IsRenderFrameLive());
EXPECT_TRUE(rfh_b2->IsRenderFrameLive());
// Verify that only RVHs in the main frame's SiteInstance have a RWHV.
EXPECT_TRUE(rfh_a->GetRenderViewHost()->GetWidget()->GetView());
EXPECT_FALSE(rfh_b1->GetRenderViewHost()->GetWidget()->GetView());
EXPECT_TRUE(rfh_b1->GetView());
EXPECT_EQ(GetRWHVForSubFrameRFHViaProxy(rfh_b1),
rfh_b1->GetView());
EXPECT_TRUE(rfh_a_nested->GetRenderViewHost()->GetWidget()->GetView());
EXPECT_FALSE(rfh_b2->GetRenderViewHost()->GetWidget()->GetView());
EXPECT_TRUE(rfh_b2->GetView());
EXPECT_EQ(GetRWHVForSubFrameRFHViaProxy(rfh_b2),
rfh_b2->GetView());
// Verify that the inner WebContents's RenderViewHosts are also alive.
EXPECT_TRUE(static_cast<RenderViewHostImpl*>(
rfh_a->GetRenderViewHost())->IsRenderViewLive());
EXPECT_TRUE(static_cast<RenderViewHostImpl*>(
rfh_b1->GetRenderViewHost())->IsRenderViewLive());
EXPECT_TRUE(static_cast<RenderViewHostImpl*>(
rfh_a_nested->GetRenderViewHost())->IsRenderViewLive());
EXPECT_TRUE(static_cast<RenderViewHostImpl*>(
rfh_b2->GetRenderViewHost())->IsRenderViewLive());
}
#endif // !BUILDFLAG(IS_ANDROID)
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
ShutdownDuringSpeculativeNavigation) {
ASSERT_TRUE(embedded_test_server()->Start());
GURL url(embedded_test_server()->GetURL("/hello.html"));
if (!AreAllSitesIsolatedForTesting()) {
// Isolate "b.com" so we are guaranteed to get a different process
// for navigations to this origin. Doing this ensures that a
// speculative RenderFrameHost is used.
IsolateOriginsForTesting(embedded_test_server(), shell()->web_contents(),
{"b.com"});
}
WebContents* attached_web_contents = shell()->web_contents();
WebContents::CreateParams create_params(
attached_web_contents->GetBrowserContext());
std::unique_ptr<WebContents> public_web_contents =
WebContents::Create(create_params);
auto* web_contents = static_cast<WebContentsImpl*>(public_web_contents.get());
FrameTreeNode* root = web_contents->GetPrimaryFrameTree().root();
// Complete a navigation.
GURL url1 = embedded_test_server()->GetURL("a.com", "/title1.html");
EXPECT_TRUE(NavigateToURL(web_contents, url1));
// Start navigating to a second page.
GURL url2 = embedded_test_server()->GetURL("b.com", "/title2.html");
TestNavigationManager manager(web_contents, url2);
web_contents->GetController().LoadURL(
url2, Referrer(), ui::PAGE_TRANSITION_LINK, std::string());
manager.WaitForSpeculativeRenderFrameHostCreation();
// While there is a speculative RenderFrameHost in the root FrameTreeNode...
ASSERT_TRUE(root->render_manager()->speculative_frame_host());
// Add an observer to ensure that the speculative RenderFrameHost gets
// deleted.
RenderFrameDeletedObserver frame_deletion_observer(
root->render_manager()->speculative_frame_host());
// ...shutdown the WebContents.
public_web_contents.reset();
// What should have happened is the speculative RenderFrameHost deletes the
// provisional RenderFrame. The |frame_deletion_observer| verifies that this
// happened.
EXPECT_TRUE(frame_deletion_observer.deleted());
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest, MouseButtonsNavigate) {
ASSERT_TRUE(embedded_test_server()->Start());
WebContentsImpl* web_contents =
static_cast<WebContentsImpl*>(shell()->web_contents());
GURL url_a = embedded_test_server()->GetURL("a.com", "/title1.html");
GURL url_b = embedded_test_server()->GetURL("b.com", "/title1.html");
EXPECT_TRUE(NavigateToURL(shell(), url_a));
EXPECT_TRUE(NavigateToURL(shell(), url_b));
{
TestNavigationObserver back_observer(web_contents);
web_contents->GetRenderWidgetHostWithPageFocus()->ForwardMouseEvent(
blink::WebMouseEvent(
blink::WebInputEvent::Type::kMouseUp, gfx::PointF(51, 50),
gfx::PointF(51, 50), blink::WebPointerProperties::Button::kBack, 0,
blink::WebInputEvent::kNoModifiers, base::TimeTicks::Now()));
back_observer.Wait();
ASSERT_EQ(url_a, web_contents->GetLastCommittedURL());
}
{
TestNavigationObserver forward_observer(web_contents);
web_contents->GetRenderWidgetHostWithPageFocus()->ForwardMouseEvent(
blink::WebMouseEvent(
blink::WebInputEvent::Type::kMouseUp, gfx::PointF(51, 50),
gfx::PointF(51, 50), blink::WebPointerProperties::Button::kForward,
0, blink::WebInputEvent::kNoModifiers, base::TimeTicks::Now()));
forward_observer.Wait();
ASSERT_EQ(url_b, web_contents->GetLastCommittedURL());
}
}
// https://crbug.com/1042128 started flaking after Field Trial Testing Config
// was enabled for content_browsertests. Most likely due to the BFCache
// experiment that got enabled.
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
DISABLED_MouseButtonsDontNavigate) {
// This test injects mouse event listeners in javascript that will
// preventDefault the action causing the default navigation action not to be
// taken.
ASSERT_TRUE(embedded_test_server()->Start());
WebContentsImpl* web_contents =
static_cast<WebContentsImpl*>(shell()->web_contents());
GURL url_a = embedded_test_server()->GetURL("a.com", "/title1.html");
GURL url_b = embedded_test_server()->GetURL("b.com", "/title1.html");
EXPECT_TRUE(NavigateToURL(shell(), url_a));
EXPECT_TRUE(NavigateToURL(shell(), url_b));
// Prevent default the action.
EXPECT_TRUE(ExecJs(shell(),
"document.addEventListener('mouseup', "
"event => event.preventDefault());"));
RenderWidgetHostImpl* render_widget_host =
web_contents->GetRenderWidgetHostWithPageFocus();
render_widget_host->ForwardMouseEvent(blink::WebMouseEvent(
blink::WebInputEvent::Type::kMouseUp, gfx::PointF(51, 50),
gfx::PointF(51, 50), blink::WebPointerProperties::Button::kBack, 0,
blink::WebInputEvent::kNoModifiers, base::TimeTicks::Now()));
RunUntilInputProcessed(render_widget_host);
// Wait an action timeout and assert the URL is correct.
{
base::RunLoop run_loop;
base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
FROM_HERE, run_loop.QuitClosure(), TestTimeouts::action_timeout());
run_loop.Run();
}
ASSERT_EQ(url_b, web_contents->GetLastCommittedURL());
// Move back so we have a forward entry in the history stack so we
// can test forward getting canceled.
{
TestNavigationObserver back_observer(web_contents);
web_contents->GetController().GoBack();
back_observer.Wait();
ASSERT_EQ(url_a, web_contents->GetLastCommittedURL());
}
// Now test the forward button by going back, and injecting the prevention
// script.
// Prevent default the action.
EXPECT_TRUE(ExecJs(shell(),
"document.addEventListener('mouseup', "
"event => event.preventDefault());"));
render_widget_host = web_contents->GetRenderWidgetHostWithPageFocus();
render_widget_host->ForwardMouseEvent(blink::WebMouseEvent(
blink::WebInputEvent::Type::kMouseUp, gfx::PointF(51, 50),
gfx::PointF(51, 50), blink::WebPointerProperties::Button::kForward, 0,
blink::WebInputEvent::kNoModifiers, base::TimeTicks::Now()));
RunUntilInputProcessed(render_widget_host);
// Wait an action timeout and assert the URL is correct.
{
base::RunLoop run_loop;
base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
FROM_HERE, run_loop.QuitClosure(), TestTimeouts::action_timeout());
run_loop.Run();
}
ASSERT_EQ(url_a, web_contents->GetLastCommittedURL());
}
#if !BUILDFLAG(IS_ANDROID)
// https://crbug.com/1402816. This test verifies that when mouse down is on main
// frame and mouse up is on OOF iframe, the mouse up event is delivered to the
// main frame as well to clear cached mouse states including autoscroll
// selection state.
IN_PROC_BROWSER_TEST_F(
WebContentsImplBrowserTest,
MouseUpInOOPIframeShouldCancelMainFrameAutoscrollSelection) {
ASSERT_TRUE(embedded_test_server()->Start());
WebContentsImpl* web_contents =
static_cast<WebContentsImpl*>(shell()->web_contents());
GURL data_url(R"HTML(
data:text/html,
<!DOCTYPE html>
<html lang='en'>
<head>
<style>
%23parentDiv {
display: flex;
}
%23input1 {
border: 1px solid black;
margin: 20px;
}
%23iframe1 {
height: 200vh;
}
</style>
</head>
<body>
<div id='parentDiv'>
<iframe src='https://b.com/title1.html' id='iframe1'></iframe>
<div>
<input type='text' id='input1'>
</div>
</div>
</body>
</html>)HTML");
EXPECT_TRUE(NavigateToURL(shell(), data_url));
WaitForLoadStop(web_contents);
const double input_center_y =
EvalJs(web_contents,
"document.getElementById('input1').offsetTop + "
"document.getElementById('input1').offsetHeight / 2")
.ExtractDouble();
const double input_center_x =
EvalJs(web_contents,
"document.getElementById('input1').offsetLeft + "
"document.getElementById('input1').offsetWidth / 2")
.ExtractDouble();
// Click the input element and start typing.
SimulateMouseClickAt(web_contents, 0, blink::WebMouseEvent::Button::kLeft,
gfx::Point(input_center_x, input_center_y));
RunUntilInputProcessed(web_contents->GetRenderWidgetHostWithPageFocus());
EXPECT_TRUE(ExecJs(web_contents,
"var inputElement = document.getElementById('input1');"
"new Promise(function(resolve) {"
" if (document.activeElement == inputElement)"
" resolve(true);"
" inputElement.addEventListener('focus', () => {"
" resolve(true);"
" });"
"});"));
SimulateKeyPress(web_contents, ui::DomKey::FromCharacter('A'),
ui::DomCode::US_A, ui::VKEY_A, false, false, false, false);
SimulateKeyPress(web_contents, ui::DomKey::FromCharacter('B'),
ui::DomCode::US_B, ui::VKEY_B, false, false, false, false);
RunUntilInputProcessed(web_contents->GetRenderWidgetHostWithPageFocus());
EXPECT_TRUE(ExecJs(web_contents,
"var inputElement = document.getElementById('input1');"
"new Promise(function(resolve) {"
" if (inputElement.value == 'AB')"
" resolve(true);"
" inputElement.addEventListener('change', () => {"
" if (inputElement.value == 'AB')"
" resolve(true);"
" });"
"});"));
EXPECT_EQ("AB",
EvalJs(web_contents, "document.getElementById('input1').value")
.ExtractString());
EXPECT_TRUE(ExecJs(web_contents,
"document.addEventListener('mousedown', () => { "
"window.receivedMouseDown = true; });"));
EXPECT_TRUE(ExecJs(web_contents,
"document.addEventListener('mouseup', () => { "
"window.receivedMouseUp = true; });"));
// Now, start the drag from input element to the OOP iframe.
SimulateMouseEvent(web_contents, blink::WebMouseEvent::Type::kMouseDown,
blink::WebMouseEvent::Button::kLeft,
gfx::Point(input_center_x, input_center_y));
SimulateMouseEvent(web_contents, blink::WebMouseEvent::Type::kMouseMove,
blink::WebMouseEvent::Button::kLeft,
gfx::Point(input_center_x - 5, input_center_y));
SimulateMouseEvent(web_contents, blink::WebMouseEvent::Type::kMouseMove,
blink::WebMouseEvent::Button::kLeft,
gfx::Point(input_center_x - 10, input_center_y));
const double iframe_center_x =
EvalJs(web_contents,
"document.getElementById('iframe1').offsetLeft + "
"document.getElementById('iframe1').offsetWidth / 2")
.ExtractDouble();
SimulateMouseEvent(web_contents, blink::WebMouseEvent::Type::kMouseMove,
blink::WebMouseEvent::Button::kLeft,
gfx::Point(iframe_center_x, input_center_y));
RunUntilInputProcessed(web_contents->GetRenderWidgetHostWithPageFocus());
EXPECT_TRUE(ExecJs(web_contents,
"new Promise(resolve => setTimeout(() => {"
" resolve(window.receivedMouseDown);"
"}));"));
EXPECT_TRUE(web_contents->GetInputEventRouter()
->root_view_receive_additional_mouse_up_);
SimulateMouseEvent(web_contents, blink::WebMouseEvent::Type::kMouseUp,
blink::WebMouseEvent::Button::kLeft,
gfx::Point(iframe_center_x, input_center_y));
RunUntilInputProcessed(web_contents->GetRenderWidgetHostWithPageFocus());
// Main frame should receive mouse up event.
EXPECT_TRUE(ExecJs(web_contents,
"new Promise(resolve => setTimeout(() => {"
" resolve(window.receivedMouseUp);"
"}));"));
EXPECT_FALSE(web_contents->GetInputEventRouter()
->root_view_receive_additional_mouse_up_);
// Type again in input element, insert text should be left to right.
SimulateKeyPress(web_contents, ui::DomKey::FromCharacter('E'),
ui::DomCode::US_E, ui::VKEY_E, false, false, false, false);
SimulateKeyPress(web_contents, ui::DomKey::FromCharacter('F'),
ui::DomCode::US_F, ui::VKEY_F, false, false, false, false);
RunUntilInputProcessed(web_contents->GetRenderWidgetHostWithPageFocus());
EXPECT_TRUE(ExecJs(web_contents,
"var inputElement = document.getElementById('input1');"
"new Promise(function(resolve) {"
" if (inputElement.value == 'EF')"
" resolve(true);"
" inputElement.addEventListener('change', () => {"
" if (inputElement.value == 'EF')"
" resolve(true);"
" });"
"});"));
EXPECT_EQ("EF",
EvalJs(web_contents, "document.getElementById('input1').value")
.ExtractString());
}
#endif // !BUILDFLAG(IS_ANDROID)
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest, FrameCount) {
ASSERT_TRUE(embedded_test_server()->Start());
base::HistogramTester histogram_tester;
GURL url_with_iframes =
embedded_test_server()->GetURL("a.com", "/page_with_iframe.html");
EXPECT_TRUE(NavigateToURL(shell(), url_with_iframes));
shell()->Close();
// Number of samples should be only one.
histogram_tester.ExpectTotalCount(kFrameCountUMA, 1);
histogram_tester.ExpectTotalCount(kMaxFrameCountUMA, 1);
histogram_tester.ExpectBucketCount(kFrameCountUMA, /* bucket */ 2,
/* count */ 1);
histogram_tester.ExpectBucketCount(kMaxFrameCountUMA, 2, 1);
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
MaxFrameCountForCrossProcessNavigation) {
ASSERT_TRUE(embedded_test_server()->Start());
base::HistogramTester histogram_tester;
auto* web_contents = static_cast<WebContentsImpl*>(shell()->web_contents());
GURL url = embedded_test_server()->GetURL("a.com", "/title1.html");
EXPECT_TRUE(NavigateToURL(shell(), url));
EXPECT_EQ(web_contents->max_loaded_frame_count_, 1u);
GURL url_with_iframes_out_of_process =
embedded_test_server()->GetURL("b.com", "/page_with_iframe.html");
EXPECT_TRUE(NavigateToURL(shell(), url_with_iframes_out_of_process));
EXPECT_EQ(web_contents->max_loaded_frame_count_, 2u);
// There should be two samples for kFrameCountUMA.
histogram_tester.ExpectTotalCount(kFrameCountUMA, 2);
histogram_tester.ExpectBucketCount(kFrameCountUMA, /* bucket */ 2,
/* count */ 1);
histogram_tester.ExpectBucketCount(kFrameCountUMA, /* bucket */ 1,
/* count */ 1);
// There should be only one record for KMaxFrameCountUMA as it is recorded
// either when a frame is destroyed or when a new page is loaded.
histogram_tester.ExpectTotalCount(kMaxFrameCountUMA, 1);
histogram_tester.ExpectBucketCount(kMaxFrameCountUMA, /* bucket */ 1,
/* count */ 1);
// Same site navigation with multiple cross process iframes.
GURL url_with_multiple_iframes = embedded_test_server()->GetURL(
"b.com", "/cross_site_iframe_factory.html?b(a,c(b),d,b)");
EXPECT_TRUE(NavigateToURL(shell(), url_with_multiple_iframes));
EXPECT_EQ(web_contents->max_loaded_frame_count_, 6u);
histogram_tester.ExpectTotalCount(kMaxFrameCountUMA, 2);
histogram_tester.ExpectBucketCount(kMaxFrameCountUMA, 1, 1);
histogram_tester.ExpectBucketCount(kMaxFrameCountUMA, 2, 1);
// Simulate tab close to check that |kMaxFrameCountUMA| gets recorded.
shell()->Close();
// When the shell closes, the web contents is destroyed, as a result the main
// frame will be destroyed. When the main frame is destroyed, the
// kMaxFrameCountUMA gets recorded.
histogram_tester.ExpectTotalCount(kMaxFrameCountUMA, 3);
histogram_tester.ExpectBucketCount(kMaxFrameCountUMA, 1, 1);
histogram_tester.ExpectBucketCount(kMaxFrameCountUMA, 2, 1);
histogram_tester.ExpectBucketCount(kMaxFrameCountUMA, 6, 1);
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
MaxFrameCountInjectedIframes) {
ASSERT_TRUE(embedded_test_server()->Start());
base::HistogramTester histogram_tester;
auto* web_contents = static_cast<WebContentsImpl*>(shell()->web_contents());
GURL url_with_iframes =
embedded_test_server()->GetURL("a.com", "/page_with_iframe.html");
EXPECT_TRUE(NavigateToURL(shell(), url_with_iframes));
EXPECT_EQ(web_contents->max_loaded_frame_count_, 2u);
// |url_with_iframes| contains another iframe inside it. This means that we
// have 4 iframes inside.
auto* rfh = static_cast<RenderFrameHostImpl*>(
CreateSubframe(web_contents, "" /* frame_id */, url_with_iframes,
true /* wait_for_navigation */));
EXPECT_EQ(web_contents->max_loaded_frame_count_, 4u);
ASSERT_NE(rfh, nullptr);
shell()->Close();
// There should be one sample for kFrameCountUMA.
histogram_tester.ExpectTotalCount(kFrameCountUMA, 1);
histogram_tester.ExpectBucketCount(kFrameCountUMA, /* bucket */ 2,
/* count */ 1);
// There should be one sample for kMaxFrameCountUMA.
histogram_tester.ExpectTotalCount(kMaxFrameCountUMA, 1);
histogram_tester.ExpectBucketCount(kMaxFrameCountUMA, /* bucket */ 4u,
/* count */ 1);
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
MaxFrameCountRemovedIframes) {
ASSERT_TRUE(embedded_test_server()->Start());
base::HistogramTester histogram_tester;
auto* web_contents = static_cast<WebContentsImpl*>(shell()->web_contents());
GURL url_with_iframes =
embedded_test_server()->GetURL("a.com", "/page_with_iframe.html");
EXPECT_TRUE(NavigateToURL(shell(), url_with_iframes));
EXPECT_EQ(web_contents->max_loaded_frame_count_, 2u);
GURL url = embedded_test_server()->GetURL("a.com", "/title1.html");
auto* rfh = static_cast<RenderFrameHostImpl*>(CreateSubframe(
web_contents, "" /* frame_id */, url, true /* wait_for_navigation */));
;
ASSERT_NE(rfh, nullptr);
EXPECT_EQ(web_contents->max_loaded_frame_count_, 3u);
// Let's remove the first child.
auto* main_frame = web_contents->GetPrimaryMainFrame();
auto* node_to_remove = main_frame->child_at(0);
FrameDeletedObserver observer(node_to_remove->current_frame_host());
EXPECT_TRUE(ExecJs(main_frame,
"document.body.removeChild(document.querySelector('"
"iframe').parentNode);"));
observer.Wait();
EXPECT_EQ(web_contents->max_loaded_frame_count_, 3u);
// Let's remove the second child.
node_to_remove = main_frame->child_at(0);
FrameDeletedObserver observer_second(node_to_remove->current_frame_host());
EXPECT_TRUE(
ExecJs(main_frame,
"document.body.removeChild(document.querySelector('iframe'));"));
observer_second.Wait();
EXPECT_EQ(web_contents->max_loaded_frame_count_, 3u);
shell()->Close();
// There should be one sample for kFrameCountUMA.
histogram_tester.ExpectTotalCount(kFrameCountUMA, 1);
histogram_tester.ExpectBucketCount(kFrameCountUMA, /* bucket */ 2,
/* count */ 1);
// There should be one sample for kMaxFrameCountUMA
histogram_tester.ExpectTotalCount(kMaxFrameCountUMA, 1);
histogram_tester.ExpectBucketCount(kMaxFrameCountUMA, /* bucket */ 3,
/* count */ 1);
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest, ForEachRenderFrameHost) {
ASSERT_TRUE(embedded_test_server()->Start());
const GURL url =
embedded_test_server()->GetURL("a.com", "/page_with_iframe.html");
ASSERT_TRUE(NavigateToURL(shell(), url));
auto* web_contents = static_cast<WebContentsImpl*>(shell()->web_contents());
// In the absence of any pages besides the primary page (e.g. nothing in
// bfcache, no prerendered pages), iterating over the RenderFrameHosts of the
// WebContents would just produce the RenderFrameHosts of the primary page.
EXPECT_THAT(CollectAllRenderFrameHosts(web_contents),
testing::ContainerEq(CollectAllRenderFrameHosts(
web_contents->GetPrimaryMainFrame())));
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
ForEachRenderFrameHostInnerContents) {
ASSERT_TRUE(embedded_test_server()->Start());
const GURL url_a(
embedded_test_server()->GetURL("a.com", "/page_with_iframe.html"));
const GURL url_b(embedded_test_server()->GetURL("b.com", "/title1.html"));
ASSERT_TRUE(NavigateToURL(shell(), url_a));
auto* web_contents = static_cast<WebContentsImpl*>(shell()->web_contents());
auto* inner_contents = CreateAndAttachInnerContents(
web_contents->GetPrimaryMainFrame()->child_at(0)->current_frame_host());
ASSERT_TRUE(NavigateToURLFromRenderer(inner_contents, url_b));
// Calling |WebContents::ForEachRenderFrameHost| on an inner contents does not
// add much value over |RenderFrameHost::ForEachRenderFrameHost|, since we
// don't have any pages besides the primary page, however for completeness, we
// allow it to be called and confirm that it just returns the RenderFrameHosts
// of the primary page.
EXPECT_THAT(CollectAllRenderFrameHosts(inner_contents),
testing::ContainerEq(CollectAllRenderFrameHosts(
inner_contents->GetPrimaryMainFrame())));
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
ForEachFrameTreeInnerContents) {
ASSERT_TRUE(embedded_test_server()->Start());
const GURL url_a(
embedded_test_server()->GetURL("a.com", "/page_with_iframe.html"));
const GURL url_b(embedded_test_server()->GetURL("b.com", "/title1.html"));
ASSERT_TRUE(NavigateToURL(shell(), url_a));
auto* web_contents = static_cast<WebContentsImpl*>(shell()->web_contents());
auto* inner_contents = static_cast<WebContentsImpl*>(
CreateAndAttachInnerContents(web_contents->GetPrimaryMainFrame()
->child_at(0)
->current_frame_host()));
ASSERT_TRUE(NavigateToURLFromRenderer(inner_contents, url_b));
// Intentionally exclude inner frame trees based on multi-WebContents.
web_contents->ForEachFrameTree([&](FrameTree& frame_tree) {
EXPECT_NE(&frame_tree, &inner_contents->GetPrimaryFrameTree());
});
}
namespace {
class LoadingObserver : public WebContentsObserver {
public:
explicit LoadingObserver(WebContents* web_contents)
: WebContentsObserver(web_contents) {}
std::vector<std::string>& GetEvents() { return events_; }
void DidStartNavigation(NavigationHandle* navigation_handle) override {
events_.push_back("DidStartNavigation");
}
void DidFinishNavigation(NavigationHandle* navigation_handle) override {
events_.push_back("DidFinishNavigation");
}
void DidStartLoading() override { events_.push_back("DidStartLoading"); }
void DidStopLoading() override {
events_.push_back("DidStopLoading");
run_loop_.Quit();
}
void PrimaryMainDocumentElementAvailable() override {
events_.push_back("PrimaryMainDocumentElementAvailable");
}
void DocumentOnLoadCompletedInPrimaryMainFrame() override {
events_.push_back("DocumentOnLoadCompletedInPrimaryMainFrame");
}
void DOMContentLoaded(RenderFrameHost* render_frame_host) override {
events_.push_back("DOMContentLoaded");
}
void DidFinishLoad(RenderFrameHost* render_frame_host,
const GURL& url) override {
events_.push_back("DidFinishLoad");
}
void DidFailLoad(RenderFrameHost* render_frame_host,
const GURL& url,
int error_code) override {
events_.push_back("DidFailLoad");
}
void Wait() { run_loop_.Run(); }
private:
std::vector<std::string> events_;
base::RepeatingClosure completion_callback_;
base::RunLoop run_loop_;
};
} // namespace
// These tests provide a reference points for simulating the navigation events
// for unittests.
//
// Keep in sync with TestRenderFrameHostTest.LoadingCallbacksOrder_*.
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
LoadingCallbacksOrder_CrossDocumentNavigation) {
ASSERT_TRUE(embedded_test_server()->Start());
WebContentsImpl* web_contents =
static_cast<WebContentsImpl*>(shell()->web_contents());
LoadingObserver loading_observer(web_contents);
GURL url = embedded_test_server()->GetURL("a.com", "/title1.html");
EXPECT_TRUE(NavigateToURL(shell(), url));
loading_observer.Wait();
EXPECT_THAT(loading_observer.GetEvents(),
testing::ElementsAre("DidStartLoading", "DidStartNavigation",
"DidFinishNavigation",
"PrimaryMainDocumentElementAvailable",
"DOMContentLoaded",
"DocumentOnLoadCompletedInPrimaryMainFrame",
"DidFinishLoad", "DidStopLoading"));
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
LoadingCallbacksOrder_SameDocumentNavigation) {
ASSERT_TRUE(embedded_test_server()->Start());
WebContentsImpl* web_contents =
static_cast<WebContentsImpl*>(shell()->web_contents());
GURL url1 = embedded_test_server()->GetURL("a.com", "/title1.html");
GURL url2 = embedded_test_server()->GetURL("a.com", "/title1.html#foo");
LoadingObserver loading_observer1(web_contents);
EXPECT_TRUE(NavigateToURL(shell(), url1));
loading_observer1.Wait();
LoadingObserver loading_observer2(web_contents);
EXPECT_TRUE(NavigateToURL(shell(), url2));
loading_observer2.Wait();
EXPECT_THAT(loading_observer2.GetEvents(),
testing::ElementsAre("DidStartLoading", "DidStartNavigation",
"DidFinishNavigation", "DidStopLoading"));
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
LoadingCallbacksOrder_AbortedNavigation) {
const char kPageURL[] = "/controlled_page_load.html";
net::test_server::ExpectationHandler handler(embedded_test_server());
ASSERT_TRUE(embedded_test_server()->Start());
GURL url = embedded_test_server()->GetURL("a.com", kPageURL);
WebContentsImpl* web_contents =
static_cast<WebContentsImpl*>(shell()->web_contents());
handler.OnRequest(kPageURL).RespondWith(net::HttpStatusCode::HTTP_NO_CONTENT);
LoadingObserver loading_observer(web_contents);
shell()->LoadURL(url);
loading_observer.Wait();
EXPECT_THAT(loading_observer.GetEvents(),
testing::ElementsAre("DidStartLoading", "DidStartNavigation",
"DidFinishNavigation", "DidStopLoading"));
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
LoadingCallbacksOrder_ErrorPage_EmptyBody) {
const char kPageURL[] = "/controlled_page_load.html";
net::test_server::ExpectationHandler handler(embedded_test_server());
ASSERT_TRUE(embedded_test_server()->Start());
handler.OnRequest(kPageURL).RespondWith(
net::HttpStatusCode::HTTP_REQUEST_TIMEOUT);
GURL url = embedded_test_server()->GetURL("a.com", kPageURL);
WebContentsImpl* web_contents =
static_cast<WebContentsImpl*>(shell()->web_contents());
LoadingObserver loading_observer(web_contents);
shell()->LoadURL(url);
loading_observer.Wait();
EXPECT_THAT(loading_observer.GetEvents(),
testing::ElementsAre("DidStartLoading", "DidStartNavigation",
"DidFinishNavigation",
"PrimaryMainDocumentElementAvailable",
"DOMContentLoaded",
"DocumentOnLoadCompletedInPrimaryMainFrame",
"DidFinishLoad", "DidStopLoading"));
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
LoadingCallbacksOrder_ErrorPage_NonEmptyBody) {
const char kPageURL[] = "/controlled_page_load.html";
net::test_server::ExpectationHandler handler(embedded_test_server());
ASSERT_TRUE(embedded_test_server()->Start());
handler.OnRequest(kPageURL).RespondWith(net::HttpStatusCode::HTTP_NOT_FOUND,
"text/html",
"<html><body>foo</body>");
GURL url = embedded_test_server()->GetURL("a.com", kPageURL);
WebContentsImpl* web_contents =
static_cast<WebContentsImpl*>(shell()->web_contents());
LoadingObserver loading_observer(web_contents);
shell()->LoadURL(url);
loading_observer.Wait();
EXPECT_THAT(loading_observer.GetEvents(),
testing::ElementsAre("DidStartLoading", "DidStartNavigation",
"DidFinishNavigation",
"PrimaryMainDocumentElementAvailable",
"DOMContentLoaded",
"DocumentOnLoadCompletedInPrimaryMainFrame",
"DidFinishLoad", "DidStopLoading"));
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
ThemeColorIsResetWhenNavigatingAway) {
ASSERT_TRUE(embedded_test_server()->Start());
const GURL url_a(
embedded_test_server()->GetURL("a.com", "/theme_color.html"));
const GURL url_b(embedded_test_server()->GetURL("b.com", "/title1.html"));
EXPECT_TRUE(NavigateToURL(shell(), url_a));
EXPECT_EQ(shell()->web_contents()->GetThemeColor(), 0xFFFF0000u);
EXPECT_TRUE(NavigateToURL(shell(), url_b));
EXPECT_EQ(shell()->web_contents()->GetThemeColor(), std::nullopt);
shell()->web_contents()->GetController().GoBack();
EXPECT_TRUE(WaitForLoadStop(shell()->web_contents()));
EXPECT_EQ(shell()->web_contents()->GetThemeColor(), 0xFFFF0000u);
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
MimeTypeResetWhenNavigatingAway) {
ASSERT_TRUE(embedded_test_server()->Start());
const GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html"));
const GURL url_b(embedded_test_server()->GetURL("b.com", "/single_face.jpg"));
EXPECT_TRUE(NavigateToURL(shell(), url_a));
EXPECT_EQ(shell()->web_contents()->GetContentsMimeType(), "text/html");
EXPECT_TRUE(NavigateToURL(shell(), url_b));
EXPECT_EQ(shell()->web_contents()->GetContentsMimeType(), "image/jpeg");
}
namespace {
// A WebContentsObserver which caches the total number of calls to
// DidChangeVerticalScrollDirection as well as the most recently provided value.
class DidChangeVerticalScrollDirectionObserver : public WebContentsObserver {
public:
explicit DidChangeVerticalScrollDirectionObserver(WebContents* web_contents)
: WebContentsObserver(web_contents) {}
DidChangeVerticalScrollDirectionObserver(
const DidChangeVerticalScrollDirectionObserver&) = delete;
DidChangeVerticalScrollDirectionObserver& operator=(
const DidChangeVerticalScrollDirectionObserver&) = delete;
// WebContentsObserver:
void DidChangeVerticalScrollDirection(
viz::VerticalScrollDirection scroll_direction) override {
++call_count_;
last_value_ = scroll_direction;
}
int call_count() const { return call_count_; }
viz::VerticalScrollDirection last_value() const { return last_value_; }
private:
int call_count_ = 0;
viz::VerticalScrollDirection last_value_ =
viz::VerticalScrollDirection::kNull;
};
} // namespace
// Tests that DidChangeVerticalScrollDirection is called only when the vertical
// scroll direction has changed and that it includes the correct details.
// TODO(crbug.com/40862270): This is flaky on the Mac10.14 bot.
// TODO(crbug.com/401544068): This is failing on Android bots.
#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_ANDROID)
#define MAYBE_DidChangeVerticalScrollDirection \
DISABLED_DidChangeVerticalScrollDirection
#else
#define MAYBE_DidChangeVerticalScrollDirection DidChangeVerticalScrollDirection
#endif
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
MAYBE_DidChangeVerticalScrollDirection) {
net::EmbeddedTestServer* server = embedded_test_server();
EXPECT_TRUE(server->Start());
// Set up the DOM.
EXPECT_TRUE(NavigateToURL(
shell(), GURL(server->GetURL("/scrollable_page_with_content.html"))));
// Size our view so that we can scroll both horizontally and vertically while
// the content is visible.
ResizeWebContentsView(shell(), gfx::Size(20, 20), /*set_start_page=*/false);
// Set up observers to watch the web contents and render frame submissions.
auto* web_contents = shell()->web_contents();
DidChangeVerticalScrollDirectionObserver web_contents_observer(web_contents);
RenderFrameSubmissionObserver render_frame_observer(web_contents);
// Verify that we are starting our test without scroll offset.
render_frame_observer.WaitForScrollOffset(gfx::PointF());
// Assert initial state.
EXPECT_EQ(0, web_contents_observer.call_count());
EXPECT_EQ(viz::VerticalScrollDirection::kNull,
web_contents_observer.last_value());
// Scroll offset is dependent upon device pixel ratio which can vary across
// devices. To account for this, we extract the |devicePixelRatio| from our
// content window and for the remainder of this test use a scaled |Vector2dF|,
// which takes pixel ratio into consideration, when waiting for scroll offset.
// Note that this is primarily being done to satisfy tests running on Android.
const double device_pixel_ratio =
EvalJs(web_contents, "window.devicePixelRatio").ExtractDouble();
auto ScaledPointF = [device_pixel_ratio](float x, float y) {
return gfx::PointF(std::round(x * device_pixel_ratio),
std::round(y * device_pixel_ratio));
};
// Scroll down.
EXPECT_TRUE(ExecJs(web_contents, "window.scrollTo(0, 5)"));
render_frame_observer.WaitForScrollOffset(ScaledPointF(0.f, 5.f));
// Assert that we are notified of the scroll down event.
EXPECT_EQ(1, web_contents_observer.call_count());
EXPECT_EQ(viz::VerticalScrollDirection::kDown,
web_contents_observer.last_value());
// Scroll down again.
EXPECT_TRUE(ExecJs(web_contents, "window.scrollTo(0, 10)"));
render_frame_observer.WaitForScrollOffset(ScaledPointF(0.f, 10.f));
// Assert that we are *not* notified of the scroll down event given that no
// change in scroll direction occurred (as our previous scroll was also down).
EXPECT_EQ(1, web_contents_observer.call_count());
EXPECT_EQ(viz::VerticalScrollDirection::kDown,
web_contents_observer.last_value());
// Scroll right.
EXPECT_TRUE(ExecJs(web_contents, "window.scrollTo(10, 10)"));
render_frame_observer.WaitForScrollOffset(ScaledPointF(10.f, 10.f));
// Assert that we are *not* notified of the scroll right event given that no
// change occurred in the vertical direction.
EXPECT_EQ(1, web_contents_observer.call_count());
EXPECT_EQ(viz::VerticalScrollDirection::kDown,
web_contents_observer.last_value());
// Scroll left.
EXPECT_TRUE(ExecJs(web_contents, "window.scrollTo(0, 10)"));
render_frame_observer.WaitForScrollOffset(ScaledPointF(0.f, 10.f));
// Assert that we are *not* notified of the scroll left event given that no
// change occurred in the vertical direction.
EXPECT_EQ(1, web_contents_observer.call_count());
EXPECT_EQ(viz::VerticalScrollDirection::kDown,
web_contents_observer.last_value());
// Scroll up.
EXPECT_TRUE(ExecJs(web_contents, "window.scrollTo(0, 5)"));
render_frame_observer.WaitForScrollOffset(ScaledPointF(0.f, 5.f));
// Assert that we are notified of the scroll up event.
EXPECT_EQ(2, web_contents_observer.call_count());
EXPECT_EQ(viz::VerticalScrollDirection::kUp,
web_contents_observer.last_value());
// Scroll up again.
EXPECT_TRUE(ExecJs(web_contents, "window.scrollTo(0, 0)"));
render_frame_observer.WaitForScrollOffset(ScaledPointF(0.f, 0.f));
// Assert that we are *not* notified of the scroll up event given that no
// change in scroll direction occurred (as our previous scroll was also up).
EXPECT_EQ(2, web_contents_observer.call_count());
EXPECT_EQ(viz::VerticalScrollDirection::kUp,
web_contents_observer.last_value());
}
// Tests that DidChangeVerticalScrollDirection is *not* called when the vertical
// scroll direction has changed in a child frame. We expect to only be notified
// of vertical scroll direction changes to the main frame's root layer.
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
DidChangeVerticalScrollDirectionWithIframe) {
net::EmbeddedTestServer* server = embedded_test_server();
EXPECT_TRUE(server->Start());
// Set up the DOM.
GURL main_url(server->GetURL("a.co", "/scrollable_page_with_iframe.html"));
EXPECT_TRUE(NavigateToURL(shell(), main_url));
// Set up the iframe.
auto* web_contents = static_cast<WebContentsImpl*>(shell()->web_contents());
FrameTreeNode* iframe =
web_contents->GetPrimaryFrameTree().root()->child_at(0);
GURL iframe_url(server->GetURL("b.co", "/scrollable_page_with_content.html"));
EXPECT_TRUE(NavigateToURLFromRenderer(iframe, iframe_url));
// Size our view so that we can scroll both horizontally and vertically.
ResizeWebContentsView(shell(), gfx::Size(10, 10), /*set_start_page=*/false);
// Set up an observer to watch the web contents.
DidChangeVerticalScrollDirectionObserver web_contents_observer(web_contents);
// Assert initial state.
EXPECT_EQ(0, web_contents_observer.call_count());
EXPECT_EQ(viz::VerticalScrollDirection::kNull,
web_contents_observer.last_value());
// Scroll down in the iframe.
EXPECT_TRUE(ExecJs(iframe->current_frame_host(), "window.scrollTo(0, 10)"));
// Assert that we are *not* notified of the scroll down event given that the
// scroll was not performed on the main frame's root layer.
EXPECT_EQ(0, web_contents_observer.call_count());
EXPECT_EQ(viz::VerticalScrollDirection::kNull,
web_contents_observer.last_value());
// Scroll right in the iframe.
EXPECT_TRUE(ExecJs(iframe->current_frame_host(), "window.scrollTo(10, 10)"));
// Assert that we are *not* notified of the scroll right event given that the
// scroll was not performed on the main frame's root layer.
EXPECT_EQ(0, web_contents_observer.call_count());
EXPECT_EQ(viz::VerticalScrollDirection::kNull,
web_contents_observer.last_value());
// Scroll left in the iframe.
EXPECT_TRUE(ExecJs(iframe->current_frame_host(), "window.scrollTo(0, 10)"));
// Assert that we are *not* notified of the scroll left event given that the
// scroll was not performed on the main frame's root layer.
EXPECT_EQ(0, web_contents_observer.call_count());
EXPECT_EQ(viz::VerticalScrollDirection::kNull,
web_contents_observer.last_value());
// Scroll up in the iframe.
EXPECT_TRUE(ExecJs(iframe->current_frame_host(), "window.scrollTo(0, 0)"));
// Assert that we are *not* notified of the scroll up event given that the
// scroll was not performed on the main frame's root layer.
EXPECT_EQ(0, web_contents_observer.call_count());
EXPECT_EQ(viz::VerticalScrollDirection::kNull,
web_contents_observer.last_value());
}
// Verifies assertions for SetRendererInitiatedUserAgentOverrideOption().
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
RendererInitiatedUserAgentOverride) {
ASSERT_TRUE(embedded_test_server()->Start());
WebContents* web_contents = shell()->web_contents();
// This url triggers a renderer initiated navigation (redirect).
NavigationController::LoadURLParams load_params(
embedded_test_server()->GetURL("a.co", "/client_redirect.html"));
load_params.override_user_agent = NavigationController::UA_OVERRIDE_TRUE;
const GURL resulting_url =
embedded_test_server()->GetURL("a.co", "/title1.html");
// Assertions for the default SetRendererInitiatedUserAgentOverrideOption(),
// which is UA_OVERRIDE_INHERIT.
{
// The 2 is because the url redirects.
TestNavigationObserver observer(shell()->web_contents(), 2);
web_contents->GetController().LoadURLWithParams(load_params);
observer.Wait();
NavigationEntry* resulting_entry =
web_contents->GetController().GetLastCommittedEntry();
ASSERT_TRUE(resulting_entry);
EXPECT_EQ(resulting_url, resulting_entry->GetURL());
// The resulting entry should override the user-agent as the previous
// entry (as created by |load_params|) was configured to override the
// user-agent, and the WebContents was configured with
// SetRendererInitiatedUserAgentOverrideOption() of
// UA_OVERRIDE_INHERIT.
EXPECT_TRUE(resulting_entry->GetIsOverridingUserAgent());
}
// Repeat the above, but with UA_OVERRIDE_FALSE.
web_contents->SetRendererInitiatedUserAgentOverrideOption(
NavigationController::UA_OVERRIDE_FALSE);
{
// The 2 is because the url redirects.
TestNavigationObserver observer(shell()->web_contents(), 2);
web_contents->GetController().LoadURLWithParams(load_params);
observer.Wait();
EXPECT_EQ(2, web_contents->GetController().GetEntryCount());
NavigationEntry* resulting_entry =
web_contents->GetController().GetLastCommittedEntry();
ASSERT_TRUE(resulting_entry);
EXPECT_EQ(resulting_url, resulting_entry->GetURL());
// Even though |load_params| was configured to override the user-agent, the
// NavigationEntry for the redirect gets an override user-agent value of
// false because
// of SetRendererInitiatedUserAgentOverrideOption(UA_OVERRIDE_FALSE).
EXPECT_FALSE(resulting_entry->GetIsOverridingUserAgent());
}
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
IgnoreUnresponsiveRendererDuringPaste) {
WebContentsImpl* web_contents =
static_cast<WebContentsImpl*>(shell()->web_contents());
ClipboardPasteData clipboard_paste_data;
clipboard_paste_data.text = u"random pasted text";
EXPECT_FALSE(web_contents->ShouldIgnoreUnresponsiveRenderer());
web_contents->IsClipboardPasteAllowedByPolicy(
ClipboardEndpoint(ui::DataTransferEndpoint(GURL("https://google.com"))),
ClipboardEndpoint(ui::DataTransferEndpoint(GURL("https://google.com")),
base::BindLambdaForTesting([web_contents] {
return web_contents->GetBrowserContext();
}),
*web_contents->GetPrimaryMainFrame()),
{.format_type = ui::ClipboardFormatType::PlainTextType()},
clipboard_paste_data,
base::BindLambdaForTesting(
[&web_contents](
std::optional<ClipboardPasteData> clipboard_paste_data) {
EXPECT_TRUE(clipboard_paste_data.has_value());
EXPECT_TRUE(web_contents->ShouldIgnoreUnresponsiveRenderer());
}));
EXPECT_FALSE(web_contents->ShouldIgnoreUnresponsiveRenderer());
}
// Intercept calls to RenderFramHostImpl's DidStopLoading mojo method. The
// caller has to guarantee that `render_frame_host` lives at least as long as
// DidStopLoadingInterceptor.
class DidStopLoadingInterceptor : public mojom::FrameHostInterceptorForTesting {
public:
explicit DidStopLoadingInterceptor(RenderFrameHostImpl* render_frame_host)
: render_frame_host_(render_frame_host),
swapped_impl_(render_frame_host_->frame_host_receiver_for_testing(),
this) {}
~DidStopLoadingInterceptor() override = default;
DidStopLoadingInterceptor(const DidStopLoadingInterceptor&) = delete;
DidStopLoadingInterceptor& operator=(const DidStopLoadingInterceptor&) =
delete;
mojom::FrameHost* GetForwardingInterface() override {
return swapped_impl_.old_impl();
}
void DidStopLoading() override {
static_cast<RenderProcessHostImpl*>(render_frame_host_->GetProcess())
->mark_child_process_activity_time();
static_cast<mojom::FrameHost*>(render_frame_host_)->DidStopLoading();
}
private:
raw_ptr<RenderFrameHostImpl> render_frame_host_;
mojo::test::ScopedSwapImplForTesting<mojom::FrameHost> swapped_impl_;
};
// Test that get_process_idle_time() returns reasonable values when compared
// with time deltas measured locally.
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest, RenderIdleTime) {
EXPECT_TRUE(embedded_test_server()->Start());
base::TimeTicks start = base::TimeTicks::Now();
DidStopLoadingInterceptor interceptor(
static_cast<content::RenderFrameHostImpl*>(
shell()->web_contents()->GetPrimaryMainFrame()));
GURL test_url(embedded_test_server()->GetURL("/title1.html"));
EXPECT_TRUE(NavigateToURL(shell(), test_url));
base::TimeDelta renderer_td = shell()
->web_contents()
->GetPrimaryMainFrame()
->GetProcess()
->GetChildProcessIdleTime();
base::TimeDelta browser_td = base::TimeTicks::Now() - start;
EXPECT_TRUE(browser_td >= renderer_td);
}
class WebContentsDiscardBrowserTest : public WebContentsImplBrowserTest {
public:
WebContentsDiscardBrowserTest() {
scoped_feature_list_.InitAndEnableFeature(features::kWebContentsDiscard);
}
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
IN_PROC_BROWSER_TEST_F(WebContentsDiscardBrowserTest, DiscardRetainsTitle) {
ASSERT_TRUE(embedded_test_server()->Start());
// Navigate to an initial page.
const GURL initial_url =
embedded_test_server()->GetURL("/frame_tree/top.html");
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
// Update the tab title.
const std::u16string test_title(u"test_title");
WebContentsImpl* contents =
static_cast<WebContentsImpl*>(shell()->web_contents());
contents->UpdateTitleForEntry(
contents->GetController().GetLastCommittedEntry(), test_title);
EXPECT_EQ(test_title, contents->GetTitle());
// Discard the tab.
testing::NiceMock<MockWebContentsObserver> observer(contents);
EXPECT_CALL(observer, AboutToBeDiscarded(contents)).Times(1);
EXPECT_CALL(observer, WasDiscarded()).Times(1);
EXPECT_FALSE(contents->WasDiscarded());
contents->Discard();
EXPECT_TRUE(contents->WasDiscarded());
FrameTreeNode* root = contents->GetPrimaryFrameTree().root();
ASSERT_TRUE(
base::test::RunUntil([&]() { return 0u == root->child_count(); }));
// The title should remain unchanged post discard.
EXPECT_EQ(test_title, contents->GetTitle());
}
// Helper class that waits to receive a favicon from the renderer process.
class FaviconWaiter : public WebContentsObserver {
public:
explicit FaviconWaiter(WebContents* web_contents)
: WebContentsObserver(web_contents) {}
// WebContentsObserver:
void DidUpdateFaviconURL(
RenderFrameHost* render_frame_host,
const std::vector<blink::mojom::FaviconURLPtr>& candidates) override {
received_favicon_ = true;
run_loop_.Quit();
}
void Wait() {
if (received_favicon_) {
return;
}
run_loop_.Run();
}
private:
bool received_favicon_ = false;
base::RunLoop run_loop_;
};
IN_PROC_BROWSER_TEST_F(WebContentsDiscardBrowserTest, DiscardRetainsFavicon) {
ASSERT_TRUE(embedded_test_server()->Start());
// Navigate to an initial page.
const GURL initial_url =
embedded_test_server()->GetURL("/frame_tree/top.html");
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
WebContentsImpl* contents =
static_cast<WebContentsImpl*>(shell()->web_contents());
FaviconWaiter favicon_waiter(contents);
// Insert a favicon dynamically.
ASSERT_TRUE(
ExecJs(shell()->web_contents(),
"let l = document.createElement('link'); "
"l.rel='icon'; l.type='image/png'; l.href='single_face.jpg'; "
"document.head.appendChild(l)"));
// Wait until it's received by the browser process.
favicon_waiter.Wait();
EXPECT_EQ(1u, contents->GetFaviconURLs().size());
auto favicon_url = contents->GetFaviconURLs()[0]->icon_url;
// Discard the tab.
testing::NiceMock<MockWebContentsObserver> observer(contents);
EXPECT_CALL(observer, AboutToBeDiscarded(contents)).Times(1);
EXPECT_CALL(observer, WasDiscarded()).Times(1);
EXPECT_FALSE(contents->WasDiscarded());
contents->Discard();
EXPECT_TRUE(contents->WasDiscarded());
FrameTreeNode* root = contents->GetPrimaryFrameTree().root();
ASSERT_TRUE(
base::test::RunUntil([&]() { return 0u == root->child_count(); }));
// The favicon URLs should remain unchanged.
EXPECT_EQ(1u, contents->GetFaviconURLs().size());
EXPECT_THAT(favicon_url, contents->GetFaviconURLs()[0]->icon_url);
}
#if !BUILDFLAG(IS_ANDROID)
class WebContentsImplBrowserTestWindowControlsOverlay
: public WebContentsImplBrowserTest {
public:
void ValidateTitlebarAreaCSSValue(const std::string& name,
int expected_result) {
SCOPED_TRACE(name);
EXPECT_EQ(
expected_result,
EvalJs(shell()->web_contents(),
JsReplace(
"(() => {"
"const e = document.getElementById('target');"
"const style = window.getComputedStyle(e, null);"
"return Math.round(style.getPropertyValue($1).replace('px', "
"''));"
"})();",
name)));
}
void ValidateWindowsControlOverlayState(WebContents* web_contents,
const gfx::Rect& expected_rect,
int css_fallback_value) {
EXPECT_EQ(!expected_rect.IsEmpty(),
EvalJs(web_contents, "navigator.windowControlsOverlay.visible"));
EXPECT_EQ(
expected_rect.x(),
EvalJs(web_contents,
"navigator.windowControlsOverlay.getTitlebarAreaRect().x"));
EXPECT_EQ(
expected_rect.y(),
EvalJs(web_contents,
"navigator.windowControlsOverlay.getTitlebarAreaRect().y"));
EXPECT_EQ(
expected_rect.width(),
EvalJs(web_contents,
"navigator.windowControlsOverlay.getTitlebarAreaRect().width"));
EXPECT_EQ(
expected_rect.height(),
EvalJs(web_contents,
"navigator.windowControlsOverlay.getTitlebarAreaRect().height"));
// When the overlay is not visible, the environment variables should be
// undefined, and the the fallback value should be used.
gfx::Rect css_rect = expected_rect;
if (css_rect.IsEmpty()) {
css_rect.SetRect(css_fallback_value, css_fallback_value,
css_fallback_value, css_fallback_value);
}
ValidateTitlebarAreaCSSValue("left", css_rect.x());
ValidateTitlebarAreaCSSValue("top", css_rect.y());
ValidateTitlebarAreaCSSValue("width", css_rect.width());
ValidateTitlebarAreaCSSValue("height", css_rect.height());
}
void WaitForWindowControlsOverlayUpdate(
WebContents* web_contents,
const gfx::Rect& bounding_client_rect) {
EXPECT_TRUE(
ExecJs(web_contents->GetPrimaryMainFrame(),
"navigator.windowControlsOverlay.ongeometrychange = (e) => {"
" document.title = 'ongeometrychange'"
"}"));
web_contents->UpdateWindowControlsOverlay(bounding_client_rect);
TitleWatcher title_watcher(web_contents, u"ongeometrychange");
std::ignore = title_watcher.WaitAndGetTitle();
}
};
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTestWindowControlsOverlay,
ValidateWindowControlsOverlayToggleOn) {
auto* web_contents = shell()->web_contents();
GURL url(
R"(data:text/html,<body><div id=target style="position=absolute;
left: env(titlebar-area-x, 50px);
top: env(titlebar-area-y, 50px);
width: env(titlebar-area-width, 50px);
height: env(titlebar-area-height, 50px);"></div></body>)");
EXPECT_TRUE(NavigateToURL(shell(), url));
// In the initial state, the overlay is not visible and the bounding rect is
// empty.
ValidateWindowsControlOverlayState(web_contents, gfx::Rect(), 50);
// Update bounds and ensure that JS APIs and CSS variables are updated.
gfx::Rect bounding_client_rect(1, 2, 3, 4);
WaitForWindowControlsOverlayUpdate(web_contents, bounding_client_rect);
ValidateWindowsControlOverlayState(web_contents, bounding_client_rect, 50);
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTestWindowControlsOverlay,
ValidateWindowControlsOverlayToggleOff) {
auto* web_contents = shell()->web_contents();
GURL url(
R"(data:text/html,<body><div id=target style="position=absolute;
left: env(titlebar-area-x, 55px);
top: env(titlebar-area-y, 55px);
width: env(titlebar-area-width, 55px);
height: env(titlebar-area-height, 55px);"></div></body>)");
EXPECT_TRUE(NavigateToURL(shell(), url));
// Update bounds and ensure that JS APIs and CSS variables are updated.
gfx::Rect bounding_client_rect(0, 0, 100, 32);
WaitForWindowControlsOverlayUpdate(web_contents, bounding_client_rect);
ValidateWindowsControlOverlayState(web_contents, bounding_client_rect, 55);
// Now toggle Windows Controls Overlay off.
gfx::Rect empty_rect;
WaitForWindowControlsOverlayUpdate(web_contents, empty_rect);
ValidateWindowsControlOverlayState(web_contents, empty_rect, 55);
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTestWindowControlsOverlay,
GeometryChangeEvent) {
auto* web_contents = shell()->web_contents();
GURL url(url::kAboutBlankURL);
EXPECT_TRUE(NavigateToURL(shell(), url));
EXPECT_TRUE(
ExecJs(web_contents->GetPrimaryMainFrame(),
"geometrychangeCount = 0;"
"navigator.windowControlsOverlay.ongeometrychange = (e) => {"
" geometrychangeCount++;"
" rect = e.titlebarAreaRect;"
" visible = e.visible;"
" document.title = 'ongeometrychange' + geometrychangeCount"
"}"));
WaitForLoadStop(web_contents);
// Ensure the "geometrychange" event is only fired when the the window
// controls overlay bounds are updated.
EXPECT_EQ(0, EvalJs(web_contents, "geometrychangeCount"));
// Information about the bounds should be updated.
gfx::Rect bounding_client_rect = gfx::Rect(2, 3, 4, 5);
web_contents->UpdateWindowControlsOverlay(bounding_client_rect);
TitleWatcher title_watcher(web_contents, u"ongeometrychange1");
std::ignore = title_watcher.WaitAndGetTitle();
// Expect the "geometrychange" event to have fired once.
EXPECT_EQ(1, EvalJs(web_contents, "geometrychangeCount"));
// Validate the event payload.
EXPECT_EQ(true, EvalJs(web_contents, "visible"));
EXPECT_EQ(bounding_client_rect.x(), EvalJs(web_contents, "rect.x;"));
EXPECT_EQ(bounding_client_rect.y(), EvalJs(web_contents, "rect.y"));
EXPECT_EQ(bounding_client_rect.width(), EvalJs(web_contents, "rect.width"));
EXPECT_EQ(bounding_client_rect.height(), EvalJs(web_contents, "rect.height"));
}
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTestWindowControlsOverlay,
ValidatePageScaleChangesInfoAndFiresEvent) {
auto* web_contents = shell()->web_contents();
GURL url(
R"(data:text/html,<body><div id=target style="position=absolute;
left: env(titlebar-area-x, 60px);
top: env(titlebar-area-y, 60px);
width: env(titlebar-area-width, 60px);
height: env(titlebar-area-height, 60px);"></div></body>)");
EXPECT_TRUE(NavigateToURL(shell(), url));
WaitForLoadStop(web_contents);
gfx::Rect bounding_client_rect = gfx::Rect(5, 10, 15, 20);
WaitForWindowControlsOverlayUpdate(web_contents, bounding_client_rect);
// Update zoom level, confirm the "geometrychange" event is fired,
// and CSS variables are updated
EXPECT_TRUE(
ExecJs(web_contents->GetPrimaryMainFrame(),
"geometrychangeCount = 0;"
"navigator.windowControlsOverlay.ongeometrychange = (e) => {"
" geometrychangeCount++;"
" rect = e.titlebarAreaRect;"
" visible = e.visible;"
" document.title = 'ongeometrychangefromzoomlevel'"
"}"));
content::HostZoomMap::SetZoomLevel(web_contents, 1.5);
TitleWatcher title_watcher(web_contents, u"ongeometrychangefromzoomlevel");
std::ignore = title_watcher.WaitAndGetTitle();
// Validate the event payload.
double zoom_factor = blink::ZoomLevelToZoomFactor(
content::HostZoomMap::GetZoomLevel(web_contents));
gfx::Rect scaled_rect =
gfx::ScaleToEnclosingRect(bounding_client_rect, 1.0f / zoom_factor);
EXPECT_EQ(true, EvalJs(web_contents, "visible"));
EXPECT_EQ(scaled_rect.x(), EvalJs(web_contents, "rect.x"));
EXPECT_EQ(scaled_rect.y(), EvalJs(web_contents, "rect.y"));
EXPECT_EQ(scaled_rect.width(), EvalJs(web_contents, "rect.width"));
EXPECT_EQ(scaled_rect.height(), EvalJs(web_contents, "rect.height"));
ValidateWindowsControlOverlayState(web_contents, scaled_rect, 60);
}
class WebContentsImplBrowserTestWindowControlsOverlayNonOneDeviceScaleFactor
: public WebContentsImplBrowserTestWindowControlsOverlay {
public:
void SetUp() override {
#if BUILDFLAG(IS_MAC)
// Device scale factor on MacOSX is always an integer.
EnablePixelOutput(2.0f);
#else
EnablePixelOutput(1.25f);
#endif
WebContentsImplBrowserTestWindowControlsOverlay::SetUp();
}
};
IN_PROC_BROWSER_TEST_F(
WebContentsImplBrowserTestWindowControlsOverlayNonOneDeviceScaleFactor,
ValidateScaledCorrectly) {
auto* web_contents = shell()->web_contents();
GURL url(
R"(data:text/html,<body><div id=target style="position=absolute;
left: env(titlebar-area-x, 70px);
top: env(titlebar-area-y, 70px);
width: env(titlebar-area-width, 70px);
height: env(titlebar-area-height, 70px);"></div></body>)");
EXPECT_TRUE(NavigateToURL(shell(), url));
WaitForLoadStop(web_contents);
#if BUILDFLAG(IS_MAC)
// Device scale factor on MacOSX is always an integer.
ASSERT_EQ(2.0f,
web_contents->GetRenderWidgetHostView()->GetDeviceScaleFactor());
#else
ASSERT_EQ(1.25f,
web_contents->GetRenderWidgetHostView()->GetDeviceScaleFactor());
#endif
gfx::Rect bounding_client_rect = gfx::Rect(5, 10, 15, 20);
WaitForWindowControlsOverlayUpdate(web_contents, bounding_client_rect);
ValidateWindowsControlOverlayState(web_contents, bounding_client_rect, 70);
}
IN_PROC_BROWSER_TEST_F(
WebContentsImplBrowserTestWindowControlsOverlayNonOneDeviceScaleFactor,
ValidateScaledCorrectlyAfterNavigate) {
auto* web_contents = shell()->web_contents();
GURL url(
R"(data:text/html,<body><div id=target style="position=absolute;
left: env(titlebar-area-x, 70px);
top: env(titlebar-area-y, 70px);
width: env(titlebar-area-width, 70px);
height: env(titlebar-area-height, 70px);"><p>Page1</p></div></body>)");
EXPECT_TRUE(NavigateToURL(shell(), url));
WaitForLoadStop(web_contents);
#if BUILDFLAG(IS_MAC)
// Device scale factor on MacOSX is always an integer.
ASSERT_EQ(2.0f,
web_contents->GetRenderWidgetHostView()->GetDeviceScaleFactor());
#else
ASSERT_EQ(1.25f,
web_contents->GetRenderWidgetHostView()->GetDeviceScaleFactor());
#endif
gfx::Rect bounding_client_rect = gfx::Rect(5, 10, 15, 20);
WaitForWindowControlsOverlayUpdate(web_contents, bounding_client_rect);
ValidateWindowsControlOverlayState(web_contents, bounding_client_rect, 70);
// Validate that the |bounding_client_rect| is scaled correctly on navigation.
GURL second_url(
R"(data:text/html,<body><div id=target style="position=absolute;
left: env(titlebar-area-x, 70px);
top: env(titlebar-area-y, 70px);
width: env(titlebar-area-width, 70px);
height: env(titlebar-area-height, 70px);"><p>Page2</p></div></body>)");
EXPECT_TRUE(NavigateToURL(shell(), second_url));
WaitForLoadStop(web_contents);
ValidateWindowsControlOverlayState(web_contents, bounding_client_rect, 70);
}
#endif // !BUILDFLAG(IS_ANDROID)
class RenderFrameCreatedObserver : public WebContentsObserver {
public:
explicit RenderFrameCreatedObserver(WebContents* web_contents)
: WebContentsObserver(web_contents) {}
~RenderFrameCreatedObserver() override = default;
void WaitForRenderFrameCreated() { run_loop_.Run(); }
void RenderFrameCreated(RenderFrameHost* host) override { run_loop_.Quit(); }
private:
base::RunLoop run_loop_;
};
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
ReinitializeMainFrameForCrashedTab) {
ASSERT_TRUE(embedded_test_server()->Start());
TestNavigationObserver load_observer(shell()->web_contents());
EXPECT_TRUE(
NavigateToURL(shell(), embedded_test_server()->GetURL("/title1.html")));
load_observer.Wait();
CrashTab(shell()->web_contents());
EXPECT_TRUE(shell()->web_contents()->IsCrashed());
RenderFrameCreatedObserver frame_created_obs(shell()->web_contents());
static_cast<WebContentsImpl*>(shell()->web_contents())
->GetPrimaryFrameTree()
.root()
->render_manager()
->InitializeMainRenderFrameForImmediateUse();
frame_created_obs.WaitForRenderFrameCreated();
EXPECT_FALSE(shell()->web_contents()->IsCrashed());
}
// Check that there's no crash if a new window is set to defer navigations (for
// example, this is done on Android Webview and for <webview> guests), then the
// renderer process crashes while there's a deferred new window navigation in
// place, and then navigations are resumed. Prior to fixing
// https://crbug.com/1487110, the deferred navigation was allowed to proceed,
// performing an early RenderFrameHost swap and hitting a bug while clearing
// the deferred navigation state. Now, the deferred navigation should be
// canceled when the renderer process dies.
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
DeferredWindowOpenNavigationIsResumedWithEarlySwap) {
// Force WebContents in a new Shell to defer new navigations until the
// delegate is set.
shell()->set_delay_popup_contents_delegate_for_testing(true);
// Load an initial page.
ASSERT_TRUE(embedded_test_server()->Start());
GURL url(embedded_test_server()->GetURL("/title1.html"));
EXPECT_TRUE(NavigateToURL(shell(), url));
// Open a popup to a same-site URL via window.open.
ShellAddedObserver new_shell_observer;
EXPECT_TRUE(ExecJs(shell(), JsReplace("window.open($1);", url)));
Shell* new_shell = new_shell_observer.GetShell();
WebContents* new_contents = new_shell->web_contents();
// The navigation in the new popup should be deferred.
EXPECT_TRUE(WaitForLoadStop(new_contents));
EXPECT_TRUE(new_contents->GetController().IsInitialBlankNavigation());
EXPECT_TRUE(new_contents->GetLastCommittedURL().is_empty());
// Set the new shell's delegate now. This doesn't resume the navigation just
// yet.
EXPECT_FALSE(new_contents->GetDelegate());
new_contents->SetDelegate(new_shell);
// Crash the renderer process. This should clear the deferred navigation
// state. If this wasn't done due to a bug, it would also force the resumed
// navigation to use the early RenderFrameHost swap.
{
RenderProcessHost* popup_process =
new_contents->GetPrimaryMainFrame()->GetProcess();
RenderProcessHostWatcher crash_observer(
popup_process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
EXPECT_TRUE(popup_process->Shutdown(0));
crash_observer.Wait();
}
// Resume the navigation and verify that it gets canceled. Ensure this
// doesn't crash.
NavigationHandleObserver handle_observer(new_contents, url);
new_contents->ResumeLoadingCreatedWebContents();
EXPECT_TRUE(WaitForLoadStop(new_contents));
EXPECT_FALSE(handle_observer.has_committed());
EXPECT_TRUE(new_contents->GetController().IsInitialBlankNavigation());
EXPECT_TRUE(new_contents->GetLastCommittedURL().is_empty());
}
namespace {
class MediaWaiter : public WebContentsObserver {
public:
explicit MediaWaiter(WebContents* web_contents)
: WebContentsObserver(web_contents) {}
void MediaStartedPlaying(const MediaPlayerInfo& video_type,
const MediaPlayerId& id) override {
started_media_id_ = id;
;
media_started_playing_loop_.Quit();
}
void MediaDestroyed(const MediaPlayerId& id) override {
EXPECT_EQ(id, started_media_id_);
media_destroyed_loop_.Quit();
}
void WaitForMediaStartedPlaying() { media_started_playing_loop_.Run(); }
void WaitForMediaDestroyed() { media_destroyed_loop_.Run(); }
private:
std::optional<MediaPlayerId> started_media_id_;
base::RunLoop media_started_playing_loop_;
base::RunLoop media_destroyed_loop_;
};
} // namespace
IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest,
MediaDestroyedOnRendererCrash) {
ASSERT_TRUE(embedded_test_server()->Start());
MediaWaiter waiter(shell()->web_contents());
EXPECT_TRUE(NavigateToURL(shell(), embedded_test_server()->GetURL(
"/media/video-player-autoplay.html")));
waiter.WaitForMediaStartedPlaying();
CrashTab(shell()->web_contents());
EXPECT_TRUE(shell()->web_contents()->IsCrashed());
// This will not hang if MediaDestroyed() is dispatched as expected when a
// frame with a media player is destroyed.
waiter.WaitForMediaDestroyed();
}
class WebContentsImplInsecureLocalhostBrowserTest
: public WebContentsImplBrowserTest {
protected:
void SetUpOnMainThread() override {
WebContentsImplBrowserTest::SetUpOnMainThread();
https_server_.AddDefaultHandlers(GetTestDataFilePath());
}
net::EmbeddedTestServer& https_server() { return https_server_; }
private:
net::EmbeddedTestServer https_server_{net::EmbeddedTestServer::TYPE_HTTPS};
};
IN_PROC_BROWSER_TEST_F(WebContentsImplInsecureLocalhostBrowserTest,
BlocksByDefault) {
https_server().SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED);
ASSERT_TRUE(https_server().Start());
GURL url = https_server().GetURL("/title1.html");
NavigateToURLBlockUntilNavigationsComplete(shell(), url, 1);
EXPECT_TRUE(
IsLastCommittedEntryOfPageType(shell()->web_contents(), PAGE_TYPE_ERROR));
}
class WebContentsImplAllowInsecureLocalhostBrowserTest
: public WebContentsImplInsecureLocalhostBrowserTest {
protected:
void SetUpCommandLine(base::CommandLine* command_line) override {
command_line->AppendSwitch(switches::kAllowInsecureLocalhost);
}
};
IN_PROC_BROWSER_TEST_F(WebContentsImplAllowInsecureLocalhostBrowserTest,
WarnsWithSwitch) {
https_server().SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED);
ASSERT_TRUE(https_server().Start());
GURL url = https_server().GetURL("/title1.html");
WebContentsConsoleObserver observer(shell()->web_contents());
observer.SetFilter(base::BindRepeating(
[](const GURL& expected_url,
const WebContentsConsoleObserver::Message& message) {
return message.source_frame->GetLastCommittedURL() == expected_url;
},
url));
observer.SetPattern("*SSL certificate*");
ASSERT_TRUE(NavigateToURL(shell(), url));
ASSERT_TRUE(observer.Wait());
}
class WebContentsPrerenderBrowserTest : public WebContentsImplBrowserTest {
public:
WebContentsPrerenderBrowserTest()
: prerender_helper_(
base::BindRepeating(&WebContentsPrerenderBrowserTest::web_contents,
base::Unretained(this))) {}
~WebContentsPrerenderBrowserTest() override = default;
// PrerenderTestHelper requires access to WebContents object.
WebContents* web_contents() { return shell()->web_contents(); }
// Testing functionality requires access to WebContentsImpl object.
WebContentsImpl* web_contents_impl() {
return static_cast<WebContentsImpl*>(web_contents());
}
content::test::PrerenderTestHelper& prerender_helper() {
return prerender_helper_;
}
private:
content::test::PrerenderTestHelper prerender_helper_;
};
class TestWebContentsDestructionObserver : public WebContentsObserver {
public:
explicit TestWebContentsDestructionObserver(WebContentsImpl* web_contents)
: content::WebContentsObserver(web_contents) {}
TestWebContentsDestructionObserver(
const TestWebContentsDestructionObserver&) = delete;
TestWebContentsDestructionObserver& operator=(
const TestWebContentsDestructionObserver&) = delete;
~TestWebContentsDestructionObserver() override = default;
void WebContentsDestroyed() override {
// This has been added to validate that it's safe to call this method
// within a WebContentsDestroyed observer. We want to verify that
// this does not cause a crash.
static_cast<WebContentsImpl*>(web_contents())
->ForEachFrameTree([](FrameTree& frame_tree) {});
}
};
IN_PROC_BROWSER_TEST_F(WebContentsPrerenderBrowserTest,
SafeToCallForEachFrameTreeDuringDestruction) {
ASSERT_TRUE(embedded_test_server()->Start());
const GURL url_a(
embedded_test_server()->GetURL("a.com", "/page_with_iframe.html"));
ASSERT_TRUE(NavigateToURL(shell(), url_a));
TestWebContentsDestructionObserver test_web_contents_observer(
web_contents_impl());
WebContentsDestroyedWatcher close_observer(web_contents_impl());
web_contents_impl()->DispatchBeforeUnload(false /* auto_cancel */);
close_observer.Wait();
}
IN_PROC_BROWSER_TEST_F(WebContentsPrerenderBrowserTest,
GetContentsMimeTypeForEachPage) {
ASSERT_TRUE(embedded_test_server()->Start());
const GURL initial_url = embedded_test_server()->GetURL("/title1.html");
// Navigate to an initial page.
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
// Prerender a page that has a MIME type, text/plain.
const GURL prerendering_url = embedded_test_server()->GetURL("/plain.txt");
FrameTreeNodeId host_id = prerender_helper().AddPrerender(prerendering_url);
// Check MIME type for each page.
EXPECT_EQ("text/html",
web_contents()->GetPrimaryPage().GetContentsMimeType());
EXPECT_EQ("text/plain", prerender_helper()
.GetPrerenderedMainFrameHost(host_id)
->GetPage()
.GetContentsMimeType());
// WebContents API should return the MIME type of the primary page.
EXPECT_EQ("text/html", shell()->web_contents()->GetContentsMimeType());
}
class WebContentsPrerenderWithDiscardBrowserTest
: public WebContentsPrerenderBrowserTest {
public:
WebContentsPrerenderWithDiscardBrowserTest() {
scoped_feature_list_.InitAndEnableFeature(features::kWebContentsDiscard);
}
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
IN_PROC_BROWSER_TEST_F(WebContentsPrerenderWithDiscardBrowserTest,
DiscardCancelsPrerendering) {
ASSERT_TRUE(embedded_test_server()->Start());
// Navigate to an initial page.
const GURL initial_url = embedded_test_server()->GetURL("/title1.html");
ASSERT_TRUE(NavigateToURL(shell(), initial_url));
// Prerender a page.
const GURL prerendering_url = embedded_test_server()->GetURL("/plain.txt");
const FrameTreeNodeId host_id =
prerender_helper().AddPrerender(prerendering_url);
PrerenderHostRegistry* registry =
static_cast<WebContentsImpl*>(web_contents())->GetPrerenderHostRegistry();
EXPECT_TRUE(registry->FindNonReservedHostById(host_id));
// Discard the tab, this should immediately clear all prerender frame trees.
testing::NiceMock<MockWebContentsObserver> observer(web_contents());
EXPECT_CALL(observer, AboutToBeDiscarded(web_contents())).Times(1);
EXPECT_CALL(observer, WasDiscarded()).Times(1);
EXPECT_FALSE(web_contents()->WasDiscarded());
web_contents()->Discard();
EXPECT_TRUE(web_contents()->WasDiscarded());
EXPECT_FALSE(registry->FindNonReservedHostById(host_id));
}
class WebContentsFencedFrameBrowserTest : public WebContentsImplBrowserTest {
public:
WebContentsFencedFrameBrowserTest() = default;
~WebContentsFencedFrameBrowserTest() override = default;
WebContentsImpl* web_contents() {
return static_cast<WebContentsImpl*>(shell()->web_contents());
}
test::FencedFrameTestHelper& fenced_frame_test_helper() {
return fenced_frame_test_helper_;
}
private:
content::test::FencedFrameTestHelper fenced_frame_test_helper_;
};
// Tests that DidUpdateFaviconURL() works only with the primary page by checking
// if it's not called on the fenced frame loading.
IN_PROC_BROWSER_TEST_F(WebContentsFencedFrameBrowserTest, UpdateFavicon) {
ASSERT_TRUE(embedded_test_server()->Start());
testing::NiceMock<MockWebContentsObserver> observer(web_contents());
const GURL main_url =
embedded_test_server()->GetURL("fencedframe.test", "/title1.html");
RenderFrameHost* primary_rfh = web_contents()->GetPrimaryMainFrame();
EXPECT_CALL(observer, DidUpdateFaviconURL(primary_rfh, testing::_));
ASSERT_TRUE(NavigateToURL(shell(), main_url));
ASSERT_TRUE(WaitForLoadStop(web_contents()));
// Create fenced frame.
const GURL fenced_frame_url = embedded_test_server()->GetURL(
"fencedframe.test", "/fenced_frames/title1.html");
RenderFrameHost* inner_fenced_frame_rfh =
fenced_frame_test_helper().CreateFencedFrame(primary_rfh,
fenced_frame_url);
EXPECT_CALL(observer, DidUpdateFaviconURL(inner_fenced_frame_rfh, testing::_))
.Times(0);
}
// Tests that pages are still visible after a page is navigated away
// from a page that contained a fenced frame. (crbug.com/1265615)
IN_PROC_BROWSER_TEST_F(WebContentsFencedFrameBrowserTest, RemainsVisible) {
ASSERT_TRUE(embedded_test_server()->Start());
const GURL main_url =
embedded_test_server()->GetURL("fencedframe.test", "/title1.html");
RenderFrameHost* primary_rfh = web_contents()->GetPrimaryMainFrame();
ASSERT_TRUE(NavigateToURL(shell(), main_url));
ASSERT_TRUE(WaitForLoadStop(web_contents()));
EXPECT_EQ(Visibility::VISIBLE, web_contents()->GetVisibility());
// Create fenced frame.
const GURL fenced_frame_url = embedded_test_server()->GetURL(
"fencedframe.test", "/fenced_frames/title1.html");
content::RenderFrameHost* fenced_frame_host =
fenced_frame_test_helper().CreateFencedFrame(primary_rfh,
fenced_frame_url);
EXPECT_NE(nullptr, fenced_frame_host);
const GURL same_origin_url =
embedded_test_server()->GetURL("fencedframe.test", "/title3.html");
ASSERT_TRUE(NavigateToURL(shell(), same_origin_url));
ASSERT_TRUE(WaitForLoadStop(web_contents()));
EXPECT_EQ(Visibility::VISIBLE, web_contents()->GetVisibility());
}
// Tests that AXTreeIDForMainFrameHasChanged() works only with the primary page
// by checking if it's not called on the fenced frame loading.
IN_PROC_BROWSER_TEST_F(WebContentsFencedFrameBrowserTest, DoNotUpdateAXTree) {
ASSERT_TRUE(embedded_test_server()->Start());
testing::NiceMock<MockWebContentsObserver> observer(web_contents());
const GURL main_url =
embedded_test_server()->GetURL("fencedframe.test", "/title1.html");
EXPECT_CALL(observer, AXTreeIDForMainFrameHasChanged())
.Times(testing::AtLeast(1));
ASSERT_TRUE(NavigateToURL(shell(), main_url));
testing::Mock::VerifyAndClearExpectations(&observer);
// Create fenced frame.
const GURL fenced_frame_url = embedded_test_server()->GetURL(
"fencedframe.test", "/fenced_frames/title1.html");
EXPECT_CALL(observer, AXTreeIDForMainFrameHasChanged()).Times(0);
RenderFrameHost* fenced_frame_rfh =
fenced_frame_test_helper().CreateFencedFrame(
web_contents()->GetPrimaryMainFrame(), fenced_frame_url);
EXPECT_NE(nullptr, fenced_frame_rfh);
}
class MediaWatchTimeChangedDelegate : public WebContentsDelegate {
public:
explicit MediaWatchTimeChangedDelegate(WebContents* contents)
: watch_time_(GURL(),
GURL(),
base::TimeDelta(),
base::TimeDelta(),
false,
false) {
contents->SetDelegate(this);
}
~MediaWatchTimeChangedDelegate() override = default;
MediaWatchTimeChangedDelegate(const MediaWatchTimeChangedDelegate&) = delete;
MediaWatchTimeChangedDelegate& operator=(
const MediaWatchTimeChangedDelegate&) = delete;
// WebContentsDelegate:
void MediaWatchTimeChanged(const MediaPlayerWatchTime& watch_time) override {
watch_time_ = watch_time;
}
const MediaPlayerWatchTime& watch_time() { return watch_time_; }
private:
MediaPlayerWatchTime watch_time_;
};
// Tests that a media in a fenced frame reports the watch time with the url from
// the top level frame.
IN_PROC_BROWSER_TEST_F(WebContentsFencedFrameBrowserTest,
MediaWatchTimeCallback) {
using UkmEntry = ukm::builders::Media_WebMediaPlayerState;
ukm::TestAutoSetUkmRecorder test_recorder;
MediaWatchTimeChangedDelegate delegate(web_contents());
net::test_server::EmbeddedTestServerHandle test_server_handle;
ASSERT_TRUE(test_server_handle =
embedded_test_server()->StartAndReturnHandle());
const GURL top_url = embedded_test_server()->GetURL("/empty.html");
ASSERT_TRUE(NavigateToURL(shell(), top_url));
// Create a fenced frame.
GURL fenced_frame_url(
embedded_test_server()->GetURL("/fenced_frames/title1.html"));
content::RenderFrameHost* fenced_frame =
fenced_frame_test_helper().CreateFencedFrame(
web_contents()->GetPrimaryMainFrame(), fenced_frame_url);
// Insert a video element.
EXPECT_TRUE(ExecJs(fenced_frame, R"(
var video = document.createElement('video');
document.body.appendChild(video);
video.src = '../media/bear.webm';
video.play();
)"));
base::RunLoop run_loop;
test_recorder.SetOnAddEntryCallback(UkmEntry::kEntryName,
run_loop.QuitClosure());
// Leave the current page to check the UKM records.
fenced_frame_test_helper().NavigateFrameInFencedFrameTree(
fenced_frame,
embedded_test_server()->GetURL("a.com", "/fenced_frames/title1.html"));
ASSERT_TRUE(NavigateToURL(shell(), GURL(url::kAboutBlankURL)));
run_loop.Run();
const auto& entries = test_recorder.GetEntriesByName(UkmEntry::kEntryName);
EXPECT_EQ(1u, entries.size());
for (const ukm::mojom::UkmEntry* entry : entries) {
test_recorder.ExpectEntryMetric(entry, UkmEntry::kIsTopFrameName, false);
}
}
} // namespace content
|