为什么 Chrome 在使用书签时更新正文而不是文本区域值

Why is Chrome updating the body instead of the textarea value when using a bookmarklet?

本文关键字:文本 区域 正文 更新 Chrome 书签 为什么      更新时间:2023-09-26

我有最新的Chrome,我想用书签更新textarea字段,如下所示:

javascript:document.getElementById("<here comes the ID>").value="test";

Chrome 始终使用值"test"(来自上面的示例)更新元素body,而不是textarea

您可以通过转到 http://reference.sitepoint.com/html/textarea/demoframe 并使用所述页面的textarea ID 或通过下面的堆栈代码段执行书签来测试这一点:

ul, li{
  margin: 0;
  padding: 0;
}
textarea {
  margin-top: 10px;
  width: 100%;
}
<ul>
  <li><strong>Without the void operator:</strong> <a href="javascript:document.getElementById('testTextarea').value='test 1';">This link will replace the contents of the page with "test 1"</a></li>
</ul>
<textarea id="testTextarea">Content to be replaced</textarea>

所以我的问题是:为什么 Chrome 会更新 HTML 元素body

编辑 3 月 1 日 凌晨 2:11 UCT:
以下代码在 Chrome 中运行良好:

javascript:document.getElementById("<here comes the ID>").value="test"; true;

因此,添加true作为最后一个命令可以解决问题。但是为什么?似乎只有书签才会有这种行为。

这是

预期行为

如果运行书签并且其返回值不是undefined则浏览器将页面内容替换为返回值是标准行为。在您的示例中,这是"测试"。

当浏览器遵循javascript:URI时,它会计算URI中的代码,然后用返回的值替换页面的内容,除非返回的值未定义。

JavaScript URIs (Mozilla Developer Network - void operator)

为什么您的第二个版本有效?

这似乎是Chrome中的一个错误(问题407505),IE和Firefox中的相同代码会导致预期的行为(即与第一个版本相同的结果)。

你能做什么?

  • 使用 void 运算符。这将确保undefined而是返回

  • 将第二种方法更改为返回undefined而不是true

ul, li{
  margin: 0;
  padding: 0;
}
textarea {
  margin-top: 10px;
  width: 100%;
}
<ul>
  <li><strong>With the void operator:</strong> <a href="javascript:void(document.getElementById('testTextarea').value='test 1');">This link will replace the contents of the textarea with "test 1"</a></li>
  <li><strong>Returning undefined:</strong> <a href="javascript:document.getElementById('testTextarea').value='test 2';undefined;">This link will replace the contents of the textarea with "test 2"</a></li>
</ul>
<textarea id="testTextarea">Content to be replaced</textarea>