'
- */
- function wrap(value, wrapper) {
- return partial(castFunction(wrapper), value);
- }
-
- /*------------------------------------------------------------------------*/
-
- /**
- * Casts `value` as an array if it's not one.
- *
- * @static
- * @memberOf _
- * @since 4.4.0
- * @category Lang
- * @param {*} value The value to inspect.
- * @returns {Array} Returns the cast array.
- * @example
- *
- * _.castArray(1);
- * // => [1]
- *
- * _.castArray({ 'a': 1 });
- * // => [{ 'a': 1 }]
- *
- * _.castArray('abc');
- * // => ['abc']
- *
- * _.castArray(null);
- * // => [null]
- *
- * _.castArray(undefined);
- * // => [undefined]
- *
- * _.castArray();
- * // => []
- *
- * var array = [1, 2, 3];
- * console.log(_.castArray(array) === array);
- * // => true
- */
- function castArray() {
- if (!arguments.length) {
- return [];
- }
- var value = arguments[0];
- return isArray(value) ? value : [value];
- }
-
- /**
- * Creates a shallow clone of `value`.
- *
- * **Note:** This method is loosely based on the
- * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm)
- * and supports cloning arrays, array buffers, booleans, date objects, maps,
- * numbers, `Object` objects, regexes, sets, strings, symbols, and typed
- * arrays. The own enumerable properties of `arguments` objects are cloned
- * as plain objects. An empty object is returned for uncloneable values such
- * as error objects, functions, DOM nodes, and WeakMaps.
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Lang
- * @param {*} value The value to clone.
- * @returns {*} Returns the cloned value.
- * @see _.cloneDeep
- * @example
- *
- * var objects = [{ 'a': 1 }, { 'b': 2 }];
- *
- * var shallow = _.clone(objects);
- * console.log(shallow[0] === objects[0]);
- * // => true
- */
- function clone(value) {
- return baseClone(value, CLONE_SYMBOLS_FLAG);
- }
-
- /**
- * This method is like `_.clone` except that it accepts `customizer` which
- * is invoked to produce the cloned value. If `customizer` returns `undefined`,
- * cloning is handled by the method instead. The `customizer` is invoked with
- * up to four arguments; (value [, index|key, object, stack]).
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to clone.
- * @param {Function} [customizer] The function to customize cloning.
- * @returns {*} Returns the cloned value.
- * @see _.cloneDeepWith
- * @example
- *
- * function customizer(value) {
- * if (_.isElement(value)) {
- * return value.cloneNode(false);
- * }
- * }
- *
- * var el = _.cloneWith(document.body, customizer);
- *
- * console.log(el === document.body);
- * // => false
- * console.log(el.nodeName);
- * // => 'BODY'
- * console.log(el.childNodes.length);
- * // => 0
- */
- function cloneWith(value, customizer) {
- customizer = typeof customizer == 'function' ? customizer : undefined;
- return baseClone(value, CLONE_SYMBOLS_FLAG, customizer);
- }
-
- /**
- * This method is like `_.clone` except that it recursively clones `value`.
- *
- * @static
- * @memberOf _
- * @since 1.0.0
- * @category Lang
- * @param {*} value The value to recursively clone.
- * @returns {*} Returns the deep cloned value.
- * @see _.clone
- * @example
- *
- * var objects = [{ 'a': 1 }, { 'b': 2 }];
- *
- * var deep = _.cloneDeep(objects);
- * console.log(deep[0] === objects[0]);
- * // => false
- */
- function cloneDeep(value) {
- return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG);
- }
-
- /**
- * This method is like `_.cloneWith` except that it recursively clones `value`.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to recursively clone.
- * @param {Function} [customizer] The function to customize cloning.
- * @returns {*} Returns the deep cloned value.
- * @see _.cloneWith
- * @example
- *
- * function customizer(value) {
- * if (_.isElement(value)) {
- * return value.cloneNode(true);
- * }
- * }
- *
- * var el = _.cloneDeepWith(document.body, customizer);
- *
- * console.log(el === document.body);
- * // => false
- * console.log(el.nodeName);
- * // => 'BODY'
- * console.log(el.childNodes.length);
- * // => 20
- */
- function cloneDeepWith(value, customizer) {
- customizer = typeof customizer == 'function' ? customizer : undefined;
- return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer);
- }
-
- /**
- * Checks if `object` conforms to `source` by invoking the predicate
- * properties of `source` with the corresponding property values of `object`.
- *
- * **Note:** This method is equivalent to `_.conforms` when `source` is
- * partially applied.
- *
- * @static
- * @memberOf _
- * @since 4.14.0
- * @category Lang
- * @param {Object} object The object to inspect.
- * @param {Object} source The object of property predicates to conform to.
- * @returns {boolean} Returns `true` if `object` conforms, else `false`.
- * @example
- *
- * var object = { 'a': 1, 'b': 2 };
- *
- * _.conformsTo(object, { 'b': function(n) { return n > 1; } });
- * // => true
- *
- * _.conformsTo(object, { 'b': function(n) { return n > 2; } });
- * // => false
- */
- function conformsTo(object, source) {
- return source == null || baseConformsTo(object, source, keys(source));
- }
-
- /**
- * Performs a
- * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
- * comparison between two values to determine if they are equivalent.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to compare.
- * @param {*} other The other value to compare.
- * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
- * @example
- *
- * var object = { 'a': 1 };
- * var other = { 'a': 1 };
- *
- * _.eq(object, object);
- * // => true
- *
- * _.eq(object, other);
- * // => false
- *
- * _.eq('a', 'a');
- * // => true
- *
- * _.eq('a', Object('a'));
- * // => false
- *
- * _.eq(NaN, NaN);
- * // => true
- */
- function eq(value, other) {
- return value === other || (value !== value && other !== other);
- }
-
- /**
- * Checks if `value` is greater than `other`.
- *
- * @static
- * @memberOf _
- * @since 3.9.0
- * @category Lang
- * @param {*} value The value to compare.
- * @param {*} other The other value to compare.
- * @returns {boolean} Returns `true` if `value` is greater than `other`,
- * else `false`.
- * @see _.lt
- * @example
- *
- * _.gt(3, 1);
- * // => true
- *
- * _.gt(3, 3);
- * // => false
- *
- * _.gt(1, 3);
- * // => false
- */
- var gt = createRelationalOperation(baseGt);
-
- /**
- * Checks if `value` is greater than or equal to `other`.
- *
- * @static
- * @memberOf _
- * @since 3.9.0
- * @category Lang
- * @param {*} value The value to compare.
- * @param {*} other The other value to compare.
- * @returns {boolean} Returns `true` if `value` is greater than or equal to
- * `other`, else `false`.
- * @see _.lte
- * @example
- *
- * _.gte(3, 1);
- * // => true
- *
- * _.gte(3, 3);
- * // => true
- *
- * _.gte(1, 3);
- * // => false
- */
- var gte = createRelationalOperation(function(value, other) {
- return value >= other;
- });
-
- /**
- * Checks if `value` is likely an `arguments` object.
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is an `arguments` object,
- * else `false`.
- * @example
- *
- * _.isArguments(function() { return arguments; }());
- * // => true
- *
- * _.isArguments([1, 2, 3]);
- * // => false
- */
- var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {
- return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&
- !propertyIsEnumerable.call(value, 'callee');
- };
-
- /**
- * Checks if `value` is classified as an `Array` object.
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is an array, else `false`.
- * @example
- *
- * _.isArray([1, 2, 3]);
- * // => true
- *
- * _.isArray(document.body.children);
- * // => false
- *
- * _.isArray('abc');
- * // => false
- *
- * _.isArray(_.noop);
- * // => false
- */
- var isArray = Array.isArray;
-
- /**
- * Checks if `value` is classified as an `ArrayBuffer` object.
- *
- * @static
- * @memberOf _
- * @since 4.3.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`.
- * @example
- *
- * _.isArrayBuffer(new ArrayBuffer(2));
- * // => true
- *
- * _.isArrayBuffer(new Array(2));
- * // => false
- */
- var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer;
-
- /**
- * Checks if `value` is array-like. A value is considered array-like if it's
- * not a function and has a `value.length` that's an integer greater than or
- * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
- * @example
- *
- * _.isArrayLike([1, 2, 3]);
- * // => true
- *
- * _.isArrayLike(document.body.children);
- * // => true
- *
- * _.isArrayLike('abc');
- * // => true
- *
- * _.isArrayLike(_.noop);
- * // => false
- */
- function isArrayLike(value) {
- return value != null && isLength(value.length) && !isFunction(value);
- }
-
- /**
- * This method is like `_.isArrayLike` except that it also checks if `value`
- * is an object.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is an array-like object,
- * else `false`.
- * @example
- *
- * _.isArrayLikeObject([1, 2, 3]);
- * // => true
- *
- * _.isArrayLikeObject(document.body.children);
- * // => true
- *
- * _.isArrayLikeObject('abc');
- * // => false
- *
- * _.isArrayLikeObject(_.noop);
- * // => false
- */
- function isArrayLikeObject(value) {
- return isObjectLike(value) && isArrayLike(value);
- }
-
- /**
- * Checks if `value` is classified as a boolean primitive or object.
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a boolean, else `false`.
- * @example
- *
- * _.isBoolean(false);
- * // => true
- *
- * _.isBoolean(null);
- * // => false
- */
- function isBoolean(value) {
- return value === true || value === false ||
- (isObjectLike(value) && baseGetTag(value) == boolTag);
- }
-
- /**
- * Checks if `value` is a buffer.
- *
- * @static
- * @memberOf _
- * @since 4.3.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
- * @example
- *
- * _.isBuffer(new Buffer(2));
- * // => true
- *
- * _.isBuffer(new Uint8Array(2));
- * // => false
- */
- var isBuffer = nativeIsBuffer || stubFalse;
-
- /**
- * Checks if `value` is classified as a `Date` object.
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a date object, else `false`.
- * @example
- *
- * _.isDate(new Date);
- * // => true
- *
- * _.isDate('Mon April 23 2012');
- * // => false
- */
- var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate;
-
- /**
- * Checks if `value` is likely a DOM element.
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`.
- * @example
- *
- * _.isElement(document.body);
- * // => true
- *
- * _.isElement('');
- * // => false
- */
- function isElement(value) {
- return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value);
- }
-
- /**
- * Checks if `value` is an empty object, collection, map, or set.
- *
- * Objects are considered empty if they have no own enumerable string keyed
- * properties.
- *
- * Array-like values such as `arguments` objects, arrays, buffers, strings, or
- * jQuery-like collections are considered empty if they have a `length` of `0`.
- * Similarly, maps and sets are considered empty if they have a `size` of `0`.
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is empty, else `false`.
- * @example
- *
- * _.isEmpty(null);
- * // => true
- *
- * _.isEmpty(true);
- * // => true
- *
- * _.isEmpty(1);
- * // => true
- *
- * _.isEmpty([1, 2, 3]);
- * // => false
- *
- * _.isEmpty({ 'a': 1 });
- * // => false
- */
- function isEmpty(value) {
- if (value == null) {
- return true;
- }
- if (isArrayLike(value) &&
- (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' ||
- isBuffer(value) || isTypedArray(value) || isArguments(value))) {
- return !value.length;
- }
- var tag = getTag(value);
- if (tag == mapTag || tag == setTag) {
- return !value.size;
- }
- if (isPrototype(value)) {
- return !baseKeys(value).length;
- }
- for (var key in value) {
- if (hasOwnProperty.call(value, key)) {
- return false;
- }
- }
- return true;
- }
-
- /**
- * Performs a deep comparison between two values to determine if they are
- * equivalent.
- *
- * **Note:** This method supports comparing arrays, array buffers, booleans,
- * date objects, error objects, maps, numbers, `Object` objects, regexes,
- * sets, strings, symbols, and typed arrays. `Object` objects are compared
- * by their own, not inherited, enumerable properties. Functions and DOM
- * nodes are compared by strict equality, i.e. `===`.
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Lang
- * @param {*} value The value to compare.
- * @param {*} other The other value to compare.
- * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
- * @example
- *
- * var object = { 'a': 1 };
- * var other = { 'a': 1 };
- *
- * _.isEqual(object, other);
- * // => true
- *
- * object === other;
- * // => false
- */
- function isEqual(value, other) {
- return baseIsEqual(value, other);
- }
-
- /**
- * This method is like `_.isEqual` except that it accepts `customizer` which
- * is invoked to compare values. If `customizer` returns `undefined`, comparisons
- * are handled by the method instead. The `customizer` is invoked with up to
- * six arguments: (objValue, othValue [, index|key, object, other, stack]).
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to compare.
- * @param {*} other The other value to compare.
- * @param {Function} [customizer] The function to customize comparisons.
- * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
- * @example
- *
- * function isGreeting(value) {
- * return /^h(?:i|ello)$/.test(value);
- * }
- *
- * function customizer(objValue, othValue) {
- * if (isGreeting(objValue) && isGreeting(othValue)) {
- * return true;
- * }
- * }
- *
- * var array = ['hello', 'goodbye'];
- * var other = ['hi', 'goodbye'];
- *
- * _.isEqualWith(array, other, customizer);
- * // => true
- */
- function isEqualWith(value, other, customizer) {
- customizer = typeof customizer == 'function' ? customizer : undefined;
- var result = customizer ? customizer(value, other) : undefined;
- return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result;
- }
-
- /**
- * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,
- * `SyntaxError`, `TypeError`, or `URIError` object.
- *
- * @static
- * @memberOf _
- * @since 3.0.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is an error object, else `false`.
- * @example
- *
- * _.isError(new Error);
- * // => true
- *
- * _.isError(Error);
- * // => false
- */
- function isError(value) {
- if (!isObjectLike(value)) {
- return false;
- }
- var tag = baseGetTag(value);
- return tag == errorTag || tag == domExcTag ||
- (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value));
- }
-
- /**
- * Checks if `value` is a finite primitive number.
- *
- * **Note:** This method is based on
- * [`Number.isFinite`](https://mdn.io/Number/isFinite).
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a finite number, else `false`.
- * @example
- *
- * _.isFinite(3);
- * // => true
- *
- * _.isFinite(Number.MIN_VALUE);
- * // => true
- *
- * _.isFinite(Infinity);
- * // => false
- *
- * _.isFinite('3');
- * // => false
- */
- function isFinite(value) {
- return typeof value == 'number' && nativeIsFinite(value);
- }
-
- /**
- * Checks if `value` is classified as a `Function` object.
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a function, else `false`.
- * @example
- *
- * _.isFunction(_);
- * // => true
- *
- * _.isFunction(/abc/);
- * // => false
- */
- function isFunction(value) {
- if (!isObject(value)) {
- return false;
- }
- // The use of `Object#toString` avoids issues with the `typeof` operator
- // in Safari 9 which returns 'object' for typed arrays and other constructors.
- var tag = baseGetTag(value);
- return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
- }
-
- /**
- * Checks if `value` is an integer.
- *
- * **Note:** This method is based on
- * [`Number.isInteger`](https://mdn.io/Number/isInteger).
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is an integer, else `false`.
- * @example
- *
- * _.isInteger(3);
- * // => true
- *
- * _.isInteger(Number.MIN_VALUE);
- * // => false
- *
- * _.isInteger(Infinity);
- * // => false
- *
- * _.isInteger('3');
- * // => false
- */
- function isInteger(value) {
- return typeof value == 'number' && value == toInteger(value);
- }
-
- /**
- * Checks if `value` is a valid array-like length.
- *
- * **Note:** This method is loosely based on
- * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
- * @example
- *
- * _.isLength(3);
- * // => true
- *
- * _.isLength(Number.MIN_VALUE);
- * // => false
- *
- * _.isLength(Infinity);
- * // => false
- *
- * _.isLength('3');
- * // => false
- */
- function isLength(value) {
- return typeof value == 'number' &&
- value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
- }
-
- /**
- * Checks if `value` is the
- * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
- * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is an object, else `false`.
- * @example
- *
- * _.isObject({});
- * // => true
- *
- * _.isObject([1, 2, 3]);
- * // => true
- *
- * _.isObject(_.noop);
- * // => true
- *
- * _.isObject(null);
- * // => false
- */
- function isObject(value) {
- var type = typeof value;
- return value != null && (type == 'object' || type == 'function');
- }
-
- /**
- * Checks if `value` is object-like. A value is object-like if it's not `null`
- * and has a `typeof` result of "object".
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
- * @example
- *
- * _.isObjectLike({});
- * // => true
- *
- * _.isObjectLike([1, 2, 3]);
- * // => true
- *
- * _.isObjectLike(_.noop);
- * // => false
- *
- * _.isObjectLike(null);
- * // => false
- */
- function isObjectLike(value) {
- return value != null && typeof value == 'object';
- }
-
- /**
- * Checks if `value` is classified as a `Map` object.
- *
- * @static
- * @memberOf _
- * @since 4.3.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a map, else `false`.
- * @example
- *
- * _.isMap(new Map);
- * // => true
- *
- * _.isMap(new WeakMap);
- * // => false
- */
- var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap;
-
- /**
- * Performs a partial deep comparison between `object` and `source` to
- * determine if `object` contains equivalent property values.
- *
- * **Note:** This method is equivalent to `_.matches` when `source` is
- * partially applied.
- *
- * Partial comparisons will match empty array and empty object `source`
- * values against any array or object value, respectively. See `_.isEqual`
- * for a list of supported value comparisons.
- *
- * @static
- * @memberOf _
- * @since 3.0.0
- * @category Lang
- * @param {Object} object The object to inspect.
- * @param {Object} source The object of property values to match.
- * @returns {boolean} Returns `true` if `object` is a match, else `false`.
- * @example
- *
- * var object = { 'a': 1, 'b': 2 };
- *
- * _.isMatch(object, { 'b': 2 });
- * // => true
- *
- * _.isMatch(object, { 'b': 1 });
- * // => false
- */
- function isMatch(object, source) {
- return object === source || baseIsMatch(object, source, getMatchData(source));
- }
-
- /**
- * This method is like `_.isMatch` except that it accepts `customizer` which
- * is invoked to compare values. If `customizer` returns `undefined`, comparisons
- * are handled by the method instead. The `customizer` is invoked with five
- * arguments: (objValue, srcValue, index|key, object, source).
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {Object} object The object to inspect.
- * @param {Object} source The object of property values to match.
- * @param {Function} [customizer] The function to customize comparisons.
- * @returns {boolean} Returns `true` if `object` is a match, else `false`.
- * @example
- *
- * function isGreeting(value) {
- * return /^h(?:i|ello)$/.test(value);
- * }
- *
- * function customizer(objValue, srcValue) {
- * if (isGreeting(objValue) && isGreeting(srcValue)) {
- * return true;
- * }
- * }
- *
- * var object = { 'greeting': 'hello' };
- * var source = { 'greeting': 'hi' };
- *
- * _.isMatchWith(object, source, customizer);
- * // => true
- */
- function isMatchWith(object, source, customizer) {
- customizer = typeof customizer == 'function' ? customizer : undefined;
- return baseIsMatch(object, source, getMatchData(source), customizer);
- }
-
- /**
- * Checks if `value` is `NaN`.
- *
- * **Note:** This method is based on
- * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as
- * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for
- * `undefined` and other non-number values.
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
- * @example
- *
- * _.isNaN(NaN);
- * // => true
- *
- * _.isNaN(new Number(NaN));
- * // => true
- *
- * isNaN(undefined);
- * // => true
- *
- * _.isNaN(undefined);
- * // => false
- */
- function isNaN(value) {
- // An `NaN` primitive is the only value that is not equal to itself.
- // Perform the `toStringTag` check first to avoid errors with some
- // ActiveX objects in IE.
- return isNumber(value) && value != +value;
- }
-
- /**
- * Checks if `value` is a pristine native function.
- *
- * **Note:** This method can't reliably detect native functions in the presence
- * of the core-js package because core-js circumvents this kind of detection.
- * Despite multiple requests, the core-js maintainer has made it clear: any
- * attempt to fix the detection will be obstructed. As a result, we're left
- * with little choice but to throw an error. Unfortunately, this also affects
- * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill),
- * which rely on core-js.
- *
- * @static
- * @memberOf _
- * @since 3.0.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a native function,
- * else `false`.
- * @example
- *
- * _.isNative(Array.prototype.push);
- * // => true
- *
- * _.isNative(_);
- * // => false
- */
- function isNative(value) {
- if (isMaskable(value)) {
- throw new Error(CORE_ERROR_TEXT);
- }
- return baseIsNative(value);
- }
-
- /**
- * Checks if `value` is `null`.
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is `null`, else `false`.
- * @example
- *
- * _.isNull(null);
- * // => true
- *
- * _.isNull(void 0);
- * // => false
- */
- function isNull(value) {
- return value === null;
- }
-
- /**
- * Checks if `value` is `null` or `undefined`.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is nullish, else `false`.
- * @example
- *
- * _.isNil(null);
- * // => true
- *
- * _.isNil(void 0);
- * // => true
- *
- * _.isNil(NaN);
- * // => false
- */
- function isNil(value) {
- return value == null;
- }
-
- /**
- * Checks if `value` is classified as a `Number` primitive or object.
- *
- * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are
- * classified as numbers, use the `_.isFinite` method.
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a number, else `false`.
- * @example
- *
- * _.isNumber(3);
- * // => true
- *
- * _.isNumber(Number.MIN_VALUE);
- * // => true
- *
- * _.isNumber(Infinity);
- * // => true
- *
- * _.isNumber('3');
- * // => false
- */
- function isNumber(value) {
- return typeof value == 'number' ||
- (isObjectLike(value) && baseGetTag(value) == numberTag);
- }
-
- /**
- * Checks if `value` is a plain object, that is, an object created by the
- * `Object` constructor or one with a `[[Prototype]]` of `null`.
- *
- * @static
- * @memberOf _
- * @since 0.8.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
- * @example
- *
- * function Foo() {
- * this.a = 1;
- * }
- *
- * _.isPlainObject(new Foo);
- * // => false
- *
- * _.isPlainObject([1, 2, 3]);
- * // => false
- *
- * _.isPlainObject({ 'x': 0, 'y': 0 });
- * // => true
- *
- * _.isPlainObject(Object.create(null));
- * // => true
- */
- function isPlainObject(value) {
- if (!isObjectLike(value) || baseGetTag(value) != objectTag) {
- return false;
- }
- var proto = getPrototype(value);
- if (proto === null) {
- return true;
- }
- var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;
- return typeof Ctor == 'function' && Ctor instanceof Ctor &&
- funcToString.call(Ctor) == objectCtorString;
- }
-
- /**
- * Checks if `value` is classified as a `RegExp` object.
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a regexp, else `false`.
- * @example
- *
- * _.isRegExp(/abc/);
- * // => true
- *
- * _.isRegExp('/abc/');
- * // => false
- */
- var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp;
-
- /**
- * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754
- * double precision number which isn't the result of a rounded unsafe integer.
- *
- * **Note:** This method is based on
- * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger).
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`.
- * @example
- *
- * _.isSafeInteger(3);
- * // => true
- *
- * _.isSafeInteger(Number.MIN_VALUE);
- * // => false
- *
- * _.isSafeInteger(Infinity);
- * // => false
- *
- * _.isSafeInteger('3');
- * // => false
- */
- function isSafeInteger(value) {
- return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER;
- }
-
- /**
- * Checks if `value` is classified as a `Set` object.
- *
- * @static
- * @memberOf _
- * @since 4.3.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a set, else `false`.
- * @example
- *
- * _.isSet(new Set);
- * // => true
- *
- * _.isSet(new WeakSet);
- * // => false
- */
- var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet;
-
- /**
- * Checks if `value` is classified as a `String` primitive or object.
- *
- * @static
- * @since 0.1.0
- * @memberOf _
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a string, else `false`.
- * @example
- *
- * _.isString('abc');
- * // => true
- *
- * _.isString(1);
- * // => false
- */
- function isString(value) {
- return typeof value == 'string' ||
- (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag);
- }
-
- /**
- * Checks if `value` is classified as a `Symbol` primitive or object.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
- * @example
- *
- * _.isSymbol(Symbol.iterator);
- * // => true
- *
- * _.isSymbol('abc');
- * // => false
- */
- function isSymbol(value) {
- return typeof value == 'symbol' ||
- (isObjectLike(value) && baseGetTag(value) == symbolTag);
- }
-
- /**
- * Checks if `value` is classified as a typed array.
- *
- * @static
- * @memberOf _
- * @since 3.0.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
- * @example
- *
- * _.isTypedArray(new Uint8Array);
- * // => true
- *
- * _.isTypedArray([]);
- * // => false
- */
- var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
-
- /**
- * Checks if `value` is `undefined`.
- *
- * @static
- * @since 0.1.0
- * @memberOf _
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.
- * @example
- *
- * _.isUndefined(void 0);
- * // => true
- *
- * _.isUndefined(null);
- * // => false
- */
- function isUndefined(value) {
- return value === undefined;
- }
-
- /**
- * Checks if `value` is classified as a `WeakMap` object.
- *
- * @static
- * @memberOf _
- * @since 4.3.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a weak map, else `false`.
- * @example
- *
- * _.isWeakMap(new WeakMap);
- * // => true
- *
- * _.isWeakMap(new Map);
- * // => false
- */
- function isWeakMap(value) {
- return isObjectLike(value) && getTag(value) == weakMapTag;
- }
-
- /**
- * Checks if `value` is classified as a `WeakSet` object.
- *
- * @static
- * @memberOf _
- * @since 4.3.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a weak set, else `false`.
- * @example
- *
- * _.isWeakSet(new WeakSet);
- * // => true
- *
- * _.isWeakSet(new Set);
- * // => false
- */
- function isWeakSet(value) {
- return isObjectLike(value) && baseGetTag(value) == weakSetTag;
- }
-
- /**
- * Checks if `value` is less than `other`.
- *
- * @static
- * @memberOf _
- * @since 3.9.0
- * @category Lang
- * @param {*} value The value to compare.
- * @param {*} other The other value to compare.
- * @returns {boolean} Returns `true` if `value` is less than `other`,
- * else `false`.
- * @see _.gt
- * @example
- *
- * _.lt(1, 3);
- * // => true
- *
- * _.lt(3, 3);
- * // => false
- *
- * _.lt(3, 1);
- * // => false
- */
- var lt = createRelationalOperation(baseLt);
-
- /**
- * Checks if `value` is less than or equal to `other`.
- *
- * @static
- * @memberOf _
- * @since 3.9.0
- * @category Lang
- * @param {*} value The value to compare.
- * @param {*} other The other value to compare.
- * @returns {boolean} Returns `true` if `value` is less than or equal to
- * `other`, else `false`.
- * @see _.gte
- * @example
- *
- * _.lte(1, 3);
- * // => true
- *
- * _.lte(3, 3);
- * // => true
- *
- * _.lte(3, 1);
- * // => false
- */
- var lte = createRelationalOperation(function(value, other) {
- return value <= other;
- });
-
- /**
- * Converts `value` to an array.
- *
- * @static
- * @since 0.1.0
- * @memberOf _
- * @category Lang
- * @param {*} value The value to convert.
- * @returns {Array} Returns the converted array.
- * @example
- *
- * _.toArray({ 'a': 1, 'b': 2 });
- * // => [1, 2]
- *
- * _.toArray('abc');
- * // => ['a', 'b', 'c']
- *
- * _.toArray(1);
- * // => []
- *
- * _.toArray(null);
- * // => []
- */
- function toArray(value) {
- if (!value) {
- return [];
- }
- if (isArrayLike(value)) {
- return isString(value) ? stringToArray(value) : copyArray(value);
- }
- if (symIterator && value[symIterator]) {
- return iteratorToArray(value[symIterator]());
- }
- var tag = getTag(value),
- func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values);
-
- return func(value);
- }
-
- /**
- * Converts `value` to a finite number.
- *
- * @static
- * @memberOf _
- * @since 4.12.0
- * @category Lang
- * @param {*} value The value to convert.
- * @returns {number} Returns the converted number.
- * @example
- *
- * _.toFinite(3.2);
- * // => 3.2
- *
- * _.toFinite(Number.MIN_VALUE);
- * // => 5e-324
- *
- * _.toFinite(Infinity);
- * // => 1.7976931348623157e+308
- *
- * _.toFinite('3.2');
- * // => 3.2
- */
- function toFinite(value) {
- if (!value) {
- return value === 0 ? value : 0;
- }
- value = toNumber(value);
- if (value === INFINITY || value === -INFINITY) {
- var sign = (value < 0 ? -1 : 1);
- return sign * MAX_INTEGER;
- }
- return value === value ? value : 0;
- }
-
- /**
- * Converts `value` to an integer.
- *
- * **Note:** This method is loosely based on
- * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to convert.
- * @returns {number} Returns the converted integer.
- * @example
- *
- * _.toInteger(3.2);
- * // => 3
- *
- * _.toInteger(Number.MIN_VALUE);
- * // => 0
- *
- * _.toInteger(Infinity);
- * // => 1.7976931348623157e+308
- *
- * _.toInteger('3.2');
- * // => 3
- */
- function toInteger(value) {
- var result = toFinite(value),
- remainder = result % 1;
-
- return result === result ? (remainder ? result - remainder : result) : 0;
- }
-
- /**
- * Converts `value` to an integer suitable for use as the length of an
- * array-like object.
- *
- * **Note:** This method is based on
- * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to convert.
- * @returns {number} Returns the converted integer.
- * @example
- *
- * _.toLength(3.2);
- * // => 3
- *
- * _.toLength(Number.MIN_VALUE);
- * // => 0
- *
- * _.toLength(Infinity);
- * // => 4294967295
- *
- * _.toLength('3.2');
- * // => 3
- */
- function toLength(value) {
- return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0;
- }
-
- /**
- * Converts `value` to a number.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to process.
- * @returns {number} Returns the number.
- * @example
- *
- * _.toNumber(3.2);
- * // => 3.2
- *
- * _.toNumber(Number.MIN_VALUE);
- * // => 5e-324
- *
- * _.toNumber(Infinity);
- * // => Infinity
- *
- * _.toNumber('3.2');
- * // => 3.2
- */
- function toNumber(value) {
- if (typeof value == 'number') {
- return value;
- }
- if (isSymbol(value)) {
- return NAN;
- }
- if (isObject(value)) {
- var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
- value = isObject(other) ? (other + '') : other;
- }
- if (typeof value != 'string') {
- return value === 0 ? value : +value;
- }
- value = value.replace(reTrim, '');
- var isBinary = reIsBinary.test(value);
- return (isBinary || reIsOctal.test(value))
- ? freeParseInt(value.slice(2), isBinary ? 2 : 8)
- : (reIsBadHex.test(value) ? NAN : +value);
- }
-
- /**
- * Converts `value` to a plain object flattening inherited enumerable string
- * keyed properties of `value` to own properties of the plain object.
- *
- * @static
- * @memberOf _
- * @since 3.0.0
- * @category Lang
- * @param {*} value The value to convert.
- * @returns {Object} Returns the converted plain object.
- * @example
- *
- * function Foo() {
- * this.b = 2;
- * }
- *
- * Foo.prototype.c = 3;
- *
- * _.assign({ 'a': 1 }, new Foo);
- * // => { 'a': 1, 'b': 2 }
- *
- * _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
- * // => { 'a': 1, 'b': 2, 'c': 3 }
- */
- function toPlainObject(value) {
- return copyObject(value, keysIn(value));
- }
-
- /**
- * Converts `value` to a safe integer. A safe integer can be compared and
- * represented correctly.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to convert.
- * @returns {number} Returns the converted integer.
- * @example
- *
- * _.toSafeInteger(3.2);
- * // => 3
- *
- * _.toSafeInteger(Number.MIN_VALUE);
- * // => 0
- *
- * _.toSafeInteger(Infinity);
- * // => 9007199254740991
- *
- * _.toSafeInteger('3.2');
- * // => 3
- */
- function toSafeInteger(value) {
- return value
- ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER)
- : (value === 0 ? value : 0);
- }
-
- /**
- * Converts `value` to a string. An empty string is returned for `null`
- * and `undefined` values. The sign of `-0` is preserved.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to convert.
- * @returns {string} Returns the converted string.
- * @example
- *
- * _.toString(null);
- * // => ''
- *
- * _.toString(-0);
- * // => '-0'
- *
- * _.toString([1, 2, 3]);
- * // => '1,2,3'
- */
- function toString(value) {
- return value == null ? '' : baseToString(value);
- }
-
- /*------------------------------------------------------------------------*/
-
- /**
- * Assigns own enumerable string keyed properties of source objects to the
- * destination object. Source objects are applied from left to right.
- * Subsequent sources overwrite property assignments of previous sources.
- *
- * **Note:** This method mutates `object` and is loosely based on
- * [`Object.assign`](https://mdn.io/Object/assign).
- *
- * @static
- * @memberOf _
- * @since 0.10.0
- * @category Object
- * @param {Object} object The destination object.
- * @param {...Object} [sources] The source objects.
- * @returns {Object} Returns `object`.
- * @see _.assignIn
- * @example
- *
- * function Foo() {
- * this.a = 1;
- * }
- *
- * function Bar() {
- * this.c = 3;
- * }
- *
- * Foo.prototype.b = 2;
- * Bar.prototype.d = 4;
- *
- * _.assign({ 'a': 0 }, new Foo, new Bar);
- * // => { 'a': 1, 'c': 3 }
- */
- var assign = createAssigner(function(object, source) {
- if (isPrototype(source) || isArrayLike(source)) {
- copyObject(source, keys(source), object);
- return;
- }
- for (var key in source) {
- if (hasOwnProperty.call(source, key)) {
- assignValue(object, key, source[key]);
- }
- }
- });
-
- /**
- * This method is like `_.assign` except that it iterates over own and
- * inherited source properties.
- *
- * **Note:** This method mutates `object`.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @alias extend
- * @category Object
- * @param {Object} object The destination object.
- * @param {...Object} [sources] The source objects.
- * @returns {Object} Returns `object`.
- * @see _.assign
- * @example
- *
- * function Foo() {
- * this.a = 1;
- * }
- *
- * function Bar() {
- * this.c = 3;
- * }
- *
- * Foo.prototype.b = 2;
- * Bar.prototype.d = 4;
- *
- * _.assignIn({ 'a': 0 }, new Foo, new Bar);
- * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 }
- */
- var assignIn = createAssigner(function(object, source) {
- copyObject(source, keysIn(source), object);
- });
-
- /**
- * This method is like `_.assignIn` except that it accepts `customizer`
- * which is invoked to produce the assigned values. If `customizer` returns
- * `undefined`, assignment is handled by the method instead. The `customizer`
- * is invoked with five arguments: (objValue, srcValue, key, object, source).
- *
- * **Note:** This method mutates `object`.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @alias extendWith
- * @category Object
- * @param {Object} object The destination object.
- * @param {...Object} sources The source objects.
- * @param {Function} [customizer] The function to customize assigned values.
- * @returns {Object} Returns `object`.
- * @see _.assignWith
- * @example
- *
- * function customizer(objValue, srcValue) {
- * return _.isUndefined(objValue) ? srcValue : objValue;
- * }
- *
- * var defaults = _.partialRight(_.assignInWith, customizer);
- *
- * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
- * // => { 'a': 1, 'b': 2 }
- */
- var assignInWith = createAssigner(function(object, source, srcIndex, customizer) {
- copyObject(source, keysIn(source), object, customizer);
- });
-
- /**
- * This method is like `_.assign` except that it accepts `customizer`
- * which is invoked to produce the assigned values. If `customizer` returns
- * `undefined`, assignment is handled by the method instead. The `customizer`
- * is invoked with five arguments: (objValue, srcValue, key, object, source).
- *
- * **Note:** This method mutates `object`.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Object
- * @param {Object} object The destination object.
- * @param {...Object} sources The source objects.
- * @param {Function} [customizer] The function to customize assigned values.
- * @returns {Object} Returns `object`.
- * @see _.assignInWith
- * @example
- *
- * function customizer(objValue, srcValue) {
- * return _.isUndefined(objValue) ? srcValue : objValue;
- * }
- *
- * var defaults = _.partialRight(_.assignWith, customizer);
- *
- * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
- * // => { 'a': 1, 'b': 2 }
- */
- var assignWith = createAssigner(function(object, source, srcIndex, customizer) {
- copyObject(source, keys(source), object, customizer);
- });
-
- /**
- * Creates an array of values corresponding to `paths` of `object`.
- *
- * @static
- * @memberOf _
- * @since 1.0.0
- * @category Object
- * @param {Object} object The object to iterate over.
- * @param {...(string|string[])} [paths] The property paths to pick.
- * @returns {Array} Returns the picked values.
- * @example
- *
- * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };
- *
- * _.at(object, ['a[0].b.c', 'a[1]']);
- * // => [3, 4]
- */
- var at = flatRest(baseAt);
-
- /**
- * Creates an object that inherits from the `prototype` object. If a
- * `properties` object is given, its own enumerable string keyed properties
- * are assigned to the created object.
- *
- * @static
- * @memberOf _
- * @since 2.3.0
- * @category Object
- * @param {Object} prototype The object to inherit from.
- * @param {Object} [properties] The properties to assign to the object.
- * @returns {Object} Returns the new object.
- * @example
- *
- * function Shape() {
- * this.x = 0;
- * this.y = 0;
- * }
- *
- * function Circle() {
- * Shape.call(this);
- * }
- *
- * Circle.prototype = _.create(Shape.prototype, {
- * 'constructor': Circle
- * });
- *
- * var circle = new Circle;
- * circle instanceof Circle;
- * // => true
- *
- * circle instanceof Shape;
- * // => true
- */
- function create(prototype, properties) {
- var result = baseCreate(prototype);
- return properties == null ? result : baseAssign(result, properties);
- }
-
- /**
- * Assigns own and inherited enumerable string keyed properties of source
- * objects to the destination object for all destination properties that
- * resolve to `undefined`. Source objects are applied from left to right.
- * Once a property is set, additional values of the same property are ignored.
- *
- * **Note:** This method mutates `object`.
- *
- * @static
- * @since 0.1.0
- * @memberOf _
- * @category Object
- * @param {Object} object The destination object.
- * @param {...Object} [sources] The source objects.
- * @returns {Object} Returns `object`.
- * @see _.defaultsDeep
- * @example
- *
- * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
- * // => { 'a': 1, 'b': 2 }
- */
- var defaults = baseRest(function(object, sources) {
- object = Object(object);
-
- var index = -1;
- var length = sources.length;
- var guard = length > 2 ? sources[2] : undefined;
-
- if (guard && isIterateeCall(sources[0], sources[1], guard)) {
- length = 1;
- }
-
- while (++index < length) {
- var source = sources[index];
- var props = keysIn(source);
- var propsIndex = -1;
- var propsLength = props.length;
-
- while (++propsIndex < propsLength) {
- var key = props[propsIndex];
- var value = object[key];
-
- if (value === undefined ||
- (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) {
- object[key] = source[key];
- }
- }
- }
-
- return object;
- });
-
- /**
- * This method is like `_.defaults` except that it recursively assigns
- * default properties.
- *
- * **Note:** This method mutates `object`.
- *
- * @static
- * @memberOf _
- * @since 3.10.0
- * @category Object
- * @param {Object} object The destination object.
- * @param {...Object} [sources] The source objects.
- * @returns {Object} Returns `object`.
- * @see _.defaults
- * @example
- *
- * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } });
- * // => { 'a': { 'b': 2, 'c': 3 } }
- */
- var defaultsDeep = baseRest(function(args) {
- args.push(undefined, customDefaultsMerge);
- return apply(mergeWith, undefined, args);
- });
-
- /**
- * This method is like `_.find` except that it returns the key of the first
- * element `predicate` returns truthy for instead of the element itself.
- *
- * @static
- * @memberOf _
- * @since 1.1.0
- * @category Object
- * @param {Object} object The object to inspect.
- * @param {Function} [predicate=_.identity] The function invoked per iteration.
- * @returns {string|undefined} Returns the key of the matched element,
- * else `undefined`.
- * @example
- *
- * var users = {
- * 'barney': { 'age': 36, 'active': true },
- * 'fred': { 'age': 40, 'active': false },
- * 'pebbles': { 'age': 1, 'active': true }
- * };
- *
- * _.findKey(users, function(o) { return o.age < 40; });
- * // => 'barney' (iteration order is not guaranteed)
- *
- * // The `_.matches` iteratee shorthand.
- * _.findKey(users, { 'age': 1, 'active': true });
- * // => 'pebbles'
- *
- * // The `_.matchesProperty` iteratee shorthand.
- * _.findKey(users, ['active', false]);
- * // => 'fred'
- *
- * // The `_.property` iteratee shorthand.
- * _.findKey(users, 'active');
- * // => 'barney'
- */
- function findKey(object, predicate) {
- return baseFindKey(object, getIteratee(predicate, 3), baseForOwn);
- }
-
- /**
- * This method is like `_.findKey` except that it iterates over elements of
- * a collection in the opposite order.
- *
- * @static
- * @memberOf _
- * @since 2.0.0
- * @category Object
- * @param {Object} object The object to inspect.
- * @param {Function} [predicate=_.identity] The function invoked per iteration.
- * @returns {string|undefined} Returns the key of the matched element,
- * else `undefined`.
- * @example
- *
- * var users = {
- * 'barney': { 'age': 36, 'active': true },
- * 'fred': { 'age': 40, 'active': false },
- * 'pebbles': { 'age': 1, 'active': true }
- * };
- *
- * _.findLastKey(users, function(o) { return o.age < 40; });
- * // => returns 'pebbles' assuming `_.findKey` returns 'barney'
- *
- * // The `_.matches` iteratee shorthand.
- * _.findLastKey(users, { 'age': 36, 'active': true });
- * // => 'barney'
- *
- * // The `_.matchesProperty` iteratee shorthand.
- * _.findLastKey(users, ['active', false]);
- * // => 'fred'
- *
- * // The `_.property` iteratee shorthand.
- * _.findLastKey(users, 'active');
- * // => 'pebbles'
- */
- function findLastKey(object, predicate) {
- return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight);
- }
-
- /**
- * Iterates over own and inherited enumerable string keyed properties of an
- * object and invokes `iteratee` for each property. The iteratee is invoked
- * with three arguments: (value, key, object). Iteratee functions may exit
- * iteration early by explicitly returning `false`.
- *
- * @static
- * @memberOf _
- * @since 0.3.0
- * @category Object
- * @param {Object} object The object to iterate over.
- * @param {Function} [iteratee=_.identity] The function invoked per iteration.
- * @returns {Object} Returns `object`.
- * @see _.forInRight
- * @example
- *
- * function Foo() {
- * this.a = 1;
- * this.b = 2;
- * }
- *
- * Foo.prototype.c = 3;
- *
- * _.forIn(new Foo, function(value, key) {
- * console.log(key);
- * });
- * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed).
- */
- function forIn(object, iteratee) {
- return object == null
- ? object
- : baseFor(object, getIteratee(iteratee, 3), keysIn);
- }
-
- /**
- * This method is like `_.forIn` except that it iterates over properties of
- * `object` in the opposite order.
- *
- * @static
- * @memberOf _
- * @since 2.0.0
- * @category Object
- * @param {Object} object The object to iterate over.
- * @param {Function} [iteratee=_.identity] The function invoked per iteration.
- * @returns {Object} Returns `object`.
- * @see _.forIn
- * @example
- *
- * function Foo() {
- * this.a = 1;
- * this.b = 2;
- * }
- *
- * Foo.prototype.c = 3;
- *
- * _.forInRight(new Foo, function(value, key) {
- * console.log(key);
- * });
- * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'.
- */
- function forInRight(object, iteratee) {
- return object == null
- ? object
- : baseForRight(object, getIteratee(iteratee, 3), keysIn);
- }
-
- /**
- * Iterates over own enumerable string keyed properties of an object and
- * invokes `iteratee` for each property. The iteratee is invoked with three
- * arguments: (value, key, object). Iteratee functions may exit iteration
- * early by explicitly returning `false`.
- *
- * @static
- * @memberOf _
- * @since 0.3.0
- * @category Object
- * @param {Object} object The object to iterate over.
- * @param {Function} [iteratee=_.identity] The function invoked per iteration.
- * @returns {Object} Returns `object`.
- * @see _.forOwnRight
- * @example
- *
- * function Foo() {
- * this.a = 1;
- * this.b = 2;
- * }
- *
- * Foo.prototype.c = 3;
- *
- * _.forOwn(new Foo, function(value, key) {
- * console.log(key);
- * });
- * // => Logs 'a' then 'b' (iteration order is not guaranteed).
- */
- function forOwn(object, iteratee) {
- return object && baseForOwn(object, getIteratee(iteratee, 3));
- }
-
- /**
- * This method is like `_.forOwn` except that it iterates over properties of
- * `object` in the opposite order.
- *
- * @static
- * @memberOf _
- * @since 2.0.0
- * @category Object
- * @param {Object} object The object to iterate over.
- * @param {Function} [iteratee=_.identity] The function invoked per iteration.
- * @returns {Object} Returns `object`.
- * @see _.forOwn
- * @example
- *
- * function Foo() {
- * this.a = 1;
- * this.b = 2;
- * }
- *
- * Foo.prototype.c = 3;
- *
- * _.forOwnRight(new Foo, function(value, key) {
- * console.log(key);
- * });
- * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'.
- */
- function forOwnRight(object, iteratee) {
- return object && baseForOwnRight(object, getIteratee(iteratee, 3));
- }
-
- /**
- * Creates an array of function property names from own enumerable properties
- * of `object`.
- *
- * @static
- * @since 0.1.0
- * @memberOf _
- * @category Object
- * @param {Object} object The object to inspect.
- * @returns {Array} Returns the function names.
- * @see _.functionsIn
- * @example
- *
- * function Foo() {
- * this.a = _.constant('a');
- * this.b = _.constant('b');
- * }
- *
- * Foo.prototype.c = _.constant('c');
- *
- * _.functions(new Foo);
- * // => ['a', 'b']
- */
- function functions(object) {
- return object == null ? [] : baseFunctions(object, keys(object));
- }
-
- /**
- * Creates an array of function property names from own and inherited
- * enumerable properties of `object`.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Object
- * @param {Object} object The object to inspect.
- * @returns {Array} Returns the function names.
- * @see _.functions
- * @example
- *
- * function Foo() {
- * this.a = _.constant('a');
- * this.b = _.constant('b');
- * }
- *
- * Foo.prototype.c = _.constant('c');
- *
- * _.functionsIn(new Foo);
- * // => ['a', 'b', 'c']
- */
- function functionsIn(object) {
- return object == null ? [] : baseFunctions(object, keysIn(object));
- }
-
- /**
- * Gets the value at `path` of `object`. If the resolved value is
- * `undefined`, the `defaultValue` is returned in its place.
- *
- * @static
- * @memberOf _
- * @since 3.7.0
- * @category Object
- * @param {Object} object The object to query.
- * @param {Array|string} path The path of the property to get.
- * @param {*} [defaultValue] The value returned for `undefined` resolved values.
- * @returns {*} Returns the resolved value.
- * @example
- *
- * var object = { 'a': [{ 'b': { 'c': 3 } }] };
- *
- * _.get(object, 'a[0].b.c');
- * // => 3
- *
- * _.get(object, ['a', '0', 'b', 'c']);
- * // => 3
- *
- * _.get(object, 'a.b.c', 'default');
- * // => 'default'
- */
- function get(object, path, defaultValue) {
- var result = object == null ? undefined : baseGet(object, path);
- return result === undefined ? defaultValue : result;
- }
-
- /**
- * Checks if `path` is a direct property of `object`.
- *
- * @static
- * @since 0.1.0
- * @memberOf _
- * @category Object
- * @param {Object} object The object to query.
- * @param {Array|string} path The path to check.
- * @returns {boolean} Returns `true` if `path` exists, else `false`.
- * @example
- *
- * var object = { 'a': { 'b': 2 } };
- * var other = _.create({ 'a': _.create({ 'b': 2 }) });
- *
- * _.has(object, 'a');
- * // => true
- *
- * _.has(object, 'a.b');
- * // => true
- *
- * _.has(object, ['a', 'b']);
- * // => true
- *
- * _.has(other, 'a');
- * // => false
- */
- function has(object, path) {
- return object != null && hasPath(object, path, baseHas);
- }
-
- /**
- * Checks if `path` is a direct or inherited property of `object`.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Object
- * @param {Object} object The object to query.
- * @param {Array|string} path The path to check.
- * @returns {boolean} Returns `true` if `path` exists, else `false`.
- * @example
- *
- * var object = _.create({ 'a': _.create({ 'b': 2 }) });
- *
- * _.hasIn(object, 'a');
- * // => true
- *
- * _.hasIn(object, 'a.b');
- * // => true
- *
- * _.hasIn(object, ['a', 'b']);
- * // => true
- *
- * _.hasIn(object, 'b');
- * // => false
- */
- function hasIn(object, path) {
- return object != null && hasPath(object, path, baseHasIn);
- }
-
- /**
- * Creates an object composed of the inverted keys and values of `object`.
- * If `object` contains duplicate values, subsequent values overwrite
- * property assignments of previous values.
- *
- * @static
- * @memberOf _
- * @since 0.7.0
- * @category Object
- * @param {Object} object The object to invert.
- * @returns {Object} Returns the new inverted object.
- * @example
- *
- * var object = { 'a': 1, 'b': 2, 'c': 1 };
- *
- * _.invert(object);
- * // => { '1': 'c', '2': 'b' }
- */
- var invert = createInverter(function(result, value, key) {
- if (value != null &&
- typeof value.toString != 'function') {
- value = nativeObjectToString.call(value);
- }
-
- result[value] = key;
- }, constant(identity));
-
- /**
- * This method is like `_.invert` except that the inverted object is generated
- * from the results of running each element of `object` thru `iteratee`. The
- * corresponding inverted value of each inverted key is an array of keys
- * responsible for generating the inverted value. The iteratee is invoked
- * with one argument: (value).
- *
- * @static
- * @memberOf _
- * @since 4.1.0
- * @category Object
- * @param {Object} object The object to invert.
- * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
- * @returns {Object} Returns the new inverted object.
- * @example
- *
- * var object = { 'a': 1, 'b': 2, 'c': 1 };
- *
- * _.invertBy(object);
- * // => { '1': ['a', 'c'], '2': ['b'] }
- *
- * _.invertBy(object, function(value) {
- * return 'group' + value;
- * });
- * // => { 'group1': ['a', 'c'], 'group2': ['b'] }
- */
- var invertBy = createInverter(function(result, value, key) {
- if (value != null &&
- typeof value.toString != 'function') {
- value = nativeObjectToString.call(value);
- }
-
- if (hasOwnProperty.call(result, value)) {
- result[value].push(key);
- } else {
- result[value] = [key];
- }
- }, getIteratee);
-
- /**
- * Invokes the method at `path` of `object`.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Object
- * @param {Object} object The object to query.
- * @param {Array|string} path The path of the method to invoke.
- * @param {...*} [args] The arguments to invoke the method with.
- * @returns {*} Returns the result of the invoked method.
- * @example
- *
- * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] };
- *
- * _.invoke(object, 'a[0].b.c.slice', 1, 3);
- * // => [2, 3]
- */
- var invoke = baseRest(baseInvoke);
-
- /**
- * Creates an array of the own enumerable property names of `object`.
- *
- * **Note:** Non-object values are coerced to objects. See the
- * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
- * for more details.
- *
- * @static
- * @since 0.1.0
- * @memberOf _
- * @category Object
- * @param {Object} object The object to query.
- * @returns {Array} Returns the array of property names.
- * @example
- *
- * function Foo() {
- * this.a = 1;
- * this.b = 2;
- * }
- *
- * Foo.prototype.c = 3;
- *
- * _.keys(new Foo);
- * // => ['a', 'b'] (iteration order is not guaranteed)
- *
- * _.keys('hi');
- * // => ['0', '1']
- */
- function keys(object) {
- return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
- }
-
- /**
- * Creates an array of the own and inherited enumerable property names of `object`.
- *
- * **Note:** Non-object values are coerced to objects.
- *
- * @static
- * @memberOf _
- * @since 3.0.0
- * @category Object
- * @param {Object} object The object to query.
- * @returns {Array} Returns the array of property names.
- * @example
- *
- * function Foo() {
- * this.a = 1;
- * this.b = 2;
- * }
- *
- * Foo.prototype.c = 3;
- *
- * _.keysIn(new Foo);
- * // => ['a', 'b', 'c'] (iteration order is not guaranteed)
- */
- function keysIn(object) {
- return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);
- }
-
- /**
- * The opposite of `_.mapValues`; this method creates an object with the
- * same values as `object` and keys generated by running each own enumerable
- * string keyed property of `object` thru `iteratee`. The iteratee is invoked
- * with three arguments: (value, key, object).
- *
- * @static
- * @memberOf _
- * @since 3.8.0
- * @category Object
- * @param {Object} object The object to iterate over.
- * @param {Function} [iteratee=_.identity] The function invoked per iteration.
- * @returns {Object} Returns the new mapped object.
- * @see _.mapValues
- * @example
- *
- * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {
- * return key + value;
- * });
- * // => { 'a1': 1, 'b2': 2 }
- */
- function mapKeys(object, iteratee) {
- var result = {};
- iteratee = getIteratee(iteratee, 3);
-
- baseForOwn(object, function(value, key, object) {
- baseAssignValue(result, iteratee(value, key, object), value);
- });
- return result;
- }
-
- /**
- * Creates an object with the same keys as `object` and values generated
- * by running each own enumerable string keyed property of `object` thru
- * `iteratee`. The iteratee is invoked with three arguments:
- * (value, key, object).
- *
- * @static
- * @memberOf _
- * @since 2.4.0
- * @category Object
- * @param {Object} object The object to iterate over.
- * @param {Function} [iteratee=_.identity] The function invoked per iteration.
- * @returns {Object} Returns the new mapped object.
- * @see _.mapKeys
- * @example
- *
- * var users = {
- * 'fred': { 'user': 'fred', 'age': 40 },
- * 'pebbles': { 'user': 'pebbles', 'age': 1 }
- * };
- *
- * _.mapValues(users, function(o) { return o.age; });
- * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
- *
- * // The `_.property` iteratee shorthand.
- * _.mapValues(users, 'age');
- * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
- */
- function mapValues(object, iteratee) {
- var result = {};
- iteratee = getIteratee(iteratee, 3);
-
- baseForOwn(object, function(value, key, object) {
- baseAssignValue(result, key, iteratee(value, key, object));
- });
- return result;
- }
-
- /**
- * This method is like `_.assign` except that it recursively merges own and
- * inherited enumerable string keyed properties of source objects into the
- * destination object. Source properties that resolve to `undefined` are
- * skipped if a destination value exists. Array and plain object properties
- * are merged recursively. Other objects and value types are overridden by
- * assignment. Source objects are applied from left to right. Subsequent
- * sources overwrite property assignments of previous sources.
- *
- * **Note:** This method mutates `object`.
- *
- * @static
- * @memberOf _
- * @since 0.5.0
- * @category Object
- * @param {Object} object The destination object.
- * @param {...Object} [sources] The source objects.
- * @returns {Object} Returns `object`.
- * @example
- *
- * var object = {
- * 'a': [{ 'b': 2 }, { 'd': 4 }]
- * };
- *
- * var other = {
- * 'a': [{ 'c': 3 }, { 'e': 5 }]
- * };
- *
- * _.merge(object, other);
- * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }
- */
- var merge = createAssigner(function(object, source, srcIndex) {
- baseMerge(object, source, srcIndex);
- });
-
- /**
- * This method is like `_.merge` except that it accepts `customizer` which
- * is invoked to produce the merged values of the destination and source
- * properties. If `customizer` returns `undefined`, merging is handled by the
- * method instead. The `customizer` is invoked with six arguments:
- * (objValue, srcValue, key, object, source, stack).
- *
- * **Note:** This method mutates `object`.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Object
- * @param {Object} object The destination object.
- * @param {...Object} sources The source objects.
- * @param {Function} customizer The function to customize assigned values.
- * @returns {Object} Returns `object`.
- * @example
- *
- * function customizer(objValue, srcValue) {
- * if (_.isArray(objValue)) {
- * return objValue.concat(srcValue);
- * }
- * }
- *
- * var object = { 'a': [1], 'b': [2] };
- * var other = { 'a': [3], 'b': [4] };
- *
- * _.mergeWith(object, other, customizer);
- * // => { 'a': [1, 3], 'b': [2, 4] }
- */
- var mergeWith = createAssigner(function(object, source, srcIndex, customizer) {
- baseMerge(object, source, srcIndex, customizer);
- });
-
- /**
- * The opposite of `_.pick`; this method creates an object composed of the
- * own and inherited enumerable property paths of `object` that are not omitted.
- *
- * **Note:** This method is considerably slower than `_.pick`.
- *
- * @static
- * @since 0.1.0
- * @memberOf _
- * @category Object
- * @param {Object} object The source object.
- * @param {...(string|string[])} [paths] The property paths to omit.
- * @returns {Object} Returns the new object.
- * @example
- *
- * var object = { 'a': 1, 'b': '2', 'c': 3 };
- *
- * _.omit(object, ['a', 'c']);
- * // => { 'b': '2' }
- */
- var omit = flatRest(function(object, paths) {
- var result = {};
- if (object == null) {
- return result;
- }
- var isDeep = false;
- paths = arrayMap(paths, function(path) {
- path = castPath(path, object);
- isDeep || (isDeep = path.length > 1);
- return path;
- });
- copyObject(object, getAllKeysIn(object), result);
- if (isDeep) {
- result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone);
- }
- var length = paths.length;
- while (length--) {
- baseUnset(result, paths[length]);
- }
- return result;
- });
-
- /**
- * The opposite of `_.pickBy`; this method creates an object composed of
- * the own and inherited enumerable string keyed properties of `object` that
- * `predicate` doesn't return truthy for. The predicate is invoked with two
- * arguments: (value, key).
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Object
- * @param {Object} object The source object.
- * @param {Function} [predicate=_.identity] The function invoked per property.
- * @returns {Object} Returns the new object.
- * @example
- *
- * var object = { 'a': 1, 'b': '2', 'c': 3 };
- *
- * _.omitBy(object, _.isNumber);
- * // => { 'b': '2' }
- */
- function omitBy(object, predicate) {
- return pickBy(object, negate(getIteratee(predicate)));
- }
-
- /**
- * Creates an object composed of the picked `object` properties.
- *
- * @static
- * @since 0.1.0
- * @memberOf _
- * @category Object
- * @param {Object} object The source object.
- * @param {...(string|string[])} [paths] The property paths to pick.
- * @returns {Object} Returns the new object.
- * @example
- *
- * var object = { 'a': 1, 'b': '2', 'c': 3 };
- *
- * _.pick(object, ['a', 'c']);
- * // => { 'a': 1, 'c': 3 }
- */
- var pick = flatRest(function(object, paths) {
- return object == null ? {} : basePick(object, paths);
- });
-
- /**
- * Creates an object composed of the `object` properties `predicate` returns
- * truthy for. The predicate is invoked with two arguments: (value, key).
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Object
- * @param {Object} object The source object.
- * @param {Function} [predicate=_.identity] The function invoked per property.
- * @returns {Object} Returns the new object.
- * @example
- *
- * var object = { 'a': 1, 'b': '2', 'c': 3 };
- *
- * _.pickBy(object, _.isNumber);
- * // => { 'a': 1, 'c': 3 }
- */
- function pickBy(object, predicate) {
- if (object == null) {
- return {};
- }
- var props = arrayMap(getAllKeysIn(object), function(prop) {
- return [prop];
- });
- predicate = getIteratee(predicate);
- return basePickBy(object, props, function(value, path) {
- return predicate(value, path[0]);
- });
- }
-
- /**
- * This method is like `_.get` except that if the resolved value is a
- * function it's invoked with the `this` binding of its parent object and
- * its result is returned.
- *
- * @static
- * @since 0.1.0
- * @memberOf _
- * @category Object
- * @param {Object} object The object to query.
- * @param {Array|string} path The path of the property to resolve.
- * @param {*} [defaultValue] The value returned for `undefined` resolved values.
- * @returns {*} Returns the resolved value.
- * @example
- *
- * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] };
- *
- * _.result(object, 'a[0].b.c1');
- * // => 3
- *
- * _.result(object, 'a[0].b.c2');
- * // => 4
- *
- * _.result(object, 'a[0].b.c3', 'default');
- * // => 'default'
- *
- * _.result(object, 'a[0].b.c3', _.constant('default'));
- * // => 'default'
- */
- function result(object, path, defaultValue) {
- path = castPath(path, object);
-
- var index = -1,
- length = path.length;
-
- // Ensure the loop is entered when path is empty.
- if (!length) {
- length = 1;
- object = undefined;
- }
- while (++index < length) {
- var value = object == null ? undefined : object[toKey(path[index])];
- if (value === undefined) {
- index = length;
- value = defaultValue;
- }
- object = isFunction(value) ? value.call(object) : value;
- }
- return object;
- }
-
- /**
- * Sets the value at `path` of `object`. If a portion of `path` doesn't exist,
- * it's created. Arrays are created for missing index properties while objects
- * are created for all other missing properties. Use `_.setWith` to customize
- * `path` creation.
- *
- * **Note:** This method mutates `object`.
- *
- * @static
- * @memberOf _
- * @since 3.7.0
- * @category Object
- * @param {Object} object The object to modify.
- * @param {Array|string} path The path of the property to set.
- * @param {*} value The value to set.
- * @returns {Object} Returns `object`.
- * @example
- *
- * var object = { 'a': [{ 'b': { 'c': 3 } }] };
- *
- * _.set(object, 'a[0].b.c', 4);
- * console.log(object.a[0].b.c);
- * // => 4
- *
- * _.set(object, ['x', '0', 'y', 'z'], 5);
- * console.log(object.x[0].y.z);
- * // => 5
- */
- function set(object, path, value) {
- return object == null ? object : baseSet(object, path, value);
- }
-
- /**
- * This method is like `_.set` except that it accepts `customizer` which is
- * invoked to produce the objects of `path`. If `customizer` returns `undefined`
- * path creation is handled by the method instead. The `customizer` is invoked
- * with three arguments: (nsValue, key, nsObject).
- *
- * **Note:** This method mutates `object`.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Object
- * @param {Object} object The object to modify.
- * @param {Array|string} path The path of the property to set.
- * @param {*} value The value to set.
- * @param {Function} [customizer] The function to customize assigned values.
- * @returns {Object} Returns `object`.
- * @example
- *
- * var object = {};
- *
- * _.setWith(object, '[0][1]', 'a', Object);
- * // => { '0': { '1': 'a' } }
- */
- function setWith(object, path, value, customizer) {
- customizer = typeof customizer == 'function' ? customizer : undefined;
- return object == null ? object : baseSet(object, path, value, customizer);
- }
-
- /**
- * Creates an array of own enumerable string keyed-value pairs for `object`
- * which can be consumed by `_.fromPairs`. If `object` is a map or set, its
- * entries are returned.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @alias entries
- * @category Object
- * @param {Object} object The object to query.
- * @returns {Array} Returns the key-value pairs.
- * @example
- *
- * function Foo() {
- * this.a = 1;
- * this.b = 2;
- * }
- *
- * Foo.prototype.c = 3;
- *
- * _.toPairs(new Foo);
- * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed)
- */
- var toPairs = createToPairs(keys);
-
- /**
- * Creates an array of own and inherited enumerable string keyed-value pairs
- * for `object` which can be consumed by `_.fromPairs`. If `object` is a map
- * or set, its entries are returned.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @alias entriesIn
- * @category Object
- * @param {Object} object The object to query.
- * @returns {Array} Returns the key-value pairs.
- * @example
- *
- * function Foo() {
- * this.a = 1;
- * this.b = 2;
- * }
- *
- * Foo.prototype.c = 3;
- *
- * _.toPairsIn(new Foo);
- * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed)
- */
- var toPairsIn = createToPairs(keysIn);
-
- /**
- * An alternative to `_.reduce`; this method transforms `object` to a new
- * `accumulator` object which is the result of running each of its own
- * enumerable string keyed properties thru `iteratee`, with each invocation
- * potentially mutating the `accumulator` object. If `accumulator` is not
- * provided, a new object with the same `[[Prototype]]` will be used. The
- * iteratee is invoked with four arguments: (accumulator, value, key, object).
- * Iteratee functions may exit iteration early by explicitly returning `false`.
- *
- * @static
- * @memberOf _
- * @since 1.3.0
- * @category Object
- * @param {Object} object The object to iterate over.
- * @param {Function} [iteratee=_.identity] The function invoked per iteration.
- * @param {*} [accumulator] The custom accumulator value.
- * @returns {*} Returns the accumulated value.
- * @example
- *
- * _.transform([2, 3, 4], function(result, n) {
- * result.push(n *= n);
- * return n % 2 == 0;
- * }, []);
- * // => [4, 9]
- *
- * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
- * (result[value] || (result[value] = [])).push(key);
- * }, {});
- * // => { '1': ['a', 'c'], '2': ['b'] }
- */
- function transform(object, iteratee, accumulator) {
- var isArr = isArray(object),
- isArrLike = isArr || isBuffer(object) || isTypedArray(object);
-
- iteratee = getIteratee(iteratee, 4);
- if (accumulator == null) {
- var Ctor = object && object.constructor;
- if (isArrLike) {
- accumulator = isArr ? new Ctor : [];
- }
- else if (isObject(object)) {
- accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {};
- }
- else {
- accumulator = {};
- }
- }
- (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) {
- return iteratee(accumulator, value, index, object);
- });
- return accumulator;
- }
-
- /**
- * Removes the property at `path` of `object`.
- *
- * **Note:** This method mutates `object`.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Object
- * @param {Object} object The object to modify.
- * @param {Array|string} path The path of the property to unset.
- * @returns {boolean} Returns `true` if the property is deleted, else `false`.
- * @example
- *
- * var object = { 'a': [{ 'b': { 'c': 7 } }] };
- * _.unset(object, 'a[0].b.c');
- * // => true
- *
- * console.log(object);
- * // => { 'a': [{ 'b': {} }] };
- *
- * _.unset(object, ['a', '0', 'b', 'c']);
- * // => true
- *
- * console.log(object);
- * // => { 'a': [{ 'b': {} }] };
- */
- function unset(object, path) {
- return object == null ? true : baseUnset(object, path);
- }
-
- /**
- * This method is like `_.set` except that accepts `updater` to produce the
- * value to set. Use `_.updateWith` to customize `path` creation. The `updater`
- * is invoked with one argument: (value).
- *
- * **Note:** This method mutates `object`.
- *
- * @static
- * @memberOf _
- * @since 4.6.0
- * @category Object
- * @param {Object} object The object to modify.
- * @param {Array|string} path The path of the property to set.
- * @param {Function} updater The function to produce the updated value.
- * @returns {Object} Returns `object`.
- * @example
- *
- * var object = { 'a': [{ 'b': { 'c': 3 } }] };
- *
- * _.update(object, 'a[0].b.c', function(n) { return n * n; });
- * console.log(object.a[0].b.c);
- * // => 9
- *
- * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; });
- * console.log(object.x[0].y.z);
- * // => 0
- */
- function update(object, path, updater) {
- return object == null ? object : baseUpdate(object, path, castFunction(updater));
- }
-
- /**
- * This method is like `_.update` except that it accepts `customizer` which is
- * invoked to produce the objects of `path`. If `customizer` returns `undefined`
- * path creation is handled by the method instead. The `customizer` is invoked
- * with three arguments: (nsValue, key, nsObject).
- *
- * **Note:** This method mutates `object`.
- *
- * @static
- * @memberOf _
- * @since 4.6.0
- * @category Object
- * @param {Object} object The object to modify.
- * @param {Array|string} path The path of the property to set.
- * @param {Function} updater The function to produce the updated value.
- * @param {Function} [customizer] The function to customize assigned values.
- * @returns {Object} Returns `object`.
- * @example
- *
- * var object = {};
- *
- * _.updateWith(object, '[0][1]', _.constant('a'), Object);
- * // => { '0': { '1': 'a' } }
- */
- function updateWith(object, path, updater, customizer) {
- customizer = typeof customizer == 'function' ? customizer : undefined;
- return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer);
- }
-
- /**
- * Creates an array of the own enumerable string keyed property values of `object`.
- *
- * **Note:** Non-object values are coerced to objects.
- *
- * @static
- * @since 0.1.0
- * @memberOf _
- * @category Object
- * @param {Object} object The object to query.
- * @returns {Array} Returns the array of property values.
- * @example
- *
- * function Foo() {
- * this.a = 1;
- * this.b = 2;
- * }
- *
- * Foo.prototype.c = 3;
- *
- * _.values(new Foo);
- * // => [1, 2] (iteration order is not guaranteed)
- *
- * _.values('hi');
- * // => ['h', 'i']
- */
- function values(object) {
- return object == null ? [] : baseValues(object, keys(object));
- }
-
- /**
- * Creates an array of the own and inherited enumerable string keyed property
- * values of `object`.
- *
- * **Note:** Non-object values are coerced to objects.
- *
- * @static
- * @memberOf _
- * @since 3.0.0
- * @category Object
- * @param {Object} object The object to query.
- * @returns {Array} Returns the array of property values.
- * @example
- *
- * function Foo() {
- * this.a = 1;
- * this.b = 2;
- * }
- *
- * Foo.prototype.c = 3;
- *
- * _.valuesIn(new Foo);
- * // => [1, 2, 3] (iteration order is not guaranteed)
- */
- function valuesIn(object) {
- return object == null ? [] : baseValues(object, keysIn(object));
- }
-
- /*------------------------------------------------------------------------*/
-
- /**
- * Clamps `number` within the inclusive `lower` and `upper` bounds.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Number
- * @param {number} number The number to clamp.
- * @param {number} [lower] The lower bound.
- * @param {number} upper The upper bound.
- * @returns {number} Returns the clamped number.
- * @example
- *
- * _.clamp(-10, -5, 5);
- * // => -5
- *
- * _.clamp(10, -5, 5);
- * // => 5
- */
- function clamp(number, lower, upper) {
- if (upper === undefined) {
- upper = lower;
- lower = undefined;
- }
- if (upper !== undefined) {
- upper = toNumber(upper);
- upper = upper === upper ? upper : 0;
- }
- if (lower !== undefined) {
- lower = toNumber(lower);
- lower = lower === lower ? lower : 0;
- }
- return baseClamp(toNumber(number), lower, upper);
- }
-
- /**
- * Checks if `n` is between `start` and up to, but not including, `end`. If
- * `end` is not specified, it's set to `start` with `start` then set to `0`.
- * If `start` is greater than `end` the params are swapped to support
- * negative ranges.
- *
- * @static
- * @memberOf _
- * @since 3.3.0
- * @category Number
- * @param {number} number The number to check.
- * @param {number} [start=0] The start of the range.
- * @param {number} end The end of the range.
- * @returns {boolean} Returns `true` if `number` is in the range, else `false`.
- * @see _.range, _.rangeRight
- * @example
- *
- * _.inRange(3, 2, 4);
- * // => true
- *
- * _.inRange(4, 8);
- * // => true
- *
- * _.inRange(4, 2);
- * // => false
- *
- * _.inRange(2, 2);
- * // => false
- *
- * _.inRange(1.2, 2);
- * // => true
- *
- * _.inRange(5.2, 4);
- * // => false
- *
- * _.inRange(-3, -2, -6);
- * // => true
- */
- function inRange(number, start, end) {
- start = toFinite(start);
- if (end === undefined) {
- end = start;
- start = 0;
- } else {
- end = toFinite(end);
- }
- number = toNumber(number);
- return baseInRange(number, start, end);
- }
-
- /**
- * Produces a random number between the inclusive `lower` and `upper` bounds.
- * If only one argument is provided a number between `0` and the given number
- * is returned. If `floating` is `true`, or either `lower` or `upper` are
- * floats, a floating-point number is returned instead of an integer.
- *
- * **Note:** JavaScript follows the IEEE-754 standard for resolving
- * floating-point values which can produce unexpected results.
- *
- * @static
- * @memberOf _
- * @since 0.7.0
- * @category Number
- * @param {number} [lower=0] The lower bound.
- * @param {number} [upper=1] The upper bound.
- * @param {boolean} [floating] Specify returning a floating-point number.
- * @returns {number} Returns the random number.
- * @example
- *
- * _.random(0, 5);
- * // => an integer between 0 and 5
- *
- * _.random(5);
- * // => also an integer between 0 and 5
- *
- * _.random(5, true);
- * // => a floating-point number between 0 and 5
- *
- * _.random(1.2, 5.2);
- * // => a floating-point number between 1.2 and 5.2
- */
- function random(lower, upper, floating) {
- if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) {
- upper = floating = undefined;
- }
- if (floating === undefined) {
- if (typeof upper == 'boolean') {
- floating = upper;
- upper = undefined;
- }
- else if (typeof lower == 'boolean') {
- floating = lower;
- lower = undefined;
- }
- }
- if (lower === undefined && upper === undefined) {
- lower = 0;
- upper = 1;
- }
- else {
- lower = toFinite(lower);
- if (upper === undefined) {
- upper = lower;
- lower = 0;
- } else {
- upper = toFinite(upper);
- }
- }
- if (lower > upper) {
- var temp = lower;
- lower = upper;
- upper = temp;
- }
- if (floating || lower % 1 || upper % 1) {
- var rand = nativeRandom();
- return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper);
- }
- return baseRandom(lower, upper);
- }
-
- /*------------------------------------------------------------------------*/
-
- /**
- * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).
- *
- * @static
- * @memberOf _
- * @since 3.0.0
- * @category String
- * @param {string} [string=''] The string to convert.
- * @returns {string} Returns the camel cased string.
- * @example
- *
- * _.camelCase('Foo Bar');
- * // => 'fooBar'
- *
- * _.camelCase('--foo-bar--');
- * // => 'fooBar'
- *
- * _.camelCase('__FOO_BAR__');
- * // => 'fooBar'
- */
- var camelCase = createCompounder(function(result, word, index) {
- word = word.toLowerCase();
- return result + (index ? capitalize(word) : word);
- });
-
- /**
- * Converts the first character of `string` to upper case and the remaining
- * to lower case.
- *
- * @static
- * @memberOf _
- * @since 3.0.0
- * @category String
- * @param {string} [string=''] The string to capitalize.
- * @returns {string} Returns the capitalized string.
- * @example
- *
- * _.capitalize('FRED');
- * // => 'Fred'
- */
- function capitalize(string) {
- return upperFirst(toString(string).toLowerCase());
- }
-
- /**
- * Deburrs `string` by converting
- * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)
- * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A)
- * letters to basic Latin letters and removing
- * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).
- *
- * @static
- * @memberOf _
- * @since 3.0.0
- * @category String
- * @param {string} [string=''] The string to deburr.
- * @returns {string} Returns the deburred string.
- * @example
- *
- * _.deburr('déjà vu');
- * // => 'deja vu'
- */
- function deburr(string) {
- string = toString(string);
- return string && string.replace(reLatin, deburrLetter).replace(reComboMark, '');
- }
-
- /**
- * Checks if `string` ends with the given target string.
- *
- * @static
- * @memberOf _
- * @since 3.0.0
- * @category String
- * @param {string} [string=''] The string to inspect.
- * @param {string} [target] The string to search for.
- * @param {number} [position=string.length] The position to search up to.
- * @returns {boolean} Returns `true` if `string` ends with `target`,
- * else `false`.
- * @example
- *
- * _.endsWith('abc', 'c');
- * // => true
- *
- * _.endsWith('abc', 'b');
- * // => false
- *
- * _.endsWith('abc', 'b', 2);
- * // => true
- */
- function endsWith(string, target, position) {
- string = toString(string);
- target = baseToString(target);
-
- var length = string.length;
- position = position === undefined
- ? length
- : baseClamp(toInteger(position), 0, length);
-
- var end = position;
- position -= target.length;
- return position >= 0 && string.slice(position, end) == target;
- }
-
- /**
- * Converts the characters "&", "<", ">", '"', and "'" in `string` to their
- * corresponding HTML entities.
- *
- * **Note:** No other characters are escaped. To escape additional
- * characters use a third-party library like [_he_](https://mths.be/he).
- *
- * Though the ">" character is escaped for symmetry, characters like
- * ">" and "/" don't need escaping in HTML and have no special meaning
- * unless they're part of a tag or unquoted attribute value. See
- * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)
- * (under "semi-related fun fact") for more details.
- *
- * When working with HTML you should always
- * [quote attribute values](http://wonko.com/post/html-escaping) to reduce
- * XSS vectors.
- *
- * @static
- * @since 0.1.0
- * @memberOf _
- * @category String
- * @param {string} [string=''] The string to escape.
- * @returns {string} Returns the escaped string.
- * @example
- *
- * _.escape('fred, barney, & pebbles');
- * // => 'fred, barney, & pebbles'
- */
- function escape(string) {
- string = toString(string);
- return (string && reHasUnescapedHtml.test(string))
- ? string.replace(reUnescapedHtml, escapeHtmlChar)
- : string;
- }
-
- /**
- * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+",
- * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`.
- *
- * @static
- * @memberOf _
- * @since 3.0.0
- * @category String
- * @param {string} [string=''] The string to escape.
- * @returns {string} Returns the escaped string.
- * @example
- *
- * _.escapeRegExp('[lodash](https://lodash.com/)');
- * // => '\[lodash\]\(https://lodash\.com/\)'
- */
- function escapeRegExp(string) {
- string = toString(string);
- return (string && reHasRegExpChar.test(string))
- ? string.replace(reRegExpChar, '\\$&')
- : string;
- }
-
- /**
- * Converts `string` to
- * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles).
- *
- * @static
- * @memberOf _
- * @since 3.0.0
- * @category String
- * @param {string} [string=''] The string to convert.
- * @returns {string} Returns the kebab cased string.
- * @example
- *
- * _.kebabCase('Foo Bar');
- * // => 'foo-bar'
- *
- * _.kebabCase('fooBar');
- * // => 'foo-bar'
- *
- * _.kebabCase('__FOO_BAR__');
- * // => 'foo-bar'
- */
- var kebabCase = createCompounder(function(result, word, index) {
- return result + (index ? '-' : '') + word.toLowerCase();
- });
-
- /**
- * Converts `string`, as space separated words, to lower case.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category String
- * @param {string} [string=''] The string to convert.
- * @returns {string} Returns the lower cased string.
- * @example
- *
- * _.lowerCase('--Foo-Bar--');
- * // => 'foo bar'
- *
- * _.lowerCase('fooBar');
- * // => 'foo bar'
- *
- * _.lowerCase('__FOO_BAR__');
- * // => 'foo bar'
- */
- var lowerCase = createCompounder(function(result, word, index) {
- return result + (index ? ' ' : '') + word.toLowerCase();
- });
-
- /**
- * Converts the first character of `string` to lower case.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category String
- * @param {string} [string=''] The string to convert.
- * @returns {string} Returns the converted string.
- * @example
- *
- * _.lowerFirst('Fred');
- * // => 'fred'
- *
- * _.lowerFirst('FRED');
- * // => 'fRED'
- */
- var lowerFirst = createCaseFirst('toLowerCase');
-
- /**
- * Pads `string` on the left and right sides if it's shorter than `length`.
- * Padding characters are truncated if they can't be evenly divided by `length`.
- *
- * @static
- * @memberOf _
- * @since 3.0.0
- * @category String
- * @param {string} [string=''] The string to pad.
- * @param {number} [length=0] The padding length.
- * @param {string} [chars=' '] The string used as padding.
- * @returns {string} Returns the padded string.
- * @example
- *
- * _.pad('abc', 8);
- * // => ' abc '
- *
- * _.pad('abc', 8, '_-');
- * // => '_-abc_-_'
- *
- * _.pad('abc', 3);
- * // => 'abc'
- */
- function pad(string, length, chars) {
- string = toString(string);
- length = toInteger(length);
-
- var strLength = length ? stringSize(string) : 0;
- if (!length || strLength >= length) {
- return string;
- }
- var mid = (length - strLength) / 2;
- return (
- createPadding(nativeFloor(mid), chars) +
- string +
- createPadding(nativeCeil(mid), chars)
- );
- }
-
- /**
- * Pads `string` on the right side if it's shorter than `length`. Padding
- * characters are truncated if they exceed `length`.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category String
- * @param {string} [string=''] The string to pad.
- * @param {number} [length=0] The padding length.
- * @param {string} [chars=' '] The string used as padding.
- * @returns {string} Returns the padded string.
- * @example
- *
- * _.padEnd('abc', 6);
- * // => 'abc '
- *
- * _.padEnd('abc', 6, '_-');
- * // => 'abc_-_'
- *
- * _.padEnd('abc', 3);
- * // => 'abc'
- */
- function padEnd(string, length, chars) {
- string = toString(string);
- length = toInteger(length);
-
- var strLength = length ? stringSize(string) : 0;
- return (length && strLength < length)
- ? (string + createPadding(length - strLength, chars))
- : string;
- }
-
- /**
- * Pads `string` on the left side if it's shorter than `length`. Padding
- * characters are truncated if they exceed `length`.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category String
- * @param {string} [string=''] The string to pad.
- * @param {number} [length=0] The padding length.
- * @param {string} [chars=' '] The string used as padding.
- * @returns {string} Returns the padded string.
- * @example
- *
- * _.padStart('abc', 6);
- * // => ' abc'
- *
- * _.padStart('abc', 6, '_-');
- * // => '_-_abc'
- *
- * _.padStart('abc', 3);
- * // => 'abc'
- */
- function padStart(string, length, chars) {
- string = toString(string);
- length = toInteger(length);
-
- var strLength = length ? stringSize(string) : 0;
- return (length && strLength < length)
- ? (createPadding(length - strLength, chars) + string)
- : string;
- }
-
- /**
- * Converts `string` to an integer of the specified radix. If `radix` is
- * `undefined` or `0`, a `radix` of `10` is used unless `value` is a
- * hexadecimal, in which case a `radix` of `16` is used.
- *
- * **Note:** This method aligns with the
- * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`.
- *
- * @static
- * @memberOf _
- * @since 1.1.0
- * @category String
- * @param {string} string The string to convert.
- * @param {number} [radix=10] The radix to interpret `value` by.
- * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
- * @returns {number} Returns the converted integer.
- * @example
- *
- * _.parseInt('08');
- * // => 8
- *
- * _.map(['6', '08', '10'], _.parseInt);
- * // => [6, 8, 10]
- */
- function parseInt(string, radix, guard) {
- if (guard || radix == null) {
- radix = 0;
- } else if (radix) {
- radix = +radix;
- }
- return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0);
- }
-
- /**
- * Repeats the given string `n` times.
- *
- * @static
- * @memberOf _
- * @since 3.0.0
- * @category String
- * @param {string} [string=''] The string to repeat.
- * @param {number} [n=1] The number of times to repeat the string.
- * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
- * @returns {string} Returns the repeated string.
- * @example
- *
- * _.repeat('*', 3);
- * // => '***'
- *
- * _.repeat('abc', 2);
- * // => 'abcabc'
- *
- * _.repeat('abc', 0);
- * // => ''
- */
- function repeat(string, n, guard) {
- if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) {
- n = 1;
- } else {
- n = toInteger(n);
- }
- return baseRepeat(toString(string), n);
- }
-
- /**
- * Replaces matches for `pattern` in `string` with `replacement`.
- *
- * **Note:** This method is based on
- * [`String#replace`](https://mdn.io/String/replace).
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category String
- * @param {string} [string=''] The string to modify.
- * @param {RegExp|string} pattern The pattern to replace.
- * @param {Function|string} replacement The match replacement.
- * @returns {string} Returns the modified string.
- * @example
- *
- * _.replace('Hi Fred', 'Fred', 'Barney');
- * // => 'Hi Barney'
- */
- function replace() {
- var args = arguments,
- string = toString(args[0]);
-
- return args.length < 3 ? string : string.replace(args[1], args[2]);
- }
-
- /**
- * Converts `string` to
- * [snake case](https://en.wikipedia.org/wiki/Snake_case).
- *
- * @static
- * @memberOf _
- * @since 3.0.0
- * @category String
- * @param {string} [string=''] The string to convert.
- * @returns {string} Returns the snake cased string.
- * @example
- *
- * _.snakeCase('Foo Bar');
- * // => 'foo_bar'
- *
- * _.snakeCase('fooBar');
- * // => 'foo_bar'
- *
- * _.snakeCase('--FOO-BAR--');
- * // => 'foo_bar'
- */
- var snakeCase = createCompounder(function(result, word, index) {
- return result + (index ? '_' : '') + word.toLowerCase();
- });
-
- /**
- * Splits `string` by `separator`.
- *
- * **Note:** This method is based on
- * [`String#split`](https://mdn.io/String/split).
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category String
- * @param {string} [string=''] The string to split.
- * @param {RegExp|string} separator The separator pattern to split by.
- * @param {number} [limit] The length to truncate results to.
- * @returns {Array} Returns the string segments.
- * @example
- *
- * _.split('a-b-c', '-', 2);
- * // => ['a', 'b']
- */
- function split(string, separator, limit) {
- if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) {
- separator = limit = undefined;
- }
- limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0;
- if (!limit) {
- return [];
- }
- string = toString(string);
- if (string && (
- typeof separator == 'string' ||
- (separator != null && !isRegExp(separator))
- )) {
- separator = baseToString(separator);
- if (!separator && hasUnicode(string)) {
- return castSlice(stringToArray(string), 0, limit);
- }
- }
- return string.split(separator, limit);
- }
-
- /**
- * Converts `string` to
- * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage).
- *
- * @static
- * @memberOf _
- * @since 3.1.0
- * @category String
- * @param {string} [string=''] The string to convert.
- * @returns {string} Returns the start cased string.
- * @example
- *
- * _.startCase('--foo-bar--');
- * // => 'Foo Bar'
- *
- * _.startCase('fooBar');
- * // => 'Foo Bar'
- *
- * _.startCase('__FOO_BAR__');
- * // => 'FOO BAR'
- */
- var startCase = createCompounder(function(result, word, index) {
- return result + (index ? ' ' : '') + upperFirst(word);
- });
-
- /**
- * Checks if `string` starts with the given target string.
- *
- * @static
- * @memberOf _
- * @since 3.0.0
- * @category String
- * @param {string} [string=''] The string to inspect.
- * @param {string} [target] The string to search for.
- * @param {number} [position=0] The position to search from.
- * @returns {boolean} Returns `true` if `string` starts with `target`,
- * else `false`.
- * @example
- *
- * _.startsWith('abc', 'a');
- * // => true
- *
- * _.startsWith('abc', 'b');
- * // => false
- *
- * _.startsWith('abc', 'b', 1);
- * // => true
- */
- function startsWith(string, target, position) {
- string = toString(string);
- position = position == null
- ? 0
- : baseClamp(toInteger(position), 0, string.length);
-
- target = baseToString(target);
- return string.slice(position, position + target.length) == target;
- }
-
- /**
- * Creates a compiled template function that can interpolate data properties
- * in "interpolate" delimiters, HTML-escape interpolated data properties in
- * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data
- * properties may be accessed as free variables in the template. If a setting
- * object is given, it takes precedence over `_.templateSettings` values.
- *
- * **Note:** In the development build `_.template` utilizes
- * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl)
- * for easier debugging.
- *
- * For more information on precompiling templates see
- * [lodash's custom builds documentation](https://lodash.com/custom-builds).
- *
- * For more information on Chrome extension sandboxes see
- * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval).
- *
- * @static
- * @since 0.1.0
- * @memberOf _
- * @category String
- * @param {string} [string=''] The template string.
- * @param {Object} [options={}] The options object.
- * @param {RegExp} [options.escape=_.templateSettings.escape]
- * The HTML "escape" delimiter.
- * @param {RegExp} [options.evaluate=_.templateSettings.evaluate]
- * The "evaluate" delimiter.
- * @param {Object} [options.imports=_.templateSettings.imports]
- * An object to import into the template as free variables.
- * @param {RegExp} [options.interpolate=_.templateSettings.interpolate]
- * The "interpolate" delimiter.
- * @param {string} [options.sourceURL='lodash.templateSources[n]']
- * The sourceURL of the compiled template.
- * @param {string} [options.variable='obj']
- * The data object variable name.
- * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
- * @returns {Function} Returns the compiled template function.
- * @example
- *
- * // Use the "interpolate" delimiter to create a compiled template.
- * var compiled = _.template('hello <%= user %>!');
- * compiled({ 'user': 'fred' });
- * // => 'hello fred!'
- *
- * // Use the HTML "escape" delimiter to escape data property values.
- * var compiled = _.template('<%- value %>');
- * compiled({ 'value': '
@@ -418,7 +417,7 @@ export default class App extends Component {
@@ -607,6 +606,7 @@ const App = () => {
Note that these cookies will only be sent on the first request unless you use the technique above for [setting custom headers on each page load](#Setting-Custom-Headers).
### Page navigation gesture and button support
+
We can provide support for conventional mobile page navigation: forward/back swipe gestures on iOS and the hardware back button/gesture on Android.
For iOS, you'll just need to use the [`allowsbackforwardnavigationgestures`](Reference.md#allowsbackforwardnavigationgestures) prop.
@@ -614,17 +614,10 @@ For iOS, you'll just need to use the [`allowsbackforwardnavigationgestures`](Ref
For Android, you need to use `BackHandler.addEventListener` and hook that up to call `goBack` on the `WebView`.
With functional React components, you can use `useRef` and `useEffect` (you'll need to import them from React if you aren't already) to allow users to navigate to the previous page when they press the back button like so:
+
```jsx
-import React, {
- useCallback,
- useEffect,
- useState,
- useRef,
-} from 'react';
-import {
- BackHandler,
- Platform,
-} from 'react-native';
+import React, { useCallback, useEffect, useState, useRef } from 'react';
+import { BackHandler, Platform } from 'react-native';
```
```jsx
@@ -649,10 +642,11 @@ useEffect(() => {
```
And add these prop to your `WebView` component:
+
```jsx
{
+ onLoadProgress={(event) => {
setCanGoBack(event.nativeEvent.canGoBack);
}}
/>
diff --git a/docs/Guide.portuguese.md b/docs/Guide.portuguese.md
index 553cf5a3e8..d58f39bd55 100644
--- a/docs/Guide.portuguese.md
+++ b/docs/Guide.portuguese.md
@@ -82,9 +82,7 @@ import { WebView } from 'react-native-webview';
class MyWeb extends Component {
render() {
- return (
-
- );
+ return ;
}
}
```
@@ -201,12 +199,12 @@ Normalmente, os aplicativos que não têm permissão para usar a câmera podem s
##### Verifique se há suporte para upload de arquivos, com `static isFileUploadSupported()`
-O upload de arquivo usando `` não é compatível com o Android 4.4 KitKat (consulte os [detalhes](https://github.com/delight-im/Android-AdvancedWebView/issues/4#issuecomment-70372146 )):
+O upload de arquivo usando `` não é compatível com o Android 4.4 KitKat (consulte os [detalhes](https://github.com/delight-im/Android-AdvancedWebView/issues/4#issuecomment-70372146)):
```javascript
-import { WebView } from "react-native-webview";
+import { WebView } from 'react-native-webview';
-WebView.isFileUploadSupported().then(res => {
+WebView.isFileUploadSupported().then((res) => {
if (res === true) {
// o upload de arquivos é suportado
} else {
@@ -275,7 +273,7 @@ Muitas vezes você vai querer enviar mensagens para as páginas da web carregada
Para fazer isso, o React Native WebView expõe três opções diferentes:
-1. Reagir Nativo -> Web: A prop `injectedJavaScript`
+1. Reagir Nativo -> Web: A prop `injectedJavaScript`
2. Reagir Nativo -> Web: O método `injectJavaScript`
3. Web -> React Native: O método `postMessage` e a prop `onMessage`
diff --git a/docs/README.french.md b/docs/README.french.md
index 62a5b39a54..6510201a68 100644
--- a/docs/README.french.md
+++ b/docs/README.french.md
@@ -13,10 +13,10 @@
Également beaucoup de temps personnel est investi pour maintenir ce projet, n'hésitez pas à nous sponsoriser, **ça aide vraiment.**
- [Thibault Malbranche](https://github.com/Titozzz) ([Twitter @titozzz](https://twitter.com/titozzz)) de [Brigad](https://www.brigad.co/fr-fr/about-us)
-[*Me Sponsor* ❤️ !](https://github.com/sponsors/Titozzz)
-
+ [_Me Sponsor_ ❤️ !](https://github.com/sponsors/Titozzz)
Windows et macOS sont maintenues par Microsoft, notamment:
+
- [Alexander Sklar](https://github.com/asklar) ([Twitter @alexsklar](https://twitter.com/alexsklar)) de [React Native for Windows](https://microsoft.github.io/react-native-windows/)
- [Chiara Mooney](https://github.com/chiaramooney) de [React Native for Windows @ Microsoft](https://microsoft.github.io/react-native-windows/)
@@ -27,21 +27,21 @@ Grand merci à [Jamon Holmgren](https://github.com/jamonholmgren) de [Infinite R
Maintenir la WebView est très compliqué, à cause de ses nombreux usages (rendering svgs, pdfs, login flows, et autres). On supporte également de nombreuses plateformes et les deux architectures de React Native.
Depuis que la WebView a été retirée du core, près de 500 PR ont été mergées.
-En considérant que nous possédons un temps limité, les issues github serviront principalement comme lieu d'échange pour la communauté, tandis que **nous prioriserons les reviews et les merges de pull requests**
+En considérant que nous possédons un temps limité, les issues github serviront principalement comme lieu d'échange pour la communauté, tandis que **nous prioriserons les reviews et les merges de pull requests**
### Platform compatibles
-Ce projet est compatible avec **iOS**, **Android**, **Windows** et **macOS**.
+Ce projet est compatible avec **iOS**, **Android**, **Windows** et **macOS**.
Ce projet supporte à la fois **l'ancienne** (paper) **et la nouvelle architecture** (fabric).
Ce projet est compatible avec [expo](https://docs.expo.dev/versions/latest/sdk/webview/).
-## Débuter
+## Débuter
Lisez attentivement notre guide (exclusivement en anglais) [Getting Started Guide](docs/Getting-Started.md). Si la moindre étape ne semble pas claire, merci de créer une **issue** détaillée.
## Versionnage
-Ce projet suit la [gestion sémantique de version](https://semver.org/). Nous n'hésitons pas à publier des modifications "breaking-change", mais elles seront intégrées dans une version majeure.
+Ce projet suit la [gestion sémantique de version](https://semver.org/). Nous n'hésitons pas à publier des modifications "breaking-change", mais elles seront intégrées dans une version majeure.
## Utilisation
@@ -54,8 +54,13 @@ import { WebView } from 'react-native-webview';
// ...
const MyWebComponent = () => {
- return ;
-}
+ return (
+
+ );
+};
```
Pour plus de détails, lisez la [Référence API](./docs/Reference.md) et le [Guide](./docs/Guide.md). Si vous êtes intéressé à contribuer, lisez le [Guide de contribution](./docs/Contributing.md).
diff --git a/docs/README.italian.md b/docs/README.italian.md
index c7d33ed202..c7cce17f34 100644
--- a/docs/README.italian.md
+++ b/docs/README.italian.md
@@ -5,32 +5,38 @@
[](https://www.npmjs.com/package/react-native-webview)

-**React Native WebView** è un componente WebView mantenuto dalla community per React Native. È un sostituto del WebView integrato, il quale è stato rimosso dal core.
+**React Native WebView** è un componente WebView mantenuto dalla community per React Native. È un sostituto del WebView integrato, il quale è stato rimosso dal core.
### Manutentori
+
**Un ringraziamento speciale a queste aziende** per averci concesso del tempo per lavorare su software open source. Si prega di notare che anche i mantainer dedicano molto del loro tempo libero a lavorare su questo progetto, quindi sentiti libero di sponsorizzarli: **fa davvero la differenza**.
- [Thibault Malbranche](https://github.com/Titozzz) ([Twitter @titozzz](https://twitter.com/titozzz)) di [Brigad](https://www.brigad.co/en-gb/about-us)
-[*Sponsorizzami* ❤️ !](https://github.com/sponsors/Titozzz)
+ [_Sponsorizzami_ ❤️ !](https://github.com/sponsors/Titozzz)
Windows e macOS sono gestiti da Microsoft, in particolare:
+
- [Alexander Sklar](https://github.com/asklar) ([Twitter @alexsklar](https://twitter.com/alexsklar)) di [React Native per Windows](https://microsoft.github.io/react-native-windows/)
- [Chiara Mooney](https://github.com/chiaramooney) di [React Native per Windows presso Microsoft](https://microsoft.github.io/react-native-windows/)
Un ringraziamento speciale va dato a [Jamon Holmgren](https://github.com/jamonholmgren) della [Infinite Red](https://infinite.red) per il prezioso aiuto fornito al repository quando aveva più tempo a disposizione.
### Esonero da responsabilità
+
Mantenere la WebView è molto complesso, poiché viene frequentemente impiegata in numerosi scenari d'uso diversi, come ad esempio la renderizzazione di SVG, PDF, flussi di accesso e altri ancora. Supportiamo inoltre numerose piattaforme e entrambe le architetture di React Native.
Dal momento che WebView è stato estratto dal core di React Native, sono state integrate quasi 500 pull request. Considerando che abbiamo un tempo limitato, gli issue serviranno principalmente come luogo di discussione per la comunità, mentre **daremo priorità alla revisione e all'integrazione delle pull request**.
### Compatibilità con le piattaforme
+
Questo progetto è compatibile con le seguenti piattaforme: **iOS**, **Android**, **Windows** e **macOS**. Supporta sia **la vecchia architettura** (paper) **che la nuova architettura** (fabric). Inoltre, è compatibile con [Expo](https://docs.expo.dev/versions/latest/sdk/webview/).
### Version
+
Questo progetto segue la convenzione del [versionamento semantico](https://semver.org/lang/it/). Non esitiamo a rilasciare modifiche che potrebbero causare incompatibilità (breaking changes), ma lo faremo all'interno di una versione principale.
### Utilizzo
+
Importa il componente `WebView` da `react-native-webview` per poi usarlo nel seguente modo:
```tsx
@@ -40,24 +46,34 @@ import { WebView } from 'react-native-webview';
// ...
const MyWebComponent = () => {
- return ;
-}
+ return (
+
+ );
+};
```
Per ulteriori informazioni, leggi il [riferimento alle API](Reference.italian.md) e la [guida](Guide.italian.md). Se sei interessato a dare il tuo contributo, consulta la [guida per i collaboratori](Contributing.italian.md).
### Problemi comuni
+
- Se riscontri `Invariant Violation: Native component for "RNCWebView does not exist"`, probabilmente significa che hai dimenticato di eseguire `react-native link` o c'è stato qualche errore durante il processo di collegamento.
- In caso di un errore di compilazione durante l'operazione `:app:mergeDexRelease`, devi abilitare il supporto multidex in `android/app/build.gradle`, come discusso in [questa issue](https://github.com/react-native-webview/react-native-webview/issues/1344#issuecomment-650544648).
### Contribuire
+
Le contribuzioni sono benvenute, per maggiori informazioni consulta la pagina [Contributing.md](Contributing.italian.md).
### Licenza
+
MIT
### Traduzioni
+
Questo readme è disponibile nelle seguenti lingue:
-- [Francese](README.french.md)
+
+- [Francese](README.french.md)
- [Inglese](../README.md)
-- [Portoghese brasiliano](README.portuguese.md)
\ No newline at end of file
+- [Portoghese brasiliano](README.portuguese.md)
diff --git a/docs/Reference.italian.md b/docs/Reference.italian.md
index a1330bba45..435356bda2 100644
--- a/docs/Reference.italian.md
+++ b/docs/Reference.italian.md
@@ -110,11 +110,13 @@ Questo documento elenca le attuali proprietà e metodi pubblici di React Native
## Props
### `source`[⬆](#props-index)
+
Carica HTML statico o un URI (con eventuali header) nella WebView. Si noti che l'HTML statico richiederà l'impostazione di [`originWhitelist`](Reference.italian.md#originWhiteList) a `["*"]`.
L'oggetto passato a `source` può avere una delle seguenti forme:
**Caricamento di un URI**
+
- `uri` (string) - L'URI da caricare nel `WebView`. Può essere un file locale o remoto e può essere modificato con lo stato o le props di React per navigare verso una nuova pagina.
- `method` (string) - Il metodo HTTP da utilizzare. Se non specificato, il valore predefinito è GET. Su Android e Windows, i metodi supportati sono solo GET e POST.
- `headers` (object) - Intestazioni HTTP aggiuntive da inviare con la richiesta. Su Android, queste possono essere utilizzate solo con richieste GET. Consulta la [Guida](Guida.italian.md#impostazione-degli-header-personalizzati) per ulteriori informazioni sull'impostazione di header personalizzati.
@@ -123,7 +125,7 @@ L'oggetto passato a `source` può avere una delle seguenti forme:
**HTML Statico**
_Note that using static HTML requires the WebView property [originWhiteList](Reference.italian.md#originWhiteList) to `['*']`. For some content, such as video embeds (e.g. Twitter or Facebook posts with video), the baseUrl needs to be set for the video playback to work_
-- `html` (string) - Una pagina HTML statica da visualizzare nel WebView.
+- `html` (string) - Una pagina HTML statica da visualizzare nel WebView.
- `baseUrl` (string) - L'URL di base da utilizzare per i link relativi nell'HTML. Questo viene utilizzato anche per l'header dell'origine con le richieste CORS effettuate dal WebView. Consulta la documentazione di [Android WebView](https://developer.android.com/reference/android/webkit/WebView#loadDataWithBaseURL) per ulteriori informazioni.
| Tipo | Obbligatorio |
@@ -133,24 +135,27 @@ _Note that using static HTML requires the WebView property [originWhiteList](Ref
---
### `automaticallyAdjustContentInsets`[⬆](#props-index)
+
Controlla se regolare l'inset del contenuto per le web view posizionate dietro una barra di navigazione, una barra delle schede o una barra degli strumenti. Il valore predefinito è `true`.
-| Tipo | Obbligatorio | Piattaforma |
-| ---- | ------------ | ------------ |
-| bool | No | iOS |
+| Tipo | Obbligatorio | Piattaforma |
+| ---- | ------------ | ----------- |
+| bool | No | iOS |
---
### `automaticallyAdjustsScrollIndicatorInsets`[⬆](#props-index)
+
Controlla se regolare l'inset dell'indicatore di scroll per le web view posizionate dietro una barra di navigazione, una barra delle schede o una barra degli strumenti. Il valore predefinito è `false`. (iOS 13+)
-| Tipo | Obbligatorio | Piattaforma |
-| ---- | ------------ | ------------ |
-| bool | No | iOS(13+) |
+| Tipo | Obbligatorio | Piattaforma |
+| ---- | ------------ | ----------- |
+| bool | No | iOS(13+) |
---
### `injectedJavaScript`[⬆](#props-index)
+
Imposta questo per fornire del codice JavaScript che verrà iniettato nella pagina web dopo il completamento del caricamento del documento, ma prima del completamento del caricamento di altre risorse secondarie.
Assicurati che la stringa abbia un tipo valido (`true` funziona) e non generi eccezioni.
@@ -167,7 +172,7 @@ N.B.: Windows non ha [supporto nativo per gli alert](https://github.com/Microsof
Esempio:
-Invia un messaggio contenente `window.location` sottoforma di un oggetto JSON da gestire tramite [`onMessage`](Reference.italian.md#onmessage):
+Invia un messaggio contenente `window.location` sottoforma di un oggetto JSON da gestire tramite [`onMessage`](Reference.italian.md#onmessage):
```jsx
const INJECTED_JAVASCRIPT = `(function() {
@@ -184,6 +189,7 @@ const INJECTED_JAVASCRIPT = `(function() {
---
### `injectedJavaScriptBeforeContentLoaded`[⬆](#props-index)
+
Imposta questo per passare del codice JavaScript che verrà iniettato nella pagina web dopo la creazione dell'elemento del documento, ma prima del completamento del caricamento di altre risorse secondarie.
Assicurati che la stringa abbia un tipo valido (`true` funziona) e non generi eccezioni.
@@ -201,7 +207,7 @@ Per saperne di più leggi la guida [Comunicazione tra JS e Native](Guide.italian
Esempio:
-Invia un messaggio contenente `window.location` sottoforma di un oggetto JSON da gestire tramite [`onMessage`](Reference.italian.md#onmessage). `window.ReactNativeWebView.postMessage` questa volta _sarà_ disponibile.
+Invia un messaggio contenente `window.location` sottoforma di un oggetto JSON da gestire tramite [`onMessage`](Reference.italian.md#onmessage). `window.ReactNativeWebView.postMessage` questa volta _sarà_ disponibile.
```jsx
const INJECTED_JAVASCRIPT = `(function() {
@@ -218,28 +224,31 @@ const INJECTED_JAVASCRIPT = `(function() {
---
### `injectedJavaScriptForMainFrameOnly`[⬆](#props-index)
+
If `true` (default; mandatory for Android), loads the `injectedJavaScript` only into the main frame.
If `false`, (only supported on iOS and macOS), loads it into all frames (e.g. iframes).
-| Tipo | Obbligatorio | Piattaforma |
-| ---- | ------------ | -------------------------------------------------------- |
+| Tipo | Obbligatorio | Piattaforma |
+| ---- | ------------ | ------------------------------------------------------ |
| bool | No | iOS e macOS (Android ha supporto solo quando è `true`) |
---
### `injectedJavaScriptBeforeContentLoadedForMainFrameOnly`[⬆](#props-index)
+
If `true` (default; mandatory for Android), loads the `injectedJavaScriptBeforeContentLoaded` only into the main frame.
If `false`, (only supported on iOS and macOS), loads it into all frames (e.g. iframes).
-| Tipo | Obbligatorio | Piattaforma |
-| ---- | ------------ | -------------------------------------------------------- |
+| Tipo | Obbligatorio | Piattaforma |
+| ---- | ------------ | ------------------------------------------------------ |
| bool | No | iOS e macOS (Android ha supporto solo quando è `true`) |
---
### `mediaPlaybackRequiresUserAction`[⬆](#props-index)
+
Boolean che determina se è necessario che l'audio e il video HTML5 richiedano all'utente di interagire prima di avviare la riproduzione. Il valore predefinito è `true`. (Versione minima dell'API Android 17).
NOTA: il valore predefinito `true` potrebbe causare il blocco del caricamento di alcuni video su iOS. Impostarlo su `false` potrebbe risolvere questo problema.
@@ -251,6 +260,7 @@ NOTA: il valore predefinito `true` potrebbe causare il blocco del caricamento di
---
### `nativeConfig`[⬆](#props-index)
+
Sovrascrive il componente nativo utilizzato per il render della WebView. Consente di utilizzare una WebView nativa personalizzata che usa lo stesso JavaScript della WebView originale.
La prop `nativeConfig` si aspetta un oggetto con le seguenti chiavi:
@@ -266,6 +276,7 @@ La prop `nativeConfig` si aspetta un oggetto con le seguenti chiavi:
---
### `onError`[⬆](#props-index)
+
Funzione che viene invocata quando il caricamento della `WebView` non riesce.
| Tipo | Obbligatorio |
@@ -307,6 +318,7 @@ Il `syntheticEvent` può essere interrotto nell'esecuzione dell'azione predefini
---
### `onLoad`[⬆](#props-index)
+
Funzione che viene invocata quando il caricamento della `WebView` è completato.
| Tipo | Obbligatorio |
@@ -339,6 +351,7 @@ url
---
### `onLoadEnd`[⬆](#props-index)
+
Funzione che viene invocata quando il caricamento della `WebView` va a buon fine o fallisce.
| Tipo | Obbligatorio |
@@ -372,6 +385,7 @@ url
---
### `onLoadStart`[⬆](#props-index)
+
Funzione che viene invocata quando il caricamento della `WebView` inizia.
| Tipo | Obbligatorio |
@@ -405,9 +419,10 @@ url
---
### `onLoadProgress`[⬆](#props-index)
+
Funzione che viene invocata quando la `WebView` sta caricando.
-| Tipo | Obbligatorio | Piattaforma |
+| Tipo | Obbligatorio | Piattaforma |
| -------- | ------------ | ------------------- |
| function | No | iOS, Android, macOS |
@@ -437,6 +452,7 @@ url
---
### `onHttpError`[⬆](#props-index)
+
Funzione che viene invocata quando la `WebView` riceve un errore HTTP.
> **_Nota_**
@@ -453,10 +469,7 @@ Esempio:
source={{ uri: 'https://reactnative.dev' }}
onHttpError={(syntheticEvent) => {
const { nativeEvent } = syntheticEvent;
- console.warn(
- 'WebView received error status code: ',
- nativeEvent.statusCode,
- );
+ console.warn('WebView received error status code: ', nativeEvent.statusCode);
}}
/>
```
@@ -480,6 +493,7 @@ url
---
### `onRenderProcessGone`[⬆](#props-index)
+
Funzione che viene invocata quando il processo della `WebView` si arresta in modo anomalo o viene interrotto dal sistema operativo su Android.
> **_Nota_**
@@ -494,12 +508,9 @@ Esempio:
```jsx
{
+ onRenderProcessGone={(syntheticEvent) => {
const { nativeEvent } = syntheticEvent;
- console.warn(
- 'La WebView ha crashato: ',
- nativeEvent.didCrash,
- );
+ console.warn('La WebView ha crashato: ', nativeEvent.didCrash);
}}
/>
```
@@ -509,9 +520,11 @@ La funzione passata a `onRenderProcessGone` viene chiamata con un evento sinteti
```
didCrash
```
+
---
### `onMessage`[⬆](#props-index)
+
Funzione che viene invocata quando la WebView chiama `window.ReactNativeWebView.postMessage`. Impostando questa proprietà, verrà iniettato questo oggetto globale nella WebView.
`window.ReactNativeWebView.postMessage` accetta un argomento, `data`, che sarà disponibile sull'oggetto evento come `event.nativeEvent.data`. `data` deve essere una stringa.
@@ -525,6 +538,7 @@ Per saperne di più leggi la guida [Comunicazione tra JS e Native](Guide.italian
---
### `onNavigationStateChange`[⬆](#props-index)
+
Funzione che viene invocata quando il caricamento del `WebView` inizia o termina.
| Tipo | Obbligatorio |
@@ -558,11 +572,12 @@ url
---
### `onContentProcessDidTerminate`[⬆](#props-index)
+
Funzione che viene invocata quando l'elaborazione del contenuto della `WebView` viene terminato.
-| Tipo | Obbligatorio | Piattaforma |
-| -------- | ------------ | --------------------------- |
-| function | No | iOS e macOS WKWebView |
+| Tipo | Obbligatorio | Piattaforma |
+| -------- | ------------ | --------------------- |
+| function | No | iOS e macOS WKWebView |
Le web view di iOS utilizzano un processo separato per il rendering e la gestione dei contenuti web. WebKit chiama questo metodo quando il processo per la web view specificata termina per qualsiasi motivo.
Il motivo non è necessariamente un crash. Ad esempio, poiché le web view di iOS non sono incluse nella RAM totale dell'app, possono essere terminate indipendentemente dall'app per liberare memoria per nuove app che l'utente sta aprendo. Non è insolito che le Web view vengano terminate dopo un po' di tempo in background.
@@ -594,6 +609,7 @@ url
---
### `onScroll`[⬆](#props-index)
+
Funzione che viene invocata quando viene generato l'evento di scorrimento (`scroll`) nella `WebView`.
| Tipo | Obbligatorio | Piattaforma |
@@ -605,9 +621,9 @@ Esempio:
```jsx
{
- const { contentOffset } = syntheticEvent.nativeEvent
- console.table(contentOffset)
+ onScroll={(syntheticEvent) => {
+ const { contentOffset } = syntheticEvent.nativeEvent;
+ console.table(contentOffset);
}}
/>
```
@@ -626,7 +642,8 @@ zoomScale
---
### `originWhitelist`[⬆](#props-index)
-Elenco di stringhe di origine consentite per la navigazione. Le stringhe consentono caratteri jolly (*) e vengono confrontate solo con l'origine (non l'URL completo). Se l'utente schiaccia per navigare verso una nuova pagina ma la nuova pagina non è in questa lista di controllo, l'URL verrà gestito dal sistema operativo. Le origini predefinite in lista bianca (whitelist o allowlist) sono "http://*" e "https://*".
+
+Elenco di stringhe di origine consentite per la navigazione. Le stringhe consentono caratteri jolly (_) e vengono confrontate solo con l'origine (non l'URL completo). Se l'utente schiaccia per navigare verso una nuova pagina ma la nuova pagina non è in questa lista di controllo, l'URL verrà gestito dal sistema operativo. Le origini predefinite in lista bianca (whitelist o allowlist) sono "http://_" e "https://\*".
| Tipo | Obbligatorio | Piattaforma |
| ---------------- | ------------ | ------------------- |
@@ -645,6 +662,7 @@ Esempio:
---
### `renderError`[⬆](#props-index)
+
Funzione che restituisce una View da mostrare in caso di errore.
| Tipo | Obbligatorio | Piattaforma |
@@ -665,6 +683,7 @@ La funzione passata a `renderError` verrà chiamata con il nome dell'errore.
---
### `renderLoading`[⬆](#props-index)
+
Funzione che restituisce un indicatore di caricamento. La prop `startInLoadingState` deve essere impostata su `true` per utilizzare questa prop.
| Tipo | Obbligatorio | Piattaforma |
@@ -684,15 +703,17 @@ Esempio:
---
### `scalesPageToFit`[⬆](#props-index)
+
Boolean che controlla se il contenuto web viene ridimensionato per adattarsi alla vista e consente all'utente di modificare la scala. Il valore predefinito è `true`.
-| Tipo | Obbligatorio | Piattaforma |
-| ---- | ------------ | ------------ |
-| bool | No | Android |
+| Tipo | Obbligatorio | Piattaforma |
+| ---- | ------------ | ----------- |
+| bool | No | Android |
---
### `onShouldStartLoadWithRequest`[⬆](#props-index)
+
Funzione che consente la gestione personalizzata di qualsiasi richiesta della web view. Restituisci `true` dalla funzione per continuare a caricare la richiesta e `false` per interrompere il caricamento.
Su Android, non viene chiamata durante il primo caricamento.
@@ -731,6 +752,7 @@ isTopFrame (solo iOS)
---
### `startInLoadingState`[⬆](#props-index)
+
Boolean che forza la `WebView` a mostrare una View di caricamento durante il primo caricamento. Questa prop dev'essere impostata su `true` affinché la prop `renderLoading` funzioni.
| Tipo | Obbligatorio | Piattaforma |
@@ -740,6 +762,7 @@ Boolean che forza la `WebView` a mostrare una View di caricamento durante il pri
---
### `style`[⬆](#props-index)
+
[Style](https://reactnative.dev/docs/view-style-props) ti permette di personalizzare lo stile della `WebView`. Nota che ci sono stili predefiniti (ad esempio: è necessario aggiungere `flex: 0` allo stile se si desidera utilizzare la proprietà `height`).
| Tipo | Obbligatorio |
@@ -758,6 +781,7 @@ Esempio:
---
### `containerStyle`[⬆](#props-index)
+
[Style](https://reactnative.dev/docs/view-style-props) che consente di personalizzare lo stile del contenitore della `WebView`. Nota che ci sono stili predefiniti (ad esempio: è necessario aggiungere `flex: 0` allo stile se si desidera utilizzare la proprietà `height`).
| Tipo | Obbligatorio |
@@ -776,26 +800,30 @@ Esempio:
---
### `decelerationRate`[⬆](#props-index)
+
Un numero in virgola mobile che determina quanto rapidamente lo scroll nella view decelera dopo che l'utente ha sollevato il dito. È possibile utilizzare anche i valori di stringa `"normal"` e `"fast"` che corrispondono alle impostazioni sottostanti di iOS per `UIScrollViewDecelerationRateNormal` e `UIScrollViewDecelerationRateFast` rispettivamente:
+
- `normal`: 0,998
- `fast`: 0,99 (impostazione predefinita per la web view di iOS)
-| Tipo | Obbligatorio | Piattaforma |
-| ------ | ------------ | ------------ |
-| number | No | iOS |
+| Tipo | Obbligatorio | Piattaforma |
+| ------ | ------------ | ----------- |
+| number | No | iOS |
---
### `domStorageEnabled`[⬆](#props-index)
+
Valore booleano per controllare se il DOM Storage è abilitato. Usato solo in Android.
-| Tipo | Obbligatorio | Piattaforma |
-| ---- | ------------ | ------------ |
-| bool | No | Android |
+| Tipo | Obbligatorio | Piattaforma |
+| ---- | ------------ | ----------- |
+| bool | No | Android |
---
### `javaScriptEnabled`[⬆](#props-index)
+
Valore booleano per abilitare JavaScript nella `WebView`. Il valore predefinito è `true`.
| Tipo | Obbligatorio |
@@ -805,6 +833,7 @@ Valore booleano per abilitare JavaScript nella `WebView`. Il valore predefinito
---
### `javaScriptCanOpenWindowsAutomatically`[⬆](#props-index)
+
Una boolean che indica se JavaScript può aprire finestre senza chel'utente interagisca. Il valore predefinito è `false`.
| Tipo | Obbligatorio |
@@ -814,6 +843,7 @@ Una boolean che indica se JavaScript può aprire finestre senza chel'utente inte
---
### `androidLayerType`[⬆](#props-index)
+
Specifica il tipo di layer.
I possibili valori per `androidLayerType` sono:
@@ -822,14 +852,14 @@ I possibili valori per `androidLayerType` sono:
- `software`: la view ha un layer software. Un layer software è supportato da un bitmap e fa sì che la view venga renderizzata utilizzando la pipeline di rendering software di Android, anche se l'accelerazione hardware è abilitata.
- `hardware`: la view ha un layer hardware. Un layer hardware è supportato da una texture specifica dell'hardware e fa sì che la view venga renderizzata utilizzando la pipeline di rendering hardware di Android, ma solo se l'accelerazione hardware è abilitata per la gerarchia delle view.
-
-| Tipo | Obbligatorio | Piattaforma |
-| ------ | ------------ | ------------ |
-| string | No | Android |
+| Tipo | Obbligatorio | Piattaforma |
+| ------ | ------------ | ----------- |
+| string | No | Android |
---
### `mixedContentMode`[⬆](#props-index)
+
Specifica la modalità di contenuto misto. Ad esempio, la WebView consentirà a un'origine sicura di caricare contenuti da qualsiasi altra origine.
I possibili valori per `mixedContentMode` sono:
@@ -838,36 +868,39 @@ I possibili valori per `mixedContentMode` sono:
- `always`: la WebView consentirà a un'origine sicura di caricare contenuti da qualsiasi altra origine, anche se questa origine non è sicura.
- `compatibility`: la WebView cercherà di essere compatibile con l'approccio di un web browser moderno per quanto riguarda i contenuti misti.
-| Tipo | Obbligatorio | Piattaforma |
-| ------ | ------------ | ------------ |
-| string | No | Android |
+| Tipo | Obbligatorio | Piattaforma |
+| ------ | ------------ | ----------- |
+| string | No | Android |
---
### `thirdPartyCookiesEnabled`[⬆](#props-index)
+
Boolean che abilita i cookie di terze parti nella WebView. Utilizzato solo su Android Lollipop e versioni successive, poiché i cookie di terze parti sono abilitati per impostazione predefinita su Android Kitkat e versioni precedenti e su iOS. Il valore predefinito è `true`. Per ulteriori informazioni sui cookie, leggi la [guida per come gestire i cookie](Guide.italian.md#gestione-dei-cookie).
-| Tipo | Obbligatorio | Piattaforma |
-| ---- | ------------ | ------------ |
-| bool | No | Android |
+| Tipo | Obbligatorio | Piattaforma |
+| ---- | ------------ | ----------- |
+| bool | No | Android |
---
### `userAgent`[⬆](#props-index)
+
Imposta l'user-agent per la WebView.
-| Tipo | Obbligatorio | Piattaforma |
-| ------ | ------------ | ----------------------- |
-| string | No | iOS, Android, macOS |
+| Tipo | Obbligatorio | Piattaforma |
+| ------ | ------------ | ------------------- |
+| string | No | iOS, Android, macOS |
---
### `applicationNameForUserAgent`[⬆](#props-index)
+
Aggiungi all'user-agent esistente. Impostare `userAgent` sovrascriverà questa opzione.
-| Tipo | Obbligatorio | Piattaforma |
-| ------ | ------------ | ----------------------- |
-| string | No | iOS, Android, macOS |
+| Tipo | Obbligatorio | Piattaforma |
+| ------ | ------------ | ------------------- |
+| string | No | iOS, Android, macOS |
```jsx
**NOTA**
>
> Per consentire la riproduzione inline dei video, non basta solo che questa proprietà sia impostata su `true`, ma l'elemento video nel documento HTML deve anche includere l'attributo `webkit-playsinline`.
-| Tipo | Obbligatorio | Piattaforma |
-| ---- | ------------ | ------------ |
-| bool | No | iOS |
+| Tipo | Obbligatorio | Piattaforma |
+| ---- | ------------ | ----------- |
+| bool | No | iOS |
---
+
### `allowsAirPlayForMediaPlayback`[⬆](#props-index)
+
Un valore booleano che indica se è consentito l'uso di AirPlay. Il valore predefinito è `false`.
-| Tipo | Obbligatorio | Piattaforma |
-| ------- | ------------ | ----------------- |
-| boolean | No | iOS e macOS |
+| Tipo | Obbligatorio | Piattaforma |
+| ------- | ------------ | ----------- |
+| boolean | No | iOS e macOS |
---
### `bounces`[⬆](#props-index)
+
Valore booleano che determina se la web view effettua l'effetto di "rimbalzo" (bounce) quando raggiunge il bordo del contenuto. Il valore predefinito è `true`.
-| Tipo | Obbligatorio | Piattaforma |
-| ---- | ------------ | ------------ |
-| bool | No | iOS |
+| Tipo | Obbligatorio | Piattaforma |
+| ---- | ------------ | ----------- |
+| bool | No | iOS |
---
### `overScrollMode`[⬆](#props-index)
+
Specifica la modalità di overscroll.
I possibili valori per `overScrollMode` sono:
@@ -927,9 +966,9 @@ I possibili valori per `overScrollMode` sono:
- `content`: consente all'utente di eseguire l'overscroll su questa view solo se il contenuto è sufficientemente grande da poter usare lo scrolling in modo significativo, a condizione che sia una view che ha lo scrolling.
- `never`: Non consente mai all'utente di eseguire l'overscroll su questa view.
-| Tipo | Obbligatorio | Piattaforma |
-| ------ | ------------ | ------------ |
-| string | No | Android |
+| Tipo | Obbligatorio | Piattaforma |
+| ------ | ------------ | ----------- |
+| string | No | Android |
---
@@ -937,44 +976,49 @@ I possibili valori per `overScrollMode` sono:
La quantità di spazio tra il contenuto della WebView e i bordi della ScrollView. Impostato di default su {top: 0, left: 0, bottom: 0, right: 0}.
-| Tipo | Obbligatorio | Piattaforma |
-| ------------------------------------------------------------------ | ------------ | ------------ |
-| object: {top: number, left: number, bottom: number, right: number} | No | iOS |
+| Tipo | Obbligatorio | Piattaforma |
+| ------------------------------------------------------------------ | ------------ | ----------- |
+| object: {top: number, left: number, bottom: number, right: number} | No | iOS |
---
### `contentInsetAdjustmentBehavior`[⬆](#props-index)
+
Questa proprietà specifica come gli inset della safe area vengono utilizzati per modificare l'area del contenuto della scroll view. Il valore predefinito di questa proprietà è "never" (mai). Disponibile su iOS 11 e versioni successive. Il valore Predefinito è `never`.
Valori possibili:
+
- `automatic` (automatico)
- `scrollableAxes` (assi scorrevoli)
- `never` (mai)
- `always` (sempre)
-| Tipo | Obbligatorio | Piattaforma |
-| ------ | ------------ | ------------ |
-| string | No | iOS |
+| Tipo | Obbligatorio | Piattaforma |
+| ------ | ------------ | ----------- |
+| string | No | iOS |
---
### `contentMode`[⬆](#props-index)
+
Controlla il tipo di contenuto da caricare. Disponibile su iOS 13 e versioni successive. Predefinito a `recommended` (consigliato), che carica contenuti per dispositivi mobili su iPhone e iPad Mini, ma contenuti per desktop su iPad più grandi.
Per ulteriori informazioni consulta [Introducing Desktop-class Browsing on iPad](https://developer.apple.com/videos/play/wwdc2019/203/).
Valori possibili:
+
- `recommended` (consigliato)
- `mobile`
- `desktop`
-| Tipo | Obbligatorio | Piattaforma |
-| ------ | ------------ | ------------ |
-| string | No | iOS |
+| Tipo | Obbligatorio | Piattaforma |
+| ------ | ------------ | ----------- |
+| string | No | iOS |
---
### `dataDetectorTypes`[⬆](#props-index)
+
I tipi di dati riconosciuti per la rilevazione dei link nel contenuto della web view. Di seguito sono riportati i possibili valori per `dataDetectorTypes`:
- `phoneNumber`
@@ -987,177 +1031,196 @@ I tipi di dati riconosciuti per la rilevazione dei link nel contenuto della web
- `flightNumber`
- `lookupSuggestion`
-| Tipo | Obbligatorio | Piattaforma |
-| ---------------- | ------------ | ------------ |
-| string o array | No | iOS |
+| Tipo | Obbligatorio | Piattaforma |
+| -------------- | ------------ | ----------- |
+| string o array | No | iOS |
---
### `scrollEnabled`[⬆](#props-index)
+
Boolean che determina se la funzionalità di scroll è abilitata nella `WebView`. Il valore predefinito è `true`. Impostando questo valore su `false`, la webview non sposterà il body del documento quando la tastiera appare sopra un campo di input.
-| Tipo | Obbligatorio | Piattaforma |
-| ---- | ------------ | ----------------- |
-| bool | No | iOS e macOS |
+| Tipo | Obbligatorio | Piattaforma |
+| ---- | ------------ | ----------- |
+| bool | No | iOS e macOS |
---
### `nestedScrollEnabled`[⬆](#props-index)
+
Boolean che determina se è possibile effettuare lo scroll nella `WebView` quando viene utilizzato all'interno di un `ScrollView` su Android. Il valore predefinito è `false`.
Impostando questo valore su `true`, verrà impedito alla `ScrollView` di effettuare lo scrolling quando si scorre all'interno della `WebView`.
-| Tipo | Obbligatorio | Piattaforma |
-| ---- | ------------ | ----------------- |
-| bool | No | Android |
+| Tipo | Obbligatorio | Piattaforma |
+| ---- | ------------ | ----------- |
+| bool | No | Android |
---
### `setBuiltInZoomControls`[⬆](#props-index)
+
Imposta se la WebView usa meccanismi di zoom integrati. Il valore predefinito è `true`. Impostando questo valore su `false`, verrà impedito l'uso del gesto di pinch (pizzico) per il controllo dello zoom.
-| Tipo | Obbligatorio | Piattaforma |
-| ---- | ------------ | ----------------- |
-| bool | No | Android |
+| Tipo | Obbligatorio | Piattaforma |
+| ---- | ------------ | ----------- |
+| bool | No | Android |
---
### `setDisplayZoomControls`[⬆](#props-index)
+
Imposta se la WebView deve mostrare i controlli di zoom sullo schermo quando si utilizzano i meccanismi di zoom integrati (vedi `setBuiltInZoomControls`). Il valore predefinito è `false`.
-| Tipo | Obbligatorio | Piattaforma |
-| ---- | ------------ | ----------------- |
-| bool | No | Android |
+| Tipo | Obbligatorio | Piattaforma |
+| ---- | ------------ | ----------- |
+| bool | No | Android |
---
### `directionalLockEnabled`[⬆](#props-index)
+
Un valore booleano che determina se lo scrolling è disabilitato per una direzione specifica. Il valore predefinito è `true`.
-| Tipo | Obbligatorio | Piattaforma |
-| ---- | ------------ | ------------ |
-| bool | No | iOS |
+| Tipo | Obbligatorio | Piattaforma |
+| ---- | ------------ | ----------- |
+| bool | No | iOS |
---
### `showsHorizontalScrollIndicator`[⬆](#props-index)
+
Boolean che determina se l'indicatore di scrolling orizzontale viene mostrato nella `WebView`. Il valore predefinito è `true`.
-| Tipo | Obbligatorio | Piattaforma |
-| ---- | ------------ | ----------------------- |
-| bool | No | iOS, Android, macOS |
+| Tipo | Obbligatorio | Piattaforma |
+| ---- | ------------ | ------------------- |
+| bool | No | iOS, Android, macOS |
---
### `showsVerticalScrollIndicator`[⬆](#props-index)
+
Boolean che determina se l'indicatore di scrolling verticale viene mostrato nella `WebView`. Il valore predefinito è `true`.
-| Tipo | Obbligatorio | Piattaforma |
-| ---- | ------------ | ----------------------- |
-| bool | No | iOS, Android, macOS |
+| Tipo | Obbligatorio | Piattaforma |
+| ---- | ------------ | ------------------- |
+| bool | No | iOS, Android, macOS |
---
### `geolocationEnabled`[⬆](#props-index)
+
Imposta se la geolocalizzazione è abilitata nella `WebView`. Il valore predefinito è `false`. Supportato solo su Android.
-| Tipo | Obbligatorio | Piattaforma |
-| ---- | ------------ | ------------ |
-| bool | No | Android |
+| Tipo | Obbligatorio | Piattaforma |
+| ---- | ------------ | ----------- |
+| bool | No | Android |
---
### `allowFileAccessFromFileURLs`[⬆](#props-index)
+
Il valore booleano determina se è consentito a JavaScript, in esecuzione all'interno di un URL con schema file, di accedere ai contenuti di altri URL con schema file. Il valore predefinito è `false`.
-| Tipo | Obbligatorio | Piattaforma |
-| ---- | ------------ | ----------------------- |
-| bool | No | iOS, Android, macOS |
+| Tipo | Obbligatorio | Piattaforma |
+| ---- | ------------ | ------------------- |
+| bool | No | iOS, Android, macOS |
---
### `allowUniversalAccessFromFileURLs`[⬆](#props-index)
+
Il valore booleano determina se è consentito a JavaScript, in esecuzione all'interno di un URL con schema file, di accedere ai contenuti di qualsiasi origine, compresi i contenuti di altri URL con schema file. Il valore predefinito è `false`.
-| Tipo | Obbligatorio | Piattaforma |
-| ---- | ------------ | ------------------------ |
-| bool | No | iOS, Android, macOS |
+| Tipo | Obbligatorio | Piattaforma |
+| ---- | ------------ | ------------------- |
+| bool | No | iOS, Android, macOS |
---
### `allowingReadAccessToURL`[⬆](#props-index)
+
Il valore di tipo stringa indica a quali URL il file della WebView può fare riferimento negli script, nelle richieste AJAX e negli import di CSS. Questo viene utilizzato solo per le WebView che vengono caricate con un `source.uri` impostato su un URL `'file://'`. Se non viene fornito, il valore predefinito è consentire solo l'accesso in lettura all'URL fornito in `source.uri` stesso.
-| Tipo | Obbligatorio | Piattaforma |
-| ------ | ------------ | ----------------- |
-| string | No | iOS e macOS |
+| Tipo | Obbligatorio | Piattaforma |
+| ------ | ------------ | ----------- |
+| string | No | iOS e macOS |
---
### `keyboardDisplayRequiresUserAction`[⬆](#props-index)
+
Se impostato su `false`, il contenuto web non mostra la tastiera mediante codice (programmatically). Il valore predefinito è `true`.
-| Tipo | Obbligatorio | Piattaforma |
-| ------- | ------------ | ------------ |
-| boolean | No | iOS |
+| Tipo | Obbligatorio | Piattaforma |
+| ------- | ------------ | ----------- |
+| boolean | No | iOS |
---
### `hideKeyboardAccessoryView`[⬆](#props-index)
+
Se impostato su `true`, nasconde la view accessorio della tastiera(< > e Fatto).
-| Tipo | Obbligatorio | Piattaforma |
-| ------- | ------------ | ------------ |
-| boolean | No | iOS |
+| Tipo | Obbligatorio | Piattaforma |
+| ------- | ------------ | ----------- |
+| boolean | No | iOS |
---
### `allowsBackForwardNavigationGestures`[⬆](#props-index)
+
Se impostato su `true`, sarà possibile utilizzare i gesti di scrolling orizzontale. Il valore predefinito è `false`.
-| Tipo | Obbligatorio | Piattaforma |
-| ------- | ------------ | ----------------- |
-| boolean | No | iOS e macOS |
+| Tipo | Obbligatorio | Piattaforma |
+| ------- | ------------ | ----------- |
+| boolean | No | iOS e macOS |
---
### `incognito`[⬆](#props-index)
+
Non memorizza alcun dato durante il ciclo di vita della WebView.
-| Tipo | Obbligatorio | Piattaforma |
-| ------- | ------------ | ----------------------- |
-| boolean | No | iOS, Android, macOS |
+| Tipo | Obbligatorio | Piattaforma |
+| ------- | ------------ | ------------------- |
+| boolean | No | iOS, Android, macOS |
---
### `allowFileAccess`[⬆](#props-index)
+
Se impostato su `true`, consentirà l'accesso ai file di sistema tramite URI `file://`. Il valore predefinito è `false`.
-| Tipo | Obbligatorio | Piattaforma |
-| ------- | ------------ | ------------ |
-| boolean | No | Android |
+| Tipo | Obbligatorio | Piattaforma |
+| ------- | ------------ | ----------- |
+| boolean | No | Android |
---
### `saveFormDataDisabled`[⬆](#props-index)
+
Imposta se la WebView deve disabilitare il salvataggio dei dati dei form. Il valore predefinito è `false`. Questa funzione non ha alcun effetto dall'API level 26 di Android in poi, in quanto è presente una funzionalità di compilazione automatica che memorizza i dati dei form.
-| Tipo | Obbligatorio | Piattaforma |
-| ------- | ------------ | ------------ |
-| boolean | No | Android |
+| Tipo | Obbligatorio | Piattaforma |
+| ------- | ------------ | ----------- |
+| boolean | No | Android |
---
### `cacheEnabled`[⬆](#props-index)
+
Imposta se la WebView deve utilizzare la cache del browser.
-| Tipo | Obbligatorio | Default | Piattaforma |
-| ------- | ------------ | ------- | ----------------------- |
-| boolean | No | true | iOS, Android, macOS |
+| Tipo | Obbligatorio | Default | Piattaforma |
+| ------- | ------------ | ------- | ------------------- |
+| boolean | No | true | iOS, Android, macOS |
---
### `cacheMode`[⬆](#props-index)
+
Sovrascrive il modo in cui viene usata la cache. Il modo in cui viene utilizzata la cache dipende dal tipo di navigazione. Per un normale caricamento della pagina, la cache viene controllata e il contenuto viene rivalidato se necessario. Quando si torna indietro, il contenuto non viene rivalidato, ma viene semplicemente recuperato dalla cache. Questa proprietà consente al client di sovrascrivere questo comportamento.
I valori possibili sono:
@@ -1167,47 +1230,51 @@ I valori possibili sono:
- `LOAD_NO_CACHE`: non utilizza la cache, carica dalla rete.
- `LOAD_CACHE_ONLY`: non utilizza la rete, carica dalla cache.
-| Tipo | Obbligatorio | Default | Piattaforma |
-| ------ | ------------ | ------------ | ------------ |
-| string | No | LOAD_DEFAULT | Android |
+| Tipo | Obbligatorio | Default | Piattaforma |
+| ------ | ------------ | ------------ | ----------- |
+| string | No | LOAD_DEFAULT | Android |
---
### `pagingEnabled`[⬆](#props-index)
+
Quando il valore di questa proprietà è impostato su `true`, la view di scrolling si fermerà sugli intervalli corrispondenti ai limiti della vista stessa quando l'utente effettua uno scroll. Il valore predefinito è `false`.
-| Tipo | Obbligatorio | Piattaforma |
-| ------- | ------------ | ------------ |
-| boolean | No | iOS |
+| Tipo | Obbligatorio | Piattaforma |
+| ------- | ------------ | ----------- |
+| boolean | No | iOS |
---
### `allowsLinkPreview`[⬆](#props-index)
+
Boolean che determina se la pressione su un link visualizza un'anteprima della destinazione del link. In iOS, questa proprietà è disponibile sui dispositivi che supportano il 3D Touch. In iOS 10 e versioni successive, il valore predefinito è `true`. Prima di iOS 10, il valore predefinito è `false`.
-| Tipo | Obbligatorio | Piattaforma |
-| ------- | ------------ | ----------------- |
-| boolean | No | iOS e macOS |
+| Tipo | Obbligatorio | Piattaforma |
+| ------- | ------------ | ----------- |
+| boolean | No | iOS e macOS |
---
### `sharedCookiesEnabled`[⬆](#props-index)
+
Imposta `true` se i cookie condivisi da `[NSHTTPCookieStorage sharedHTTPCookieStorage]` devono essere usati per ogni richiesta di caricamento nella WebView. Il valore predefinito è `false`. Per ulteriori informazioni sui cookie, leggi la [guida di gestione dei cookie](Guide.italian.md#gestione-dei-cookie)
-| Tipo | Obbligatorio | Piattaforma |
-| ------- | ------------ | ----------------- |
-| boolean | No | iOS e macOS |
+| Tipo | Obbligatorio | Piattaforma |
+| ------- | ------------ | ----------- |
+| boolean | No | iOS e macOS |
---
### `textZoom`[⬆](#props-index)
+
Se l'utente ha impostato una dimensione del carattere personalizzata nel sistema Android, si verifica una scala indesiderata dell'interfaccia del sito nella WebView.
Impostando la prop `textZoom` standard (100), questa conseguenza indesiderata scompare.
-| Tipo | Obbligatorio | Piattaforma |
-| ------ | ------------ | ------------ |
-| number | No | Android |
+| Tipo | Obbligatorio | Piattaforma |
+| ------ | ------------ | ----------- |
+| number | No | Android |
Esempio:
@@ -1218,11 +1285,12 @@ Esempio:
---
### `pullToRefreshEnabled`[⬆](#props-index)
+
Boolean che determina se è abilitato il gesto di trascinamento per aggiornare nella WebView. Il valore predefinito è `false`, il che significa che il gesto di trascinamento per aggiornare non è disponibile. Se impostato su `true`, abiliterà automaticamente la proprietà `bounces` a `true`, consentendo al contenuto di rimbalzare quando viene trascinato oltre i limiti.
-| Tipo | Obbligatorio | Piattaforma |
-| ------- | ------------ | ------------ |
-| boolean | No | iOS |
+| Tipo | Obbligatorio | Piattaforma |
+| ------- | ------------ | ----------- |
+| boolean | No | iOS |
### `refreshControlLightMode`[⬆](#props-index)
@@ -1236,15 +1304,17 @@ L'impostazione predefinita è "false", il che significa che il colore del contro
| boolean | No | iOS |
### `ignoreSilentHardwareSwitch`[⬆](#props-index)
+
(solo iOS)
Quando impostato su `true`, viene ignorato il pulsante del silenzioso dell'hardware fisico. Predefinito: `false`.
-| Tipo | Obbligatorio | Piattaforma |
-| ------- | ------------ | ------------ |
-| boolean | No | iOS |
+| Tipo | Obbligatorio | Piattaforma |
+| ------- | ------------ | ----------- |
+| boolean | No | iOS |
### `onFileDownload`[⬆](#props-index)
+
(solo iOS)
È una funzione che viene invocata quando il client ha bisogno di scaricare un file.
@@ -1268,21 +1338,22 @@ Esempio:
/>
```
-| Tipo | Obbligatorio | Piattaforma |
-| -------- | ------------ | ------------ |
-| function | No | iOS |
+| Tipo | Obbligatorio | Piattaforma |
+| -------- | ------------ | ----------- |
+| function | No | iOS |
---
### `limitsNavigationsToAppBoundDomains`[⬆](#props-index)
+
Se impostato su `true`, indica a WebKit che un WKWebView può navigare solo su domini legati all'applicazione. Applicabile solo su iOS 14 o versioni successive.
Una volta impostato, qualsiasi tentativo di navigare su una pagina che non ha un dominio legato all'applicazione fallirà con l'errore "App-bound domain failure" (mancato dominio legato all'applicazione).
Le applicazioni possono specificare fino a 10 domini "app-bound" utilizzando una nuova chiave `WKAppBoundDomains` nel file `Info.plist`. Per ulteriori informazioni, consulta [App-Bound Domains](https://webkit.org/blog/10882/app-bound-domains/).
-| Tipo | Obbligatorio | Piattaforma |
-| ------- | ------------ | ------------ |
-| boolean | No | iOS |
+| Tipo | Obbligatorio | Piattaforma |
+| ------- | ------------ | ----------- |
+| boolean | No | iOS |
Esempio:
@@ -1293,13 +1364,14 @@ Esempio:
---
### `textInteractionEnabled`[⬆](#props-index)
+
Se impostato su `false`, indica a WebKit che un WKWebView non interagirà con il testo e non mostrerà quindi un'area di selezione del testo. Applicabile solo su iOS 14.5 o versioni successive.
Il valore predefinito è `true`.
-| Tipo | Obbligatorio | Piattaforma |
-| ------- | ------------ | ------------ |
-| boolean | No | iOS |
+| Tipo | Obbligatorio | Piattaforma |
+| ------- | ------------ | ----------- |
+| boolean | No | iOS |
Esempio:
@@ -1310,6 +1382,7 @@ Esempio:
---
### `mediaCapturePermissionGrantType`[⬆](#props-index)
+
Questa prop specifica come gestire le richieste di autorizzazione per la cattura degli strumenti di comunicazione. Il valore predefinito è `prompt`, il che comporta che all'utente venga richiesta l'autorizzazione ripetutamente. Disponibile su iOS 15 e versioni successive.
I possibili valori sono:
@@ -1322,9 +1395,9 @@ I possibili valori sono:
Nota che anche una concessione può comportare una richiesta all'utente, ad esempio se l'autorizzazione non è mai stata richiesta all'utente in precedenza.
-| Tipo | Obbligatorio | Piattaforma |
-| ------ | ------------ | ------------ |
-| string | No | iOS |
+| Tipo | Obbligatorio | Piattaforma |
+| ------ | ------------ | ----------- |
+| string | No | iOS |
Esempio:
@@ -1335,11 +1408,12 @@ Esempio:
---
### `autoManageStatusBarEnabled`[⬆](#props-index)
+
Se impostato su `true`, la barra di stato verrà automaticamente nascosta/mostrata dalla WebView, in particolare quando si guarda un video a schermo intero. Se impostato su `false`, WebView non gestirà affatto la barra di stato. Il valore predefinito è `true`.
-| Tipo | Obbligatorio | Piattaforma |
-| ------- | ------------ | ------------ |
-| boolean | No | iOS |
+| Tipo | Obbligatorio | Piattaforma |
+| ------- | ------------ | ----------- |
+| boolean | No | iOS |
Esempio:
@@ -1348,12 +1422,13 @@ Esempio:
```
### `setSupportMultipleWindows`[⬆](#props-index)
-Imposta se la WebView supporta più finestre. Consulta la [documentazione di Android]('https://developer.android.com/reference/android/webkit/WebSettings#setSupportMultipleWindows(boolean)') per ulteriori informazioni.
+
+Imposta se la WebView supporta più finestre. Consulta la [documentazione di Android](<'https://developer.android.com/reference/android/webkit/WebSettings#setSupportMultipleWindows(boolean)'>) per ulteriori informazioni.
Impostando questo valore su `false`, si potrebbe esporre l'applicazione a questa [vulnerabilità](https://alesandroortiz.com/articles/uxss-android-webview-cve-2020-6506/), consentendo a un iframe maligno di sfuggire al DOM del livello superiore.
-| Tipo | Obbligatorio | Default | Piattaforma |
-| ------- | ------------ | ------- | ------------ |
-| boolean | No | true | Android |
+| Tipo | Obbligatorio | Default | Piattaforma |
+| ------- | ------------ | ------- | ----------- |
+| boolean | No | true | Android |
Esempio:
@@ -1362,18 +1437,19 @@ Esempio:
```
### `enableApplePay`[⬆](#props-index)
+
Una boolean che, quando impostata su `true`, renderizzerà la WebView con il supporto di Apple Pay. Una volta impostato, i siti web saranno in grado di invocare Apple Pay da React Native Webview.
Tuttavia, ciò comporta alcune limitazioni, ad esempio le funzionalità come [`injectJavaScript`](Reference.italian.md#injectjavascriptstr), la cronologia di HTML5, [`sharedCookiesEnabled`](Reference.italian.md#sharedCookiesEnabled), [`injectedJavaScript`](Reference.italian.md#injectedjavascript) e [`injectedJavaScriptBeforeContentLoaded`](Reference.italian.md#injectedjavascriptbeforecontentloaded) non funzioneranno. Consulta la [nota di rilascio di Apple Pay](https://developer.apple.com/documentation/safari-release-notes/safari-13-release-notes#Payment-Request-API) per ulteriori informazioni.
Se devi inviare messaggi all'app, la pagina web dovrà chiamare esplicitamente l'handler dei messaggi di WebKit e riceverli tramite l'handler `onMessage` nel lato di React Native.
```javascript
-window.webkit.messageHandlers.ReactNativeWebView.postMessage("ciao apple pay")
+window.webkit.messageHandlers.ReactNativeWebView.postMessage('ciao apple pay');
```
-| Tipo | Obbligatorio | Default | Piattaforma |
-| ------- | ------------ | ------- | ------------ |
-| boolean | No | false | iOS |
+| Tipo | Obbligatorio | Default | Piattaforma |
+| ------- | ------------ | ------- | ----------- |
+| boolean | No | false | iOS |
Esempio:
@@ -1382,15 +1458,16 @@ Esempio:
```
### `forceDarkOn`[⬆](#props-index)
+
Configurazione del tema scuro (Dark Mode).
-*NOTA*: L'impostazione della Dark Mode non è persistente. È necessario chiamare il metodo statico ogni volta che il processo dell'app viene avviato.
+_NOTA_: L'impostazione della Dark Mode non è persistente. È necessario chiamare il metodo statico ogni volta che il processo dell'app viene avviato.
-*NOTA*: Il passaggio da modalità giorno a modalità notte è una modifica di configurazione, quindi per l'impostazione predefinita l'attività verrà riavviata e registrerà i nuovi valori per attivare il tema. Presta attenzione quando sovrascrivi questo comportamento predefinito e assicurati che questo metodo venga comunque chiamato quando vengono apportate modifiche.
+_NOTA_: Il passaggio da modalità giorno a modalità notte è una modifica di configurazione, quindi per l'impostazione predefinita l'attività verrà riavviata e registrerà i nuovi valori per attivare il tema. Presta attenzione quando sovrascrivi questo comportamento predefinito e assicurati che questo metodo venga comunque chiamato quando vengono apportate modifiche.
-| Tipo | Obbligatorio | Piattaforma |
-| ------- | ------------ | ------------ |
-| boolean | No | Android |
+| Tipo | Obbligatorio | Piattaforma |
+| ------- | ------------ | ----------- |
+| boolean | No | Android |
Esempio:
@@ -1399,32 +1476,38 @@ Esempio:
```
### `menuItems`[⬆](#props-index)
+
Un array di oggetti di elementi di menu personalizzati che verranno aggiunti all'UIMenu che appare quando si seleziona del testo (appariranno dopo 'Copia' e 'Condividi...'). Utilizzato insieme a `onCustomMenuSelection`.
-| Tipo | Obbligatorio | Piattaforma |
-| ------------------------------------------------------------------ | ------------ | ------------ |
-| array of objects: {label: string, key: string} | No | iOS |
+| Tipo | Obbligatorio | Piattaforma |
+| ---------------------------------------------- | ------------ | ----------- |
+| array of objects: {label: string, key: string} | No | iOS |
Esempio:
```jsx
-
```
### `onCustomMenuSelection`[⬆](#props-index)
+
La funzione chiamata quando viene selezionato un elemento di menu personalizzato. Riceve un evento Native che include tre chiavi personalizzate: `label`, `key` e `selectedText`.
-| Tipo | Obbligatorio | Piattaforma |
-| ------------------------------------------------------------------ | ------------ | ------------ |
-| function | No | iOS |
+| Tipo | Obbligatorio | Piattaforma |
+| -------- | ------------ | ----------- |
+| function | No | iOS |
```javascript
{
const { label } = webViewEvent.nativeEvent; // Il nome dell'elemento di menu, i.e. 'Tweet'
const { key } = webViewEvent.nativeEvent; // La chiave dell'elemento di menu, i.e. 'tweet'
@@ -1434,7 +1517,9 @@ La funzione chiamata quando viene selezionato un elemento di menu personalizzato
```
### `basicAuthCredential`[⬆](#props-index)
+
Un oggetto che specifica le credenziali di un utente da usare per l'autenticazione di base.
+
- `username` (string): un nome utente usato per l'autenticazione di base.
- `password` (string): una password usata per l'autenticazione di base.
@@ -1443,11 +1528,12 @@ Un oggetto che specifica le credenziali di un utente da usare per l'autenticazio
| object | No |
### `useWebView2`[⬆](#props-index)
+
Usa il controllo WebView2 di WinUI al posto del controllo WebView come visualizzatore web nativo. Il controllo WebView2 è un controllo WinUI che renderizza il contenuto web utilizzando il motore di esecuzione Microsoft Edge (Chromium). L'opzione può essere attivata o disattivata durante l'esecuzione e supporta Fast Refresh. Per saperne di più leggi la sezione riguardante WebView2 nella [guida getting-started](Getting-Started.italian.md#3-supporto-per-webview2).
-| Tipo | Obbligatorio | Piattaforma |
-| ------- | ------------ | ------------ |
-| boolean | No | Windows |
+| Tipo | Obbligatorio | Piattaforma |
+| ------- | ------------ | ----------- |
+| boolean | No | Windows |
Esempio:
@@ -1456,11 +1542,12 @@ Esempio:
```
### `minimumFontSize`[⬆](#props-index)
+
Android impone una dimensione minima del carattere basata su questo valore. Un numero intero non negativo compreso tra `1` e `72`. Qualsiasi numero al di fuori di questo intervallo verrà limitato ai valori consentiti. Il valore predefinito è `8`. Se si utilizzano dimensioni del carattere più piccole e si riscontrano problemi nel visualizzare l'intera finestra su un unico schermo, si consiglia di impostare un valore più piccolo.
-| Tipo | Obbligatorio | Piattaforma |
-| ------ | ------------ | ------------ |
-| number | No | Android |
+| Tipo | Obbligatorio | Piattaforma |
+| ------ | ------------ | ----------- |
+| number | No | Android |
Esempio:
@@ -1469,42 +1556,48 @@ Esempio:
```
### `downloadingMessage`[⬆](#props-index)
+
Questo è il messaggio visualizzato nel Toast (finestra di dialogo o notifica) durante il download di un file tramite la WebView. Il messaggio predefinito è "Downloading".
-| Tipo | Obbligatorio | Piattaforma |
-| ------ | -------- | ------------ |
-| string | No | Android |
+| Tipo | Obbligatorio | Piattaforma |
+| ------ | ------------ | ----------- |
+| string | No | Android |
### `lackPermissionToDownloadMessage`[⬆](#props-index)
+
Questo è il messaggio visualizzato nel Toast (finestra di dialogo o notifica) quando la WebView non è in grado di scaricare un file. Il messaggio predefinito è "Cannot download files as permission was denied. Please provide permission to write to storage, in order to download files." (_Impossibile scaricare i file in quanto è stato negato l'accesso. Fornisci il permesso di scrittura sulla memoria per poter scaricare i file._).
-| Tipo | Obbligatorio | Piattaforma |
-| ------ | ------------ | ------------ |
-| string | No | Android |
+| Tipo | Obbligatorio | Piattaforma |
+| ------ | ------------ | ----------- |
+| string | No | Android |
### `allowsProtectedMedia`[⬆](#props-index)
+
Se impostato su `true`, la WebView può riprodurre contenuti multimediali protetti da DRM (Digital Rights Management). Il valore predefinito è `false`.
⚠️ L'impostazione di questa opzione su `false` non revoca automaticamente il permesso già concesso alla pagina web corrente. Per farlo, è necessario ricaricare la pagina. ⚠️
-| Tipo | Obbligatorio | Piattaforma |
-| ------- | ------------ | ------------ |
-| boolean | No | Android |
+| Tipo | Obbligatorio | Piattaforma |
+| ------- | ------------ | ----------- |
+| boolean | No | Android |
### `fraudulentWebsiteWarningEnabled`[⬆](#props-index)
+
Boolean che indica se la WebView mostra avvisi per contenuti sospetti di frode, come malware o tentativi di phishing. Il valore predefinito è `true`. (iOS 13+)
-| Tipo | Obbligatorio | Default | Piattaforma |
-| ------- | ------------ | ------- | ------------ |
-| boolean | No | true | iOS |
+| Tipo | Obbligatorio | Default | Piattaforma |
+| ------- | ------------ | ------- | ----------- |
+| boolean | No | true | iOS |
### `webviewDebuggingEnabled`[⬆](#props-index)
+
Valore che determina se la WebView può essere debuggata in remoto utilizzando Safari/Chrome. Il valore predefinito è `false`. Supportato su iOS a partire dalla versione 16.4, nelle versioni precedenti il debug è sempre abilitato di default.
-| Tipo | Obbligatorio | Piattaforma |
-| ------- | ------------ | -------------- |
-| boolean | No | iOS e Android |
+| Tipo | Obbligatorio | Piattaforma |
+| ------- | ------------ | ------------- |
+| boolean | No | iOS e Android |
## Methods
+
### `goForward()`[⬆](#methods-index)
```javascript
@@ -1578,7 +1671,7 @@ Se presente, toglie la popup di autocompletamento dal campo di form attualmente
(solo android)
```javascript
-clearCache(true)
+clearCache(true);
```
Cancella la cache delle risorse. Nota che la cache è specifica dell'applicazione, quindi questa operazione cancellerà la cache per tutte le WebView in uso. [developer.android.com reference]()
@@ -1594,10 +1687,12 @@ clearHistory();
Indica a questa WebView di cancellare la sua cronologia interna di pagine precedenti/successive.[developer.android.com reference]()
## Altri Documenti
-Fai anche riferimento alla nostra [Guida per Iniziare](Getting-Started.italian.md) e alla [Guida Approfondita](Guide.italian.md).
+Fai anche riferimento alla nostra [Guida per Iniziare](Getting-Started.italian.md) e alla [Guida Approfondita](Guide.italian.md).
### Traduzioni
+
Questo file è disponibile nelle seguenti lingue:
+
- [Inglese](Reference.md)
-- [Portoghese brasiliano](Reference.portuguese.md)
\ No newline at end of file
+- [Portoghese brasiliano](Reference.portuguese.md)
diff --git a/docs/Reference.md b/docs/Reference.md
index 897cada864..2bdfcb3971 100644
--- a/docs/Reference.md
+++ b/docs/Reference.md
@@ -53,6 +53,7 @@ This document lays out the current public properties and methods for the React N
- [`contentInsetAdjustmentBehavior`](Reference.md#contentInsetAdjustmentBehavior)
- [`contentMode`](Reference.md#contentMode)
- [`dataDetectorTypes`](Reference.md#datadetectortypes)
+- [`indicatorStyle`](Reference.md#indicatorStyle)
- [`scrollEnabled`](Reference.md#scrollenabled)
- [`nestedScrollEnabled`](Reference.md#nestedscrollenabled)
- [`setBuiltInZoomControls`](Reference.md#setBuiltInZoomControls)
@@ -93,6 +94,7 @@ This document lays out the current public properties and methods for the React N
- [`lackPermissionToDownloadMessage`](Reference.md#lackPermissionToDownloadMessage)
- [`allowsProtectedMedia`](Reference.md#allowsProtectedMedia)
- [`webviewDebuggingEnabled`](Reference.md#webviewDebuggingEnabled)
+- [`paymentRequestEnabled`](Reference.md#paymentRequestEnabled)
## Methods Index
@@ -257,21 +259,21 @@ If `false`, (only supported on iOS and macOS), loads it into all frames (e.g. if
Inject any JavaScript object into the webview so it is available to the JS running on the page.
-| Type | Required | Platform |
-| ---- | -------- | ------------------------------------------------- |
-| obj | No | iOS, Android |
+| Type | Required | Platform |
+| ---- | -------- | ------------ |
+| obj | No | iOS, Android |
Example:
Set a value to be used in JavaScript.
-Note: Any value in the object will be accessible to *all* frames of the webpage. If sensitive values are present please ensure that you have a strict Content Security Policy set up to avoid data leaking.
+Note: Any value in the object will be accessible to _all_ frames of the webpage. If sensitive values are present please ensure that you have a strict Content Security Policy set up to avoid data leaking.
```jsx
;
+/>
```
```html
@@ -513,10 +515,7 @@ Example:
source={{ uri: 'https://reactnative.dev' }}
onHttpError={(syntheticEvent) => {
const { nativeEvent } = syntheticEvent;
- console.warn(
- 'WebView received error status code: ',
- nativeEvent.statusCode,
- );
+ console.warn('WebView received error status code: ', nativeEvent.statusCode);
}}
/>
```
@@ -555,12 +554,9 @@ Example:
```jsx
{
+ onRenderProcessGone={(syntheticEvent) => {
const { nativeEvent } = syntheticEvent;
- console.warn(
- 'WebView Crashed: ',
- nativeEvent.didCrash,
- );
+ console.warn('WebView Crashed: ', nativeEvent.didCrash);
}}
/>
```
@@ -570,6 +566,7 @@ Function passed to `onRenderProcessGone` is called with a SyntheticEvent wrappin
```
didCrash
```
+
---
### `onMessage`[⬆](#props-index)
@@ -637,8 +634,8 @@ Example:
source={{ uri: 'https://reactnative.dev' }}
onOpenWindow={(syntheticEvent) => {
const { nativeEvent } = syntheticEvent;
- const { targetUrl } = nativeEvent
- console.log('Intercepted OpenWindow for', targetUrl)
+ const { targetUrl } = nativeEvent;
+ console.log('Intercepted OpenWindow for', targetUrl);
}}
/>
```
@@ -701,9 +698,9 @@ Example:
```jsx
{
- const { contentOffset } = syntheticEvent.nativeEvent
- console.table(contentOffset)
+ onScroll={(syntheticEvent) => {
+ const { contentOffset } = syntheticEvent.nativeEvent;
+ console.table(contentOffset);
}}
/>
```
@@ -723,7 +720,7 @@ zoomScale
### `originWhitelist`[⬆](#props-index)
-List of origin strings to allow being navigated to. The strings allow wildcards and get matched against _just_ the origin (not the full URL). If the user taps to navigate to a new page but the new page is not in this whitelist, the URL will be handled by the OS. The default whitelisted origins are "http://*" and "https://*".
+List of origin strings to allow being navigated to. The strings allow wildcards and get matched against _just_ the origin (not the full URL). If the user taps to navigate to a new page but the new page is not in this whitelist, the URL will be handled by the OS. The default whitelisted origins are "http://_" and "https://_".
| Type | Required | Platform |
| ---------------- | -------- | ------------------- |
@@ -897,7 +894,7 @@ A floating-point number that determines how quickly the scroll view decelerates
### `domStorageEnabled`[⬆](#props-index)
-Boolean value to control whether DOM Storage is enabled. Used only in Android.
+Boolean value to control whether DOM Storage is enabled. Used only in Android. The default value is `true`.
| Type | Required | Platform |
| ---- | -------- | -------- |
@@ -935,7 +932,6 @@ Possible values for `androidLayerType` are:
- `software` - The view has a software layer. A software layer is backed by a bitmap and causes the view to be rendered using Android's software rendering pipeline, even if hardware acceleration is enabled.
- `hardware` - The view has a hardware layer. A hardware layer is backed by a hardware specific texture and causes the view to be rendered using Android's hardware rendering pipeline, but only if hardware acceleration is turned on for the view hierarchy.
-
| Type | Required | Platform |
| ------ | -------- | -------- |
| string | No | Android |
@@ -1026,8 +1022,8 @@ Boolean value that indicates whether HTML5 videos can play Picture in Picture. T
> **NOTE**
>
-> In order to restrict playing video in picture in picture mode this props need to be set to `false`
-.
+> In order to restrict playing video in picture in picture mode this props need to be set to `false`.
+
| Type | Required | Platform |
| ---- | -------- | -------- |
| bool | No | iOS |
@@ -1149,15 +1145,25 @@ Boolean value that determines whether scrolling is enabled in the `WebView`. The
---
+### `indicatorStyle`[⬆](#props-index)
+
+The colorstyle of the scroll indicator. The default value is `default`.
+
+| Type | Required | Platform |
+| ------ | -------- | -------- |
+| string | No | iOS |
+
+---
+
### `nestedScrollEnabled`[⬆](#props-index)
Boolean value that determines whether scrolling is possible in the `WebView` when used inside a `ScrollView` on Android. The default value is `false`.
Setting this to `true` will prevent the `ScrollView` to scroll when scrolling from inside the `WebView`.
-| Type | Required | Platform |
-| ---- | -------- | ------------- |
-| bool | No | Android |
+| Type | Required | Platform |
+| ---- | -------- | -------- |
+| bool | No | Android |
---
@@ -1165,9 +1171,9 @@ Setting this to `true` will prevent the `ScrollView` to scroll when scrolling fr
Sets whether the WebView should use its built-in zoom mechanisms. The default value is `true`. Setting this to `false` will prevent the use of a pinch gesture to control zooming.
-| Type | Required | Platform |
-| ---- | -------- | ------------- |
-| bool | No | Android |
+| Type | Required | Platform |
+| ---- | -------- | -------- |
+| bool | No | Android |
---
@@ -1175,9 +1181,9 @@ Sets whether the WebView should use its built-in zoom mechanisms. The default va
Sets whether the WebView should display on-screen zoom controls when using the built-in zoom mechanisms (see `setBuiltInZoomControls`). The default value is `false`.
-| Type | Required | Platform |
-| ---- | -------- | ------------- |
-| bool | No | Android |
+| Type | Required | Platform |
+| ---- | -------- | -------- |
+| bool | No | Android |
---
@@ -1236,9 +1242,9 @@ Boolean that sets whether JavaScript running in the context of a file scheme URL
Boolean that sets whether JavaScript running in the context of a file scheme URL should be allowed to access content from any origin. Including accessing content from other file scheme URLs. The default value is `false`.
-| Type | Required | Platform |
-| ---- | -------- | -------------------- |
-| bool | No | iOS, Android, macOS |
+| Type | Required | Platform |
+| ---- | -------- | ------------------- |
+| bool | No | iOS, Android, macOS |
---
@@ -1416,6 +1422,7 @@ When set to `true` the hardware silent switch is ignored. Default: `false`
| boolean | No | iOS |
### `onFileDownload`[⬆](#props-index)
+
This property is iOS-only.
Function that is invoked when the client needs to download a file.
@@ -1507,9 +1514,9 @@ Possible values are:
- `underline`
- `share`
-| Type | Required | Default | Platform |
-| ---------------- | -------- | ------------ | -------- |
-| array of strings | No | [] | iOS |
+| Type | Required | Default | Platform |
+| ---------------- | -------- | ------- | -------- |
+| array of strings | No | [] | iOS |
### `mediaCapturePermissionGrantType`[⬆](#props-index)
@@ -1553,7 +1560,7 @@ Example:
### `setSupportMultipleWindows`[⬆](#props-index)
-Sets whether the WebView supports multiple windows. See [Android documentation]('https://developer.android.com/reference/android/webkit/WebSettings#setSupportMultipleWindows(boolean)') for more information.
+Sets whether the WebView supports multiple windows. See [Android documentation](<'https://developer.android.com/reference/android/webkit/WebSettings#setSupportMultipleWindows(boolean)'>) for more information.
Setting this to `false` can expose the application to this [vulnerability](https://alesandroortiz.com/articles/uxss-android-webview-cve-2020-6506/) allowing a malicious iframe to escape into the top layer DOM.
| Type | Required | Default | Platform |
@@ -1569,11 +1576,12 @@ Example:
### `enableApplePay`[⬆](#props-index)
A Boolean value which, when set to `true`, WebView will be rendered with Apple Pay support. Once set, websites will be able to invoke Apple Pay from React Native Webview.
-This comes with a cost features like [`injectJavaScript`](Reference.md#injectjavascriptstr), html5 History, [`sharedCookiesEnabled`](Reference.md#sharedCookiesEnabled), [`injectedJavaScript`](Reference.md#injectedjavascript), [`injectedJavaScriptBeforeContentLoaded`](Reference.md#injectedjavascriptbeforecontentloaded) will not work See [Apple Pay Release Note](https://developer.apple.com/documentation/safari-release-notes/safari-13-release-notes#Payment-Request-API).
+This comes with a cost features like [`injectJavaScript`](Reference.md#injectjavascriptstr), html5 History, [`sharedCookiesEnabled`](Reference.md#sharedCookiesEnabled), [`injectedJavaScript`](Reference.md#injectedjavascript), [`injectedJavaScriptBeforeContentLoaded`](Reference.md#injectedjavascriptbeforecontentloaded) will not work See [Apple Pay Release Note](https://developer.apple.com/documentation/safari-release-notes/safari-13-release-notes#Payment-Request-API).
If you are required to send message to App , webpage has to explicitly call webkit message handler and receive it on `onMessage` handler on react native side
+
```javascript
-window.webkit.messageHandlers.ReactNativeWebView.postMessage("hello apple pay")
+window.webkit.messageHandlers.ReactNativeWebView.postMessage('hello apple pay');
```
| Type | Required | Default | Platform |
@@ -1590,9 +1598,9 @@ Example:
Configuring Dark Theme
-*NOTE* : The force dark setting is not persistent. You must call the static method every time your app process is started.
+_NOTE_ : The force dark setting is not persistent. You must call the static method every time your app process is started.
-*NOTE* : The change from day<->night mode is a configuration change so by default the activity will be restarted and pickup the new values to apply the theme. Take care when overriding this default behavior to ensure this method is still called when changes are made.
+_NOTE_ : The change from day<->night mode is a configuration change so by default the activity will be restarted and pickup the new values to apply the theme. Take care when overriding this default behavior to ensure this method is still called when changes are made.
| Type | Required | Platform |
| ------- | -------- | -------- |
@@ -1606,29 +1614,37 @@ Example:
### `menuItems`[⬆](#props-index)
-An array of custom menu item objects that will be shown when selecting text. An empty array will suppress the menu. Used in tandem with `onCustomMenuSelection`
+An array of custom menu item objects that will be shown when selecting text. An empty array will suppress the menu. Used in tandem with `onCustomMenuSelection`
-| Type | Required | Platform |
-| ------------------------------------------------------------------ | -------- | -------- |
-| array of objects: {label: string, key: string} | No | iOS, Android |
+| Type | Required | Platform |
+| ---------------------------------------------- | -------- | ------------ |
+| array of objects: {label: string, key: string} | No | iOS, Android |
Example:
```jsx
-
+
```
### `onCustomMenuSelection`[⬆](#props-index)
-Function called when a custom menu item is selected. It receives a Native event, which includes three custom keys: `label`, `key` and `selectedText`.
+Function called when a custom menu item is selected. It receives a Native event, which includes three custom keys: `label`, `key` and `selectedText`.
-| Type | Required | Platform |
-| ------------------------------------------------------------------ | -------- | -------- |
-| function | No | iOS, Android |
+| Type | Required | Platform |
+| -------- | -------- | ------------ |
+| function | No | iOS, Android |
```jsx
{
const { label } = webViewEvent.nativeEvent; // The name of the menu item, i.e. 'Tweet'
const { key } = webViewEvent.nativeEvent; // The key of the menu item, i.e. 'tweet'
@@ -1714,9 +1730,18 @@ A Boolean value that indicates whether the web view shows warnings for suspected
Whether or not the webview can be debugged remotely using Safari / Chrome.
Default is `false`. Supported on iOS as of 16.4, previous versions always allow debugging by default.
+| Type | Required | Platform |
+| ------- | -------- | ------------- |
+| boolean | No | iOS & Android |
+
+### `paymentRequestEnabled`[⬆](#props-index)
+
+Whether or not the webview has the Payment Request API enabled. Default is `false`.
+This is needed for Google Pay to work within the WebView.
+
| Type | Required | Platform |
| ------- | -------- | -------- |
-| boolean | No | iOS & Android |
+| boolean | No | Android |
## Methods
diff --git a/docs/Reference.portuguese.md b/docs/Reference.portuguese.md
index c338c04f68..a0cf4d8de5 100644
--- a/docs/Reference.portuguese.md
+++ b/docs/Reference.portuguese.md
@@ -125,7 +125,7 @@ _Observe que usar HTML estático requer a propriedade WebView [originWhiteList](
- `baseUrl` (string) - A URL base a ser usada para quaisquer links relativos no HTML. Isso também é usado para o cabeçalho de origem com solicitações CORS feitas a partir da WebView. Ver [Documentação do Android WebView](https://developer.android.com/reference/android/webkit/WebView#loadDataWithBaseURL)
| Tipo | Requerido |
-| ------ | -------- |
+| ------ | --------- |
| object | Falso |
---
@@ -135,7 +135,7 @@ _Observe que usar HTML estático requer a propriedade WebView [originWhiteList](
Controla se a inserção de conteúdo deve ser ajustada para exibições da Web que são colocadas atrás de uma barra de navegação, barra de guias ou barra de ferramentas. O valor padrão é `true`.
| Tipo | Requerido | Plataforma |
-| ---- | -------- | ---------- |
+| ---- | --------- | ---------- |
| bool | Falso | iOS |
---
@@ -145,7 +145,7 @@ Controla se a inserção de conteúdo deve ser ajustada para exibições da Web
Controla se a inserção do indicador de rolagem deve ser ajustada para exibições da Web que são colocadas atrás de uma barra de navegação, barra de guias ou barra de ferramentas. O valor padrão `falso`. (iOS 13+)
| Tipo | Requerido | Plataforma |
-| ---- | -------- | ---------- |
+| ---- | --------- | ---------- |
| bool | Falso | iOS(13+) |
---
@@ -235,8 +235,8 @@ Se `true` (padrão; obrigatório para Android), carrega o `injectedJavaScriptBef
Se `false`, (suportado apenas em iOS e macOS), carrega-o em todos os quadros (por exemplo, iframes).
-| Tipo | Requerido | Plataforma |
-| ---- | --------- | ------------------------------------------------- |
+| Tipo | Requerido | Plataforma |
+| ---- | --------- | --------------------------------------------------- |
| bool | Não | iOS e macOS (`true` somente suportado para Android) |
---
@@ -463,10 +463,7 @@ Exemplo:
source={{ uri: 'https://reactnative.dev' }}
onHttpError={(syntheticEvent) => {
const { nativeEvent } = syntheticEvent;
- console.warn(
- 'Código de status de erro recebido da WebView: ',
- nativeEvent.statusCode,
- );
+ console.warn('Código de status de erro recebido da WebView: ', nativeEvent.statusCode);
}}
/>
```
@@ -505,12 +502,9 @@ Exemplo:
```jsx
{
+ onRenderProcessGone={(syntheticEvent) => {
const { nativeEvent } = syntheticEvent;
- console.warn(
- 'WebView falhou: ',
- nativeEvent.didCrash,
- );
+ console.warn('WebView falhou: ', nativeEvent.didCrash);
}}
/>
```
@@ -520,6 +514,7 @@ A função passada para `onRenderProcessGone` é chamada com um SyntheticEvent e
```
didCrash
```
+
---
### `onMessage`[⬆](#props-index)
@@ -574,9 +569,9 @@ url
Função que é invocada quando o processo de conteúdo da `WebView` é encerrado.
-| Tipo | Requerido | Plataforma |
-| -------- | --------- | ----------------------- |
-| function | Não | iOS e macOS WKWebView |
+| Tipo | Requerido | Plataforma |
+| -------- | --------- | --------------------- |
+| function | Não | iOS e macOS WKWebView |
Exemplo:
@@ -617,9 +612,9 @@ Exemplo:
```jsx
{
- const { contentOffset } = syntheticEvent.nativeEvent
- console.table(contentOffset)
+ onScroll={(syntheticEvent) => {
+ const { contentOffset } = syntheticEvent.nativeEvent;
+ console.table(contentOffset);
}}
/>
```
@@ -639,7 +634,7 @@ zoomScale
### `originWhitelist`[⬆](#props-index)
-Lista de strings de origem para permitir a navegação. As strings permitem curingas e são correspondidas com __somente a origem (não o URL completo). Se o usuário tocar para navegar para uma nova página, mas a nova página não estiver nesta lista de permissões, a URL será tratada pelo sistema operacional. As origens padrão da lista de permissões são "http://*" e "https://*".
+Lista de strings de origem para permitir a navegação. As strings permitem curingas e são correspondidas com \_\_somente a origem (não o URL completo). Se o usuário tocar para navegar para uma nova página, mas a nova página não estiver nesta lista de permissões, a URL será tratada pelo sistema operacional. As origens padrão da lista de permissões são "http://_" e "https://_".
| Tipo | Requerido | Plataforma |
| ---------------- | --------- | ------------------- |
@@ -932,15 +927,17 @@ Booleano que determina se os vídeos HTML5 são reproduzidos inline ou usam o co
| bool | Não | iOS |
---
+
### `allowsAirPlayForMediaPlayback`[⬆](#props-index)
Um valor booleano que indica se o AirPlay é permitido. O valor padrão é `falso`.
-| Tipo | Requerido | Plataforma |
-| ---- | --------- | --------------- |
-| bool | Não | iOS e macOS |
+| Tipo | Requerido | Plataforma |
+| ---- | --------- | ----------- |
+| bool | Não | iOS e macOS |
---
+
### `bounces`[⬆](#props-index)
Valor booleano que determina se a visualização da Web é rejeitada quando atinge a borda do conteúdo. O valor padrão é `true`.
@@ -972,7 +969,7 @@ Os valores possíveis para `overScrollMode` são:
A quantidade pela qual o conteúdo da visualização da web é inserido a partir das bordas da visualização de rolagem. Padrão {top: 0, left: 0, bottom: 0, right: 0}.
| Tipo | Requerido | Plataforma |
-| ----------------------------------------------------------------- | --------- | ---------- |
+| ------------------------------------------------------------------ | --------- | ---------- |
| object: {top: number, left: number, bottom: number, right: number} | Não | iOS |
---
@@ -1040,9 +1037,9 @@ Os valores possíveis para `dataDetectorTypes` são:
Valor booleano que determina se a rolagem está habilitada na `WebView`. O valor padrão é `true`. Definir isso como `false` impedirá que a visualização da Web mova o corpo do documento quando o teclado aparecer sobre uma entrada.
-| Tipo | Requerido | Plataforma |
-| ---- | --------- | --------------- |
-| bool | Não | iOS e macOS |
+| Tipo | Requerido | Plataforma |
+| ---- | --------- | ----------- |
+| bool | Não | iOS e macOS |
---
@@ -1052,9 +1049,9 @@ Valor booleano que determina se a rolagem é possível na `WebView` quando usado
Definir isso como `true` impedirá que o `ScrollView` role ao rolar de dentro do `WebView`.
-| Tipo | Requerido | Plataforma |
-| ---- | --------- | ------------- |
-| bool | Não | Android |
+| Tipo | Requerido | Plataforma |
+| ---- | --------- | ---------- |
+| bool | Não | Android |
---
@@ -1062,9 +1059,9 @@ Definir isso como `true` impedirá que o `ScrollView` role ao rolar de dentro do
Define se o WebView deve usar seus mecanismos de zoom integrados. O valor padrão é `true`. Definir isso como "falso" impedirá o uso de um gesto de pinça para controlar o zoom.
-| Tipo | Requerido | Plataforma |
-| ---- | --------- | ------------- |
-| bool | Não | Android |
+| Tipo | Requerido | Plataforma |
+| ---- | --------- | ---------- |
+| bool | Não | Android |
---
@@ -1072,9 +1069,9 @@ Define se o WebView deve usar seus mecanismos de zoom integrados. O valor padrã
Define se o WebView deve exibir controles de zoom na tela ao usar os mecanismos de zoom integrados (consulte `setBuiltInZoomControls`). O valor padrão é `falso`.
-| Tipo | Requerido | Plataforma |
-| ---- | --------- | ------------- |
-| bool | Não | Android |
+| Tipo | Requerido | Plataforma |
+| ---- | --------- | ---------- |
+| bool | Não | Android |
---
@@ -1133,9 +1130,9 @@ Booleano que define se o JavaScript executado no contexto de uma URL de esquema
Booleano que define se o JavaScript executado no contexto de uma URL de esquema de arquivo deve ter permissão para acessar conteúdo de qualquer origem. Incluindo o acesso ao conteúdo de outros URLs de esquema de arquivos. O valor padrão é `falso`.
-| Tipo | Requerido | Plataforma |
-| ---- | --------- | -------------------- |
-| bool | Não | iOS, Android, macOS |
+| Tipo | Requerido | Plataforma |
+| ---- | --------- | ------------------- |
+| bool | Não | iOS, Android, macOS |
---
@@ -1143,9 +1140,9 @@ Booleano que define se o JavaScript executado no contexto de uma URL de esquema
Um valor String que indica quais URLs o arquivo da WebView pode referenciar em scripts, solicitações AJAX e importações CSS. Isso é usado apenas para WebViews que são carregados com um source.uri definido como um URL `'file://'`. Se não for fornecido, o padrão é permitir apenas acesso de leitura à URL fornecida no próprio source.uri.
-| Tipo | Requerido | Plataforma |
-| ------ | --------- | ------------- |
-| string | Não | iOS e macOS |
+| Tipo | Requerido | Plataforma |
+| ------ | --------- | ----------- |
+| string | Não | iOS e macOS |
---
@@ -1173,9 +1170,9 @@ Se true, isso ocultará a visualização do acessório de teclado (< > e Feito).
Se for verdade, isso será capaz de gestos de furto horizontal. O valor padrão é `falso`.
-| Tipo | Requerido | Plataforma |
-| ------- | --------- | ------------- |
-| boolean | Não | iOS e macOS |
+| Tipo | Requerido | Plataforma |
+| ------- | --------- | ----------- |
+| boolean | Não | iOS e macOS |
---
@@ -1213,9 +1210,9 @@ Define se a WebView deve desabilitar o salvamento de dados de formulário. O val
Define se a WebView deve usar o cache do navegador.
-| Tipo | Requerido | Padrão | Plataforma |
-| ------- | --------- | ------- | ------------------- |
-| boolean | Não | true | iOS, Android, macOS |
+| Tipo | Requerido | Padrão | Plataforma |
+| ------- | --------- | ------ | ------------------- |
+| boolean | Não | true | iOS, Android, macOS |
---
@@ -1241,8 +1238,8 @@ Os valores possíveis são:
Se o valor desta propriedade for true, a visualização de rolagem para em múltiplos dos limites da visualização de rolagem quando o usuário rola. O valor padrão é falso.
| Tipo | Requerido | Plataforma |
-| ------- | --------- | -------- |
-| boolean | Não | iOS |
+| ------- | --------- | ---------- |
+| boolean | Não | iOS |
---
@@ -1250,9 +1247,9 @@ Se o valor desta propriedade for true, a visualização de rolagem para em múlt
Um valor booleano que determina se pressionar um link exibe uma visualização do destino do link. No iOS esta propriedade está disponível em dispositivos que suportam 3D Touch. No iOS 10 e posterior, o valor padrão é true; antes disso, o valor padrão é false.
-| Tipo | Requerido | Plataforma |
-| ------- | --------- | ------------- |
-| boolean | Não | iOS e macOS |
+| Tipo | Requerido | Plataforma |
+| ------- | --------- | ----------- |
+| boolean | Não | iOS e macOS |
---
@@ -1260,9 +1257,9 @@ Um valor booleano que determina se pressionar um link exibe uma visualização d
Defina `true` se os cookies compartilhados de `[NSHTTPCookieStorage sharedHTTPCookieStorage]` devem ser usados para cada solicitação de carregamento no WebView. O valor padrão é `falso`. Para saber mais sobre cookies, leia o [Guia](Guide.portuguese.md#Managing-Cookies)
-| Tipo | Requerido | Plataforma |
-| ------- | --------- | ------------- |
-| boolean | Não | iOS e macOS |
+| Tipo | Requerido | Plataforma |
+| ------- | --------- | ----------- |
+| boolean | Não | iOS e macOS |
---
@@ -1312,6 +1309,7 @@ Quando definido como true, o switch silencioso do hardware é ignorado. Padrão:
| boolean | Não | iOS |
### `onFileDownload`[⬆](#props-index)
+
Esta propriedade é somente para iOS.
Função que é chamada quando o cliente precisa baixar um arquivo.
@@ -1425,12 +1423,12 @@ Exemplo:
### `setSupportMultipleWindows`
-Define se a WebView oferece suporte a várias janelas. Consulte [documentação do Android]('https://developer.android.com/reference/android/webkit/WebSettings#setSupportMultipleWindows(boolean)') para obter mais informações.
+Define se a WebView oferece suporte a várias janelas. Consulte [documentação do Android](<'https://developer.android.com/reference/android/webkit/WebSettings#setSupportMultipleWindows(boolean)'>) para obter mais informações.
Definir isso como false pode expor o aplicativo a essa [vulnerabilidade](https://alesandroortiz.com/articles/uxss-android-webview-cve-2020-6506/), permitindo que um iframe malicioso escape para o DOM da camada superior.
-| Tipo | Requerido | Padrão | Plataforma |
-| ------- | --------- | ------- | ---------- |
-| boolean | Não | true | Android |
+| Tipo | Requerido | Padrão | Plataforma |
+| ------- | --------- | ------ | ---------- |
+| boolean | Não | true | Android |
Exemplo:
@@ -1446,12 +1444,12 @@ Isso vem com recursos como [`injectJavaScript`](Reference.portuguese.md#injectja
Se você for solicitado a enviar uma mensagem para App , a página da Web deve chamar explicitamente o manipulador de mensagens do webkit e recebê-lo no manipulador `onMessage` no lado nativo.
```javascript
-window.webkit.messageHandlers.ReactNativeWebView.postMessage("hello apple pay")
+window.webkit.messageHandlers.ReactNativeWebView.postMessage('hello apple pay');
```
-| Tipo | Requerido | Padrão | Plataforma |
-| ------- | --------- | ------- | --------- |
-| boolean | Não | false | iOS |
+| Tipo | Requerido | Padrão | Plataforma |
+| ------- | --------- | ------ | ---------- |
+| boolean | Não | false | iOS |
Exemplo:
@@ -1462,9 +1460,9 @@ Exemplo:
### `forceDarkOn`
Configurando o tema escuro
-*NOTA* : A configuração de forçar o tema escuro não é persistente. Você deve chamar o método estático sempre que o processo do aplicativo for iniciado.
+_NOTA_ : A configuração de forçar o tema escuro não é persistente. Você deve chamar o método estático sempre que o processo do aplicativo for iniciado.
-*NOTA* : A mudança do modo dia<->noite é uma alteração de configuração, portanto, por padrão, a atividade será reiniciada e serão coletados os novos valores para aplicar o tema. Tome cuidado ao substituir esse comportamento padrão para garantir que esse método ainda seja chamado quando as alterações forem feitas.
+_NOTA_ : A mudança do modo dia<->noite é uma alteração de configuração, portanto, por padrão, a atividade será reiniciada e serão coletados os novos valores para aplicar o tema. Tome cuidado ao substituir esse comportamento padrão para garantir que esse método ainda seja chamado quando as alterações forem feitas.
| Tipo | Requerido | Plataforma |
| ------- | --------- | ---------- |
@@ -1475,31 +1473,40 @@ Exemplo:
```javascript
```
+
### `menuItems`
Uma matriz de objetos de itens de menu personalizados que serão exibidos ao selecionar o texto. Uma matriz vazia suprimirá o menu. Usado em conjunto com `onCustomMenuSelection`
-| Tipo | Requerido | Plataforma |
-| ------------------------------------------------------------------ | -------- | -------- |
-| array of objects: {label: string, key: string} | Não | iOS, Android |
+| Tipo | Requerido | Plataforma |
+| ---------------------------------------------- | --------- | ------------ |
+| array of objects: {label: string, key: string} | Não | iOS, Android |
Exemplo:
```javascript
-
+
```
### `onCustomMenuSelection`
Função chamada quando um item de menu personalizado é selecionado. Ele recebe um evento Nativo, que inclui três chaves personalizadas: `label`, `key` e `selectedText`.
-| Tipo | Requerido | Plataforma |
-| ------------------------------------------------------------------ | -------- | -------- |
-| function | Não | iOS, Android |
+| Tipo | Requerido | Plataforma |
+| -------- | --------- | ------------ |
+| function | Não | iOS, Android |
```javascript
{
const { label } = webViewEvent.nativeEvent; // O nome do item de menu, ou seja, 'Tweet'
const { key } = webViewEvent.nativeEvent; // A chave do item de menu, ou seja, 'tweet'
@@ -1608,7 +1615,7 @@ Remove o pop-up de preenchimento automático do campo de formulário em foco no
(somente Android)
```javascript
-clearCache(true)
+clearCache(true);
```
Limpa o cache de recursos. Observe que o cache é por aplicativo, portanto, isso limpará o cache de todos os WebViews usados. [referência do desenvolvedor.android.com]()
@@ -1633,4 +1640,3 @@ Esse arquivo está disponível em:
- [Inglês](Reference.md)
- [Italiano](Reference.italian.md)
-
diff --git a/example/.watchmanconfig b/example/.watchmanconfig
index 9e26dfeeb6..0967ef424b 100644
--- a/example/.watchmanconfig
+++ b/example/.watchmanconfig
@@ -1 +1 @@
-{}
\ No newline at end of file
+{}
diff --git a/example/App.tsx b/example/App.tsx
index b2dd6fafcd..e3428a1390 100644
--- a/example/App.tsx
+++ b/example/App.tsx
@@ -21,10 +21,12 @@ import Messaging from './examples/Messaging';
import MultiMessaging from './examples/MultiMessaging';
import NativeWebpage from './examples/NativeWebpage';
import ApplePay from './examples/ApplePay';
+import GooglePay from './examples/GooglePay';
import CustomMenu from './examples/CustomMenu';
import OpenWindow from './examples/OpenWindow';
import SuppressMenuItems from './examples/Suppress';
import ClearData from './examples/ClearData';
+import SslError from './examples/SslError';
const TESTS = {
Messaging: {
@@ -123,6 +125,14 @@ const TESTS = {
return ;
},
},
+ GooglePay: {
+ title: 'Google Pay ',
+ testId: 'GooglePay',
+ description: 'Test to open a Google Pay supported page',
+ render() {
+ return ;
+ },
+ },
CustomMenu: {
title: 'Custom Menu',
testId: 'CustomMenu',
@@ -147,27 +157,32 @@ const TESTS = {
return ;
},
},
+ SslError: {
+ title: 'SslError',
+ testId: 'SslError',
+ description: 'SSL error test',
+ render() {
+ return ;
+ },
+ },
};
-interface Props {}
interface State {
restarting: boolean;
- currentTest: Object;
+ currentTest: (typeof TESTS)[keyof typeof TESTS];
}
-export default class App extends Component {
+export default class App extends Component {
state = {
restarting: false,
currentTest: TESTS.Alerts,
};
_simulateRestart = () => {
- this.setState({ restarting: true }, () =>
- this.setState({ restarting: false }),
- );
+ this.setState({ restarting: true }, () => this.setState({ restarting: false }));
};
- _changeTest = (testName) => {
+ _changeTest = (testName: keyof typeof TESTS) => {
this.setState({ currentTest: TESTS[testName] });
};
@@ -250,6 +265,13 @@ export default class App extends Component {
onPress={() => this._changeTest('ApplePay')}
/>
)}
+ {Platform.OS === 'android' && (
+
{restarting ? null : (
@@ -279,12 +306,8 @@ export default class App extends Component {
style={styles.exampleContainer}
>
{currentTest.title}
-
- {currentTest.description}
-
-
- {currentTest.render()}
-
+ {currentTest.description}
+ {currentTest.render()}
)}
diff --git a/example/app.json b/example/app.json
index e9f9c44346..70a2835452 100644
--- a/example/app.json
+++ b/example/app.json
@@ -8,22 +8,10 @@
}
],
"resources": {
- "android": [
- "dist/res",
- "dist/main.android.jsbundle"
- ],
- "ios": [
- "dist/assets",
- "dist/main.ios.jsbundle"
- ],
- "macos": [
- "dist/assets",
- "dist/main.macos.jsbundle"
- ],
- "windows": [
- "dist/assets",
- "dist/main.windows.bundle"
- ]
+ "android": ["dist/res", "dist/main.android.jsbundle"],
+ "ios": ["dist/assets", "dist/main.ios.jsbundle"],
+ "macos": ["dist/assets", "dist/main.macos.jsbundle"],
+ "windows": ["dist/assets", "dist/main.windows.bundle"]
},
"windows": {
"appxManifest": "windows/Package.appxmanifest"
diff --git a/example/assets/test.html b/example/assets/test.html
index 62d8620c01..64df803ae3 100644
--- a/example/assets/test.html
+++ b/example/assets/test.html
@@ -1,9 +1,9 @@
-
- Test
-
-
-
Local page test
-
-
\ No newline at end of file
+
+ Test
+
+
+
Local page test
+
+
diff --git a/example/examples/Alerts.tsx b/example/examples/Alerts.tsx
index e6ed30c567..3bb8efd229 100644
--- a/example/examples/Alerts.tsx
+++ b/example/examples/Alerts.tsx
@@ -1,5 +1,5 @@
-import React, {Component} from 'react';
-import {Text, View} from 'react-native';
+import React, { Component } from 'react';
+import { Text, View } from 'react-native';
import WebView from 'react-native-webview';
@@ -63,7 +63,7 @@ export default class Alerts extends Component {
return (
diff --git a/example/examples/Alerts.windows.tsx b/example/examples/Alerts.windows.tsx
index 60cb696cd7..6a8bdd9e70 100644
--- a/example/examples/Alerts.windows.tsx
+++ b/example/examples/Alerts.windows.tsx
@@ -1,5 +1,5 @@
-import React, {Component} from 'react';
-import {Text, View} from 'react-native';
+import React, { Component } from 'react';
+import { Text, View } from 'react-native';
import WebView from 'react-native-webview';
@@ -63,7 +63,7 @@ export default class Alerts extends Component {
return (
diff --git a/example/examples/ApplePay.tsx b/example/examples/ApplePay.tsx
index 6bd67a425c..8e6b4e2858 100644
--- a/example/examples/ApplePay.tsx
+++ b/example/examples/ApplePay.tsx
@@ -1,5 +1,5 @@
-import React, {Component} from 'react';
-import {View} from 'react-native';
+import React, { Component } from 'react';
+import { View } from 'react-native';
import WebView from 'react-native-webview';
@@ -7,17 +7,17 @@ type Props = {};
type State = {};
export default class Alerts extends Component {
- state = {};
+ state = {};
- render() {
- return (
-
-
-
- );
- }
+ render() {
+ return (
+
+
+
+ );
+ }
}
diff --git a/example/examples/Background.tsx b/example/examples/Background.tsx
index 79a360eb3b..f899c04467 100644
--- a/example/examples/Background.tsx
+++ b/example/examples/Background.tsx
@@ -1,5 +1,5 @@
-import React, {Component} from 'react';
-import {Text, View} from 'react-native';
+import React, { Component } from 'react';
+import { Text, View } from 'react-native';
import WebView from 'react-native-webview';
@@ -27,23 +27,23 @@ const HTML = `
type Props = {};
type State = {
- backgroundColor: string,
+ backgroundColor: string;
};
export default class Background extends Component {
state = {
- backgroundColor: '#FF00FF00'
+ backgroundColor: '#FF00FF00',
};
render() {
return (
-
+
diff --git a/example/examples/ClearData.tsx b/example/examples/ClearData.tsx
index 0ed4c2f030..18a5cac900 100644
--- a/example/examples/ClearData.tsx
+++ b/example/examples/ClearData.tsx
@@ -34,7 +34,10 @@ export default class ClearData extends Component {
title="Clear cache (no diskFiles)"
onPress={() => this.clearCacheAndReload(false)}
/>
-
+ {
-export default CustomMenu = () => {
- const [selectionInfo, setSelectionInfo] = React.useState(null)
- const webviewRef = React.useRef()
+export default (CustomMenu = () => {
+ const [selectionInfo, setSelectionInfo] = React.useState(null);
+ const webviewRef = React.useRef();
- return (
-
-
- {
- const { label, key, selectedText } = webViewEvent.nativeEvent;
- setSelectionInfo(webViewEvent.nativeEvent)
- // clearing the selection by sending a message. This would need a script on the source page to listen to the message.
- webviewRef.current?.postMessage(JSON.stringify({what: 'clearSelection'}))
- }}
- />
-
- {selectionInfo
- &&
- onCustomMenuSelection called: {"\n"}
- - label: {selectionInfo?.label}{"\n"}
- - key: {selectionInfo?.key}{"\n"}
- - selectedText: {selectionInfo?.selectedText}
-
- }
+ return (
+
+
+ {
+ const { label, key, selectedText } = webViewEvent.nativeEvent;
+ setSelectionInfo(webViewEvent.nativeEvent);
+ // clearing the selection by sending a message. This would need a script on the source page to listen to the message.
+ webviewRef.current?.postMessage(JSON.stringify({ what: 'clearSelection' }));
+ }}
+ />
- );
-}
\ No newline at end of file
+ {selectionInfo && (
+
+ onCustomMenuSelection called: {'\n'}- label: {selectionInfo?.label}
+ {'\n'}- key: {selectionInfo?.key}
+ {'\n'}- selectedText: {selectionInfo?.selectedText}
+
+ )}
+
+ );
+});
diff --git a/example/examples/Downloads.tsx b/example/examples/Downloads.tsx
index 13c1d5f2bd..9f4fa34e00 100644
--- a/example/examples/Downloads.tsx
+++ b/example/examples/Downloads.tsx
@@ -1,7 +1,7 @@
-import React, {Component} from 'react';
-import {Alert, Platform, View} from 'react-native';
+import React, { Component } from 'react';
+import { Alert, Platform, View } from 'react-native';
-import WebView, {FileDownload} from 'react-native-webview';
+import WebView, { FileDownload } from 'react-native-webview';
const HTML = `
\n
@@ -33,8 +33,8 @@ interface State {}
export default class Downloads extends Component {
state = {};
- onFileDownload = ({ nativeEvent }: { nativeEvent: FileDownload } ) => {
- Alert.alert("File download detected", nativeEvent.downloadUrl);
+ onFileDownload = ({ nativeEvent }: { nativeEvent: FileDownload }) => {
+ Alert.alert('File download detected', nativeEvent.downloadUrl);
};
render() {
@@ -47,7 +47,7 @@ export default class Downloads extends Component {
return (
diff --git a/example/examples/GooglePay.tsx b/example/examples/GooglePay.tsx
new file mode 100644
index 0000000000..ec0dbf0fa5
--- /dev/null
+++ b/example/examples/GooglePay.tsx
@@ -0,0 +1,22 @@
+import React, { Component } from 'react';
+import { View } from 'react-native';
+
+import WebView from 'react-native-webview';
+
+type Props = {};
+type State = {};
+
+export default class Alerts extends Component {
+ state = {};
+
+ render() {
+ return (
+
+
+
+ );
+ }
+}
diff --git a/example/examples/Injection.tsx b/example/examples/Injection.tsx
index aa2ea16054..d5e172760c 100644
--- a/example/examples/Injection.tsx
+++ b/example/examples/Injection.tsx
@@ -1,5 +1,5 @@
-import React, {Component} from 'react';
-import {Text, View, ScrollView} from 'react-native';
+import React, { Component } from 'react';
+import { Text, View, ScrollView } from 'react-native';
import WebView from 'react-native-webview';
@@ -23,18 +23,18 @@ const HTML = `
type Props = {};
type State = {
- backgroundColor: string,
+ backgroundColor: string;
};
export default class Injection extends Component {
state = {
- backgroundColor: '#FF00FF00'
+ backgroundColor: '#FF00FF00',
};
render() {
return (
-
+ {
* The cause of this is unresolved.
*/
// source={{ html: HTML }}
- source={{ uri: "https://birchlabs.co.uk/linguabrowse/infopages/obsol/rnw_iframe_test.html" }}
+ source={{
+ uri: 'https://birchlabs.co.uk/linguabrowse/infopages/obsol/rnw_iframe_test.html',
+ }}
automaticallyAdjustContentInsets={false}
- style={{backgroundColor:'#00000000'}}
-
+ style={{ backgroundColor: '#00000000' }}
/* Must be populated in order for `messagingEnabled` to be `true` to activate the
* JS injection user scripts, consistent with current behaviour. This is undesirable,
* so needs addressing in a follow-up PR. */
onMessage={() => {}}
injectedJavaScriptBeforeContentLoadedForMainFrameOnly={false}
injectedJavaScriptForMainFrameOnly={false}
- injectedJavaScriptObject={{ hello: "world" }}
-
+ injectedJavaScriptObject={{ hello: 'world' }}
/* We set this property in each frame */
injectedJavaScriptBeforeContentLoaded={`
console.log("executing injectedJavaScriptBeforeContentLoaded... " + (new Date()).toString());
@@ -88,7 +88,6 @@ export default class Injection extends Component {
console.log("wasn't window.top. Still going...");
}
`}
-
/* We read the colourToUse property in each frame to recolour each frame */
injectedJavaScript={`
console.log("executing injectedJavaScript... " + (new Date()).toString());
@@ -153,22 +152,58 @@ export default class Injection extends Component {
/>
- This test presents three iframes: iframe_0 (yellow); iframe_1 (pink); and iframe_2 (transparent, because its 'X-Frame-Options' is set to 'SAMEORIGIN').
- Before injection, the main frame's background is the browser's default value (transparent or white) and each frame has its natural colour.
+
+ This test presents three iframes: iframe_0 (yellow); iframe_1 (pink); and iframe_2
+ (transparent, because its 'X-Frame-Options' is set to 'SAMEORIGIN').
+
+
+ Before injection, the main frame's background is the browser's default value (transparent
+ or white) and each frame has its natural colour.
+
{/*1a) At injection time "beforeContentLoaded", a variable will be set in each frame to set 'orange' as the "colour to be used".*/}
{/*1b) Also upon "beforeContentLoaded", a style element to change the text "beforeContentLoaded failed" -> "beforeContentLoaded succeeded" will be applied as soon as the head has loaded.*/}
{/*2a) At injection time "afterContentLoaded", that variable will be read – if present, the colour orange will be injected into all frames. Otherwise, cyan.*/}
{/*2b) Also upon "afterContentLoaded", a style element to change the text "afterContentLoaded failed" -> "afterContentLoaded succeeded" will be applied as soon as the head has loaded.*/}
- ✅ If the main frame becomes orange, then top-frame injection both beforeContentLoaded and afterContentLoaded is supported.
- ✅ If iframe_0, and iframe_1 become orange, then multi-frame injection beforeContentLoaded and afterContentLoaded is supported.
- ✅ If the two texts say "beforeContentLoaded on the top frame succeeded!" and "afterContentLoaded on the top frame succeeded!", then both injection times are supported at least on the main frame.
- ❌ If either of the two iframes become coloured cyan, then for that given frame, JS injection succeeded after the content loaded, but didn't occur before the content loaded.
- ❌ If "Names of iframes that called beforeContentLoaded: " is [], then see above.
- ❌ If "Names of iframes that called afterContentLoaded: " is [], then afterContentLoaded is not supported in iframes.
- ❌ If the main frame becomes coloured cyan, then JS injection succeeded after the content loaded, but didn't occur before the content loaded.
- ❌ If the text "beforeContentLoaded on the top frame failed" remains unchanged, then JS injection has failed on the main frame before the content loaded.
- ❌ If the text "afterContentLoaded on the top frame failed" remains unchanged, then JS injection has failed on the main frame after the content loaded.
- ❌ If the iframes remain their original colours (yellow and pink), then multi-frame injection is not supported at all.
+
+ ✅ If the main frame becomes orange, then top-frame injection both beforeContentLoaded and
+ afterContentLoaded is supported.
+
+
+ ✅ If iframe_0, and iframe_1 become orange, then multi-frame injection beforeContentLoaded
+ and afterContentLoaded is supported.
+
+
+ ✅ If the two texts say "beforeContentLoaded on the top frame succeeded!" and
+ "afterContentLoaded on the top frame succeeded!", then both injection times are supported
+ at least on the main frame.
+
+
+ ❌ If either of the two iframes become coloured cyan, then for that given frame, JS
+ injection succeeded after the content loaded, but didn't occur before the content loaded.
+
+
+ ❌ If "Names of iframes that called beforeContentLoaded: " is [], then see above.
+
+
+ ❌ If "Names of iframes that called afterContentLoaded: " is [], then afterContentLoaded
+ is not supported in iframes.
+
+
+ ❌ If the main frame becomes coloured cyan, then JS injection succeeded after the content
+ loaded, but didn't occur before the content loaded.
+
+
+ ❌ If the text "beforeContentLoaded on the top frame failed" remains unchanged, then JS
+ injection has failed on the main frame before the content loaded.
+
+
+ ❌ If the text "afterContentLoaded on the top frame failed" remains unchanged, then JS
+ injection has failed on the main frame after the content loaded.
+
+
+ ❌ If the iframes remain their original colours (yellow and pink), then multi-frame
+ injection is not supported at all.
+
);
}
diff --git a/example/examples/LocalPageLoad.tsx b/example/examples/LocalPageLoad.tsx
index 780e6e6972..2c3266d94c 100644
--- a/example/examples/LocalPageLoad.tsx
+++ b/example/examples/LocalPageLoad.tsx
@@ -1,16 +1,16 @@
-import React, {Component} from 'react';
-import {View, Text, Alert, TextInput, Button} from 'react-native';
+import React, { Component } from 'react';
+import { View, Text, Alert, TextInput, Button } from 'react-native';
import WebView from 'react-native-webview';
const localHtmlFile = require('../assets/test.html');
export default class LocalPageLoad extends Component {
- render() {
- return (
-
-
-
-
+ render() {
+ return (
+
+
+
- );
- }
- }
\ No newline at end of file
+
+ );
+ }
+}
diff --git a/example/examples/Messaging.tsx b/example/examples/Messaging.tsx
index 46680d7d26..7d8704202c 100644
--- a/example/examples/Messaging.tsx
+++ b/example/examples/Messaging.tsx
@@ -1,5 +1,5 @@
-import React, {Component} from 'react';
-import {View, Alert, TextInput} from 'react-native';
+import React, { Component } from 'react';
+import { View, Alert, TextInput } from 'react-native';
import WebView from 'react-native-webview';
@@ -54,16 +54,20 @@ export default class Messaging extends Component {
render() {
return (
-
- {
- this.webView.current.postMessage(e.nativeEvent.text);
- }}/>
+
+ {
+ this.webView.current.postMessage(e.nativeEvent.text);
+ }}
+ />
{this.webView.current.postMessage('Hello from RN');}}
+ source={{ html: HTML }}
+ onLoadEnd={() => {
+ this.webView.current.postMessage('Hello from RN');
+ }}
automaticallyAdjustContentInsets={false}
- onMessage={(e: {nativeEvent: {data?: string}}) => {
+ onMessage={(e: { nativeEvent: { data?: string } }) => {
Alert.alert('Message received from JS: ', e.nativeEvent.data);
}}
/>
diff --git a/example/examples/Messaging.windows.tsx b/example/examples/Messaging.windows.tsx
index 0ddc1ff88a..bc2e7f8a07 100644
--- a/example/examples/Messaging.windows.tsx
+++ b/example/examples/Messaging.windows.tsx
@@ -1,5 +1,5 @@
-import React, {Component} from 'react';
-import {View, Alert, TextInput} from 'react-native';
+import React, { Component } from 'react';
+import { View, Alert, TextInput } from 'react-native';
import WebView from 'react-native-webview';
@@ -54,16 +54,20 @@ export default class Messaging extends Component {
render() {
return (
-
- {
- this.webView.current.postMessage(e.nativeEvent.text);
- }}/>
+
+ {
+ this.webView.current.postMessage(e.nativeEvent.text);
+ }}
+ />
{this.webView.current.postMessage('Hello from RN');}}
+ source={{ html: HTML }}
+ onLoadEnd={() => {
+ this.webView.current.postMessage('Hello from RN');
+ }}
automaticallyAdjustContentInsets={false}
- onMessage={(e: {nativeEvent: {data?: string}}) => {
+ onMessage={(e: { nativeEvent: { data?: string } }) => {
Alert.alert('Message received from JS: ', e.nativeEvent.data);
}}
useWebView2
diff --git a/example/examples/NativeWebpage.tsx b/example/examples/NativeWebpage.tsx
index 39c7502203..d01a7bac0f 100644
--- a/example/examples/NativeWebpage.tsx
+++ b/example/examples/NativeWebpage.tsx
@@ -16,11 +16,11 @@ export default class NativeWebpage extends Component {
source={{ uri: 'https://infinite.red' }}
style={{ width: '100%', height: '100%' }}
onShouldStartLoadWithRequest={(event) => {
- console.log("onShouldStartLoadWithRequest", event);
+ console.log('onShouldStartLoadWithRequest', event);
return true;
}}
onLoadStart={(event) => {
- console.log("onLoadStart", event.nativeEvent);
+ console.log('onLoadStart', event.nativeEvent);
}}
/>
diff --git a/example/examples/OpenWindow.tsx b/example/examples/OpenWindow.tsx
index c927f8bad1..94613e03ac 100644
--- a/example/examples/OpenWindow.tsx
+++ b/example/examples/OpenWindow.tsx
@@ -1,5 +1,5 @@
-import React, {Component} from 'react';
-import {Button, Switch, StyleSheet, Text, View} from 'react-native';
+import React, { Component } from 'react';
+import { Button, Switch, StyleSheet, Text, View } from 'react-native';
import WebView from 'react-native-webview';
@@ -53,49 +53,47 @@ const HTML = `
type Props = {};
type State = {
- shouldInterceptOpenWindow: boolean,
- text: string,
- webViewKey: number
+ shouldInterceptOpenWindow: boolean;
+ text: string;
+ webViewKey: number;
};
export default class OpenWindow extends Component {
state = {
shouldInterceptOpenWindow: true,
text: 'No OpenWindow event intercepted yet',
- webViewKey: 1
+ webViewKey: 1,
};
interceptOpenWindow = (syntheticEvent) => {
- const { nativeEvent } = syntheticEvent
- const { targetUrl } = nativeEvent
+ const { nativeEvent } = syntheticEvent;
+ const { targetUrl } = nativeEvent;
this.setState({
- text: `Intercepted OpenWindow event for ${targetUrl} at ${Date.now()}`
- })
+ text: `Intercepted OpenWindow event for ${targetUrl} at ${Date.now()}`,
+ });
};
toggleShouldInterceptOpenWindow = () => {
- this.setState(prevState => ({
- shouldInterceptOpenWindow: !prevState.shouldInterceptOpenWindow
- }))
+ this.setState((prevState) => ({
+ shouldInterceptOpenWindow: !prevState.shouldInterceptOpenWindow,
+ }));
};
resetWebView = () => {
- this.setState(prevState => ({
- webViewKey: prevState.webViewKey + 1
- }))
+ this.setState((prevState) => ({
+ webViewKey: prevState.webViewKey + 1,
+ }));
};
render() {
const onOpenWindow = this.state.shouldInterceptOpenWindow
? this.interceptOpenWindow
- : undefined
+ : undefined;
return (
-
- Intercept OpenWindow event
-
+ Intercept OpenWindow event {
-
- {this.state.text}
-
-
+ {this.state.text}
+
);
}
@@ -118,15 +117,15 @@ export default class OpenWindow extends Component {
const styles = StyleSheet.create({
container: {
- height: 300
+ height: 300,
},
interceptSection: {
alignItems: 'center',
- flexDirection: "row",
+ flexDirection: 'row',
justifyContent: 'space-between',
- marginBottom: 20
+ marginBottom: 20,
},
text: {
- color: 'black'
- }
-})
+ color: 'black',
+ },
+});
diff --git a/example/examples/OpenWindow.windows.tsx b/example/examples/OpenWindow.windows.tsx
index eeeabb88f6..1a2d381135 100644
--- a/example/examples/OpenWindow.windows.tsx
+++ b/example/examples/OpenWindow.windows.tsx
@@ -1,5 +1,5 @@
-import React, {Component} from 'react';
-import {Button, Switch, StyleSheet, Text, View} from 'react-native';
+import React, { Component } from 'react';
+import { Button, Switch, StyleSheet, Text, View } from 'react-native';
import WebView from 'react-native-webview';
@@ -53,49 +53,47 @@ const HTML = `
type Props = {};
type State = {
- shouldInterceptOpenWindow: boolean,
- text: string,
- webViewKey: number
+ shouldInterceptOpenWindow: boolean;
+ text: string;
+ webViewKey: number;
};
export default class OpenWindow extends Component {
state = {
shouldInterceptOpenWindow: true,
text: 'No OpenWindow event intercepted yet',
- webViewKey: 1
+ webViewKey: 1,
};
interceptOpenWindow = (syntheticEvent) => {
- const { nativeEvent } = syntheticEvent
- const { targetUrl } = nativeEvent
+ const { nativeEvent } = syntheticEvent;
+ const { targetUrl } = nativeEvent;
this.setState({
- text: `Intercepted OpenWindow event for ${targetUrl} at ${Date.now()}`
- })
+ text: `Intercepted OpenWindow event for ${targetUrl} at ${Date.now()}`,
+ });
};
toggleShouldInterceptOpenWindow = () => {
- this.setState(prevState => ({
- shouldInterceptOpenWindow: !prevState.shouldInterceptOpenWindow
- }))
+ this.setState((prevState) => ({
+ shouldInterceptOpenWindow: !prevState.shouldInterceptOpenWindow,
+ }));
};
resetWebView = () => {
- this.setState(prevState => ({
- webViewKey: prevState.webViewKey + 1
- }))
+ this.setState((prevState) => ({
+ webViewKey: prevState.webViewKey + 1,
+ }));
};
render() {
const onOpenWindow = this.state.shouldInterceptOpenWindow
? this.interceptOpenWindow
- : undefined
+ : undefined;
return (
-
- Intercept OpenWindow event
-
+ Intercept OpenWindow event {
-
- {this.state.text}
-
-
+ {this.state.text}
+
);
}
@@ -119,15 +118,15 @@ export default class OpenWindow extends Component {
const styles = StyleSheet.create({
container: {
- height: 300
+ height: 300,
},
interceptSection: {
alignItems: 'center',
- flexDirection: "row",
+ flexDirection: 'row',
justifyContent: 'space-between',
- marginBottom: 20
+ marginBottom: 20,
},
text: {
- color: 'black'
- }
-})
+ color: 'black',
+ },
+});
diff --git a/example/examples/Scrolling.tsx b/example/examples/Scrolling.tsx
index 7f35645229..f933214cd5 100644
--- a/example/examples/Scrolling.tsx
+++ b/example/examples/Scrolling.tsx
@@ -1,5 +1,5 @@
-import React, {Component} from 'react';
-import {Button, Text, View} from 'react-native';
+import React, { Component } from 'react';
+import { Button, Text, View } from 'react-native';
import WebView from 'react-native-webview';
@@ -31,14 +31,14 @@ const HTML = `
type Props = {};
type State = {
- scrollEnabled: boolean,
- lastScrollEvent: string
+ scrollEnabled: boolean;
+ lastScrollEvent: string;
};
export default class Scrolling extends Component {
state = {
scrollEnabled: true,
- lastScrollEvent: ''
+ lastScrollEvent: '',
};
render() {
@@ -46,7 +46,7 @@ export default class Scrolling extends Component {
{
this.setState({scrollEnabled: !this.state.scrollEnabled})}
+ onPress={() => this.setState({ scrollEnabled: !this.state.scrollEnabled })}
/>
Last scroll event:{this.state.lastScrollEvent}
@@ -62,7 +62,7 @@ export default class Scrolling extends Component {
);
}
- _onScroll = event => {
- this.setState({lastScrollEvent: JSON.stringify(event.nativeEvent)});
- }
+ _onScroll = (event) => {
+ this.setState({ lastScrollEvent: JSON.stringify(event.nativeEvent) });
+ };
}
diff --git a/example/examples/SslError.tsx b/example/examples/SslError.tsx
new file mode 100644
index 0000000000..82f4e47ea6
--- /dev/null
+++ b/example/examples/SslError.tsx
@@ -0,0 +1,24 @@
+import React, { Component } from 'react';
+import { View } from 'react-native';
+
+import WebView from 'react-native-webview';
+
+type Props = {};
+type State = {};
+
+export default class SslError extends Component {
+ state = {};
+
+ render() {
+ return (
+
+ {
+ console.log('onLoadSubResourceError', event.nativeEvent.description);
+ }}
+ />
+
+ );
+ }
+}
diff --git a/example/examples/Suppress.tsx b/example/examples/Suppress.tsx
index f6c4b2cdc1..5a05f416de 100644
--- a/example/examples/Suppress.tsx
+++ b/example/examples/Suppress.tsx
@@ -20,7 +20,7 @@ const HTML = `