Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getElementById in chrome extension

I have written a code for extension but it doesn't work: I can't getElementById in document nor in extension popup. I would like when I click popup text extension starts the game. HTML CODE;

    <!DOCTYPE html>
<html>
<head> 

<style> p {color: purple;} </style>
</head>
<body>
<p id="pocinje"> Ekstenzija je pokrenuta i ceka se vrijeme za pocetak. </p>
<script src="background.js"> </script>
</body>
</html>

JAVASCRIPT;

document.getElementById("pocinje").onclick= function() {open};

function open() {
document.getElementById("startNewGame").click();

console.log("alorka");

}

How can I fix this?

like image 509
Alo Balo Avatar asked Jun 02 '18 18:06

Alo Balo


People also ask

What is the use of getElementById () Javascript HTML method?

getElementById() The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.

What is document getElementById () value?

HTML DOM Document getElementById() The getElementById() method returns an element with a specified value. The getElementById() method returns null if the element does not exist. The getElementById() method is one of the most common methods in the HTML DOM.

What is Chrome background script extension?

The background script should be viewed as "running in the background of the Chrome browser". Your desired effect (running a script for every page) is actually a task for content scripts. To learn more, read https://developer.chrome.com/extensions/overview.html#arch. Follow this answer to receive notifications.


Video Answer


2 Answers

An extension popup can't directly interact with the "tab" content (your web page).

Only "background" and "content" script can interact with the "tab" content. The "popup" script can only message to them it's ok to insert another script into it (the click into the "tab" content).

1/ you must establish a communication between your "popup" script and one of these scripts

2/ your action must be inserted into the "tab" content by the right extension script


manifest.json:

First of all, you must declare into your manifest that you want to interact with the tab content:

"permissions": ["tabs", "<all_urls>"],

Secondly, you must declare a "background" file that will be used to be the core of your extension (still in the manifest), at least to centralize the communication between the extension scripts:

"background": {
    "scripts": ["background.js"]
},

Thirdly, you must declare your "popup" (still in the manifest):

"browser_action": {
    "default_popup": "popup.html"
}

Now you have set up your extension, here is the main scripts you can use:

popup.html:

The popup inserts the "popup.js" file that will communicate with the "background.js":

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="popup.js"></script>
</head>
<body>

    <a id="popupBtn">Click me</a>

</body>
</html>

popup.js:

The popup script listens to a click into the popup content and will message to the background if fired:

// always waits the document to be loaded when shown
document.addEventListener('DOMContentLoaded', function() {

    // opens a communication between scripts
    var port = chrome.runtime.connect();

    // listens to the click of the button into the popup content
    document.getElementById('popupBtn').addEventListener('click', function() {

        // sends a message throw the communication port
        port.postMessage({
            'from': 'popup'
            'start': 'Y'
        });
    });
});

background.js:

The background script creates a communication between the popup and itself throw "chrome.runtime", and will insert a code into the tab content if properly messaged:

// opens a communication port
chrome.runtime.onConnect.addListener(function(port) {

    // listen for every message passing throw it
    port.onMessage.addListener(function(o) {

        // if the message comes from the popup
        if (o.from && o.from === 'popup' && o.start && o.start === 'Y') {

            // inserts a script into your tab content
            chrome.tabs.executeScript(null, {

                // the script will click the button into the tab content
                code: "document.getElementById('pageBtn').click();"
            });
        }
    });
});

More information here: https://developer.chrome.com/extensions/content_scripts#functionality

like image 114
Neii Avatar answered Oct 25 '22 10:10

Neii


In your code you are using the onclick event handler:

element.onclick = functionRef;

Where functionRef is a function: the name of a function declared elsewhere (1) or a function expression (2).

- MDN web docs

So you can either:

  1. Call a function with the parenthesis after the function's identifier:

    document.getElementById("pocinje").onclick = function() {
        open()
    };
    
  2. Or just pass the function directly to the property onclick:

    document.getElementById("pocinje").onclick = open
    
like image 38
Ivan Avatar answered Oct 25 '22 09:10

Ivan