简体   繁体   English

无法在Chrome Extension中从外部js访问HTML元素

[英]Unable to access HTML element from external js in Chrome Extention

Hi I am learning to build Chrome Extensions and am very new to this field. 嗨,我正在学习构建Chrome扩展程序,并且对该领域来说是一个新手。 I am working on a very basic extension here and even before I have started on the main task, I am stuck in my demo code. 我正在这里进行非常基本的扩展,甚至在开始执行主要任务之前,我就一直停留在演示代码中。 I simply wish to print "hello" or any message in my paragraph tag when I click my extension. 当我单击扩展名时,我只是希望在段落标签中打印“ hello”或任何消息。

Here is the HTML code: 这是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>

And here is the code for getMSG.js: 这是getMSG.js的代码:

document.getElementById('content').innerHTML = 'Hello';

My extentsion was working just fine when I simply wrote "Hello World" in my HTML code. 当我在HTML代码中简单地编写“ Hello World”时,我的扩展工作正常。 But now when I do this I get no output at all. 但是现在,当我这样做时,我什么都没有输出。 Please can someone help with this? 请有人帮忙吗? Thanks in advance :) 提前致谢 :)

To access the properties of a DOM element you need to do that operation when the window load: 要访问DOM元素的属性,您需要在窗口加载时执行以下操作:

// Using pure JavaScript
window.onload = function() {
    document.getElementById('content').innerHTML = 'Hello';
}

I was tested your code and it doesn't work, i think the content page wasn't loaded completely, So it's preferred to use jQuery accompany this code in your "getMSG.js": 我已经测试了您的代码,但无法正常工作,我认为内容页面未完全加载,因此,在您的“ getMSG.js”中将此代码与jQuery一起使用是首选方法:

$(document).ready(function () {
    document.getElementById('content').innerHTML = 'Hello';
});

Works fine for me. 对我来说很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM