首页 > 解决方案 > 将当前浏览器的源代码存储在 chrome 扩展中

问题描述

我正在尝试通过 chrome 扩展获取当前浏览器的源代码(HTML 代码)。我试图将此 HTML 代码存储在一个字符串中,但它似乎不起作用。

http://jsfiddle.net/ufbxge08/2/

<head>
<style>
  button {
    height: 30px;
    width: 100px;
    outline: none;
  }
</style>
</head>
<body>
<button id="bth1">Predict</button>
<script src="popup.js"></script>
<script src="jquery-2.0.3.js"></script>
<form>
  <label id = 'mybtn1'></label>
</form>

JavaScript:

btn1.onclick = function scrapeThePage() {
// Keep this function isolated - it can only call methods you set up in content scripts
var htmlCode = document.documentElement.outerHTML;
var btn = document.getElementById("mybtn1");
btn.innerHTML = htmlCode;
console.log(htmlCode)

}

我希望代码将源代码存储在一个字符串中,但它似乎不起作用。

标签: javascripthtmlgoogle-chrome-extension

解决方案


如果您想在 HTML 元素中显示 HTML 代码,您可能需要设置文本内容 ( innerText),而不是 HTML 内容 ( innerHTML):

bth1.onclick = function scrapeThePage() {
    // Keep this function isolated - it can only call methods you set up in content scripts
    var htmlCode = document.documentElement.outerHTML;
    var btn = document.getElementById("mybtn1");
    btn.innerText = htmlCode;
}

http://jsfiddle.net/1jk94r50/


推荐阅读