有的网页为了防止 tampermonkey 这类插件读取页面中的 js 变量,把变量写到了匿名自调用函数 self-invocation 中,例如 <script type="text/javascript"> (function() { var a = 1; console.log(a); })(); </script> 而我为了某些不可告人的目的必须读取到变量 a 的值。 一种有效的方式是,使用 ajax 获取当前页面的源代码,然后正则匹配中某个指定变量的值。 正则匹配 var s = ‘var name = "hahahaha"‘; var s = ‘var name = "hahahaha";‘; s.match(/var \w+ = (.+);/); 0: "var name = "hahahaha";" 1: ""hahahaha"" var s = ‘var name = "hahahaha"; var age = 10;‘; s.match(/var \w+ = (.+);/); 0: "var name = "hahahaha"; var age = 10;" 1: ""hahahaha"; var age = 10" // 避免贪婪匹配 s.match(/var \w+ = (.+?);/); 0: "var name = "hahahaha";" 1: ""hahahaha"" s.match(/var age = (.+?);/); 0: "var age = 10;" 1: "10" 避免贪婪匹配 * - zero or more *? - zero or more (non-greedy) + - one or more +? - one or more (non-greedy) ? - zero or one ?? - zero or one (non-greedy)
原文链接:https://www.sunzhongwei.com/javascript-regular-extract-variable-values-in-a-web-page