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

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

我有最新的 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 作为最后一个命令解决了这个问题。但为什么?似乎只有小书签才会这样。

这是预期的行为

如果小书签是 运行 并且其 returned 值是 not undefined 这是浏览器替换具有 returned 值的页面内容。在您的示例中,这是 "test".

When a browser follows a javascript: URI, it evaluates the code in the URI and then replaces the contents of the page with the returned value, unless the returned value is undefined.

JavaScript URI (Mozilla Developer Network - void operator)

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

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

你能做什么?

  • 使用 void 运算符。这将确保 undefined 是 returned 而不是

  • 将第二种方法改为 return 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>