我有这样的情况:错误S经常是从第三方JS发出的,比如Chartbeat等等。我想捕捉并丢弃这些错误和相关的噪音。
所有这样的第三方脚本都有以下几个变体:
<script> DOM标记windowwindow.onload以调用初始化程序例如:
function loadChartbeat() {
window._sf_endpt=(new Date()).getTime();
var e = document.createElement('script');
e.setAttribute('language', 'javascript');
e.setAttribute('type', 'text/javascript');
e.setAttribute('src', '//static.chartbeat.com/js/chartbeat.js');
document.body.appendChild(e);
}如何在此上下文中try/catch错误?
在处理此模式的<script>标记/加载时,是否有另一种方法可以避免错误的冒泡?
我尝试添加一个静音函数,像这样
function stoperror() {
return true;
}
function loadChartbeat() {
window._sf_endpt=(new Date()).getTime();
var e = document.createElement('script');
e.setAttribute('language', 'javascript');
e.setAttribute('type', 'text/javascript');
e.setAttribute('src', '//static.chartbeat.com/js/chartbeat.js');
e.onerror = stoperror;
document.body.appendChild(e);
}但这些错误仍在继续冒泡。
发布于 2017-02-17 15:15:26
最简单的方法是将它添加到服务器端。就像这样:
//loadscript.php
<?php
echo "try{";
readfile($_GET["url"]);//bad style, may improve it
echo "}catch(e){}";
?>在用户端,它将陷入混乱,涉及安全性+可用性。可以做这样的事情:
[...document.getElementsByTagName("script")].forEach(function(el){
var url=el.src;
el.parentNode.removeChild(el);
ajax(url,function(code){ // needs to be implemented
try{
eval(code);
}catch(e){}
});
});https://stackoverflow.com/questions/42301074
复制相似问题