18910140161

JavaScript-无法捕获SVG元素上的setAttribute后出现JS错误-堆栈溢出

顺晟科技

2022-10-18 13:27:07

189

我正在开发一个Web工具,它可以让您更改SVG元素的属性。目前,我正在尝试向用户反馈任何无效的属性或值。

对具有意外值的SVG元素调用setAttribute(或setAttributeNS)

时,会发生JavaScript错误。我试图通过使用try/catch或window.onerror来捕获它,但找不到这样做的方法。

示例代码:

    <svg id="svg" width="300" height="100">
      <linearGradient id="gradient" x1="10" y1="10" x2="100" y2="100">
        <stop offset="0" stop-color="#000000"></stop>
        <stop offset="1" stop-color="#969695"></stop>
      </linearGradient>
    </svg>
    try {
       document.querySelector('#gradient').setAttribute('x1', 'This error is not catchable');
    } catch (error) {
       console.log('never triggered');
    }
https://jsfiddle.net/wr3tne2y/.

在Chromium V91和Firefox中

测试:

js error slipping through try/catch


顺晟科技:

在设置之前,

您需要检查该值。

let val = 'This error is not catchable';
if (!isNaN(parseInt(val, 10)))
{
  document.querySelector('#gradient').setAttribute('x1', val);
}
else
{
  console.log('ERROR!');
}
  • TAG:
相关文章
我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航