javascript - 无法更改 body 元素的 html

标签 javascript bookmarklet

我想创建一个小书签,单击时应替换 body 标记内的 html 内容。我使用了 document.writedocument.getElementByTag('body')[0].innerHTML = 但两者也都覆盖了 head 元素中的内容。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>

<body>

<a href="javascript:document.write('<h1>Hello</h1>');">Click here</a>

<a href="javascript:document.getElementsByTagName('body')[0].innerHTML='<h1>Hello</h1>'">Click here</a>
</body>
</html>

在不删除 javascript 库的情况下替换 body 标签 html 的方法是什么?

最佳答案

哦,这似乎有效,而且看起来像一个谜题。

替换为整个页面 HTML(包括 head 元素、库等)使其正常工作:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>

<body>

<a href="javascript:document.getElementsByTagName('body')[0].innerHTML='<html><head><script src=\'a\'></script></head><h1>Hello</h1>;return false;'">Click here</a>


</body>
</html>

关于javascript - 无法更改 body 元素的 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39836438/

相关文章:

javascript - 从 Windows 10 上的 IE 页面在 Edge 中打开窗口

javascript - 如何创建一个带有延迟/超时的 JavaScript 书签?

javascript - 在来自不同域的 iFrame 上运行小书签

javascript - 如何在书签中进行身份验证?

javascript - 如何使用 Javascript 创建工具栏/书签?

javascript - fileReader.readAsBinaryString 上传文件

javascript - HTML Canvas 中的 2D 图形和统一缩放

javascript - 检测什么 javascript 被应用到给定的 dom 元素?

javascript - 尝试从 json 文件中获取数据时出现问题

javascript - 使网站在页面加载时运行javascript bookmarklet