- 1 devtool提供了debug时机
- 2 借助油猴插件
- 2.1 找到alert调用
- 2.2 找到更改cookie
- 监听url变化(pushstate or replacestate)">2.3 监听url变化(pushstate or replacestate)
经常需要在不清楚代码具体情况下,需要在某个时间节点debug住,查找调用栈,查找响应函数调用关系,比如DOM某个属性的更改,alert弹窗的调用,某个cookie字段的写入。
1 devtool提供了debug时机

2 借助油猴插件
2.1 找到alert调用
重写alert方法,并插入debug
// ==UserScript==// @name debugger-alert// @namespace http://tampermonkey.net/// @version 0.1// @description try to take over the world!// @author You// @match https://www.baidu.com/home-header2.html// @grant none// ==/UserScript==(function() {'use strict';// Your code here...var originAlert = window.alert; // 首先记录原生的alertwindow.alert = function (text) { // 用我们带断点的alert覆盖window.alertdebugger;return originAlert.call(window, text);};})();
跳过alert
window.alert=function(){}
2.2 找到更改cookie
参考:怎么找出js里面改变cookies的代码?
同样是重写document.cookie来截获
var _cookie = document.__lookupSetter__('cookie');document.__defineSetter__("cookie", function(c) {debugger; //console.log(c); //或dispatch事件_cookie=c;} );document.__defineGetter__("cookie", function() {return _cookie;} );
2.3 监听url变化(pushstate or replacestate)
// Add this:var _wr = function(type) {var orig = history[type];return function() {var rv = orig.apply(this, arguments);var e = new Event(type);e.arguments = arguments;window.dispatchEvent(e);return rv;};};history.pushState = _wr('pushState'), history.replaceState = _wr('replaceState');// Use it like this:window.addEventListener('replaceState', function(e) {console.warn('THEY DID IT AGAIN!');});

