getScriptVariables method

Map<String, dynamic> getScriptVariables(
  1. List<String> variableNames
)

Returns Map between given variable names and list of their occurence in the script tags

Implementation

// ex. if document contains
// <script> var a = 15; var b = 10; </script>
// <script> var a = 9; </script>
// method will return {a: ['var a = 15;', 'var a = 9;'], b: ['var b = 10;'] }.
Map<String, dynamic> getScriptVariables(List<String> variableNames) {
  // The _document should not be null (loadWebPage must be called before getScriptVariables).
  assert(_document != null);

  // Quering the list of elements by tag names.
  var scripts = _document!.getElementsByTagName('script');

  var result = <String, List<String>?>{};

  // Looping in all the script tags of the document.
  for (var script in scripts) {
    // Looping in all the variable names that are required to extract.
    for (var variableName in variableNames) {
      // Regular expression to get the variable names.
      var re = RegExp(
          '$variableName *=.*?;(?=([^\"\']*\"[^\"\']*\")*[^\"\']*\$)',
          multiLine: true);
      //  Iterate all matches
      Iterable matches = re.allMatches(script.text);
      matches.forEach((match) {
        if (match != null) {
          // List for all the occurence of the variable name.
          var temp = result[variableName];
          if (result[variableName] == null) {
            temp = [];
          }
          temp!.add(script.text.substring(match.start, match.end));
          result[variableName] = temp;
        }
      });
    }
  }

  // Returning final result i.e. Map of variable names with the list of their occurences.
  return result;
}