仅当页面有密码字段时运行用户脚本

问题描述 投票:0回答:2

我有一小段 JavaScript 代码用作用户脚本。该操作运行良好,但我想向其中添加 if 语句,但不知道如何构建它。

用简单的语言,我希望它这样做:

  • 如果页面上有密码输入框,请不要运行我的操作。

或者交替

  • 如果此页面上没有密码输入字段,则运行我的操作。

这是如何实现的?我在摆弄

document.querySelectorAll
但到目前为止没有运气。

javascript if-statement userscripts
2个回答
0
投票

您可以使用

document.querySelector
来检查是否存在。

if (!document.querySelector('input[type=password]')) {
    // your code here
}

0
投票

尝试将此查询与

document.querySelector()
一起使用:
input[type="password"]
。如果你没有得到结果,它会返回
null
,你知道它不存在于页面上。

然后您可以使用它通过返回来结束用户脚本。

这里有两个例子(相同的 JS,第一个有密码,第二个没有):

(function(){
  if (document.querySelector('input[type="password"]') !== null) {
    return;
  }
  console.log('userscript');
})();
<input type="text">
<input type="password">

(function(){
  if (document.querySelector('input[type="password"]') !== null) {
    return;
  }
  console.log('userscript');
})();
<input type="text">

© www.soinside.com 2019 - 2024. All rights reserved.