您好我正在学习构建Chrome扩展程序并且对这个领域非常陌生。我正在这里进行一个非常基本的扩展,甚至在我开始执行主要任务之前,我就被困在我的演示代码中。我只想在点击扩展名时打印“hello”或段落标记中的任何消息。
以下是HTML代码:
<!DOCTYPE html>
<html>
<head>
<title>hi</title>
<style>
p
{
color:red;
font-size:20px;
}
</style>
<script src="getMSG.js"></script>
</head>
<body>
<p id='content'></p>
</body>
</html>
以下是getMSG.js的代码:
document.getElementById('content').innerHTML = 'Hello';
当我在HTML代码中编写“Hello World”时,我的扩展工作正常。但是现在当我这样做时,我根本没有输出。有人可以帮帮忙吗?在此先感谢:)
答案 0 :(得分:3)
要访问DOM元素的属性,您需要在窗口加载时执行该操作:
// Using pure JavaScript
window.onload = function() {
document.getElementById('content').innerHTML = 'Hello';
}
答案 1 :(得分:2)
我测试了你的代码并且它不起作用,我认为内容页面没有完全加载, 因此,最好在“getMSG.js”中使用此代码的jQuery:
$(document).ready(function () {
document.getElementById('content').innerHTML = 'Hello';
});
对我来说很好。