2

I am teaching myself how to build Chrome Extensions. The first thing I want to build is a simple word predictor that takes in your last few words, predicts the next word, and allows you to autocomplete the word by pressing tab.

The first thing I need to do is figure out how to access the text box the user is currently typing in. For example, Grammarly seems to do this well. I've searched through StackOverflow, but can't seem to find an answer (forgive me, I'm a beginner). Any help would be amazing!

Mashu
  • 79
  • 2
  • 5
  • Learn about JavaScript Events https://www.w3schools.com/js/js_events.asp and HTML DOM Events https://www.w3schools.com/jsref/dom_obj_event.asp Plenty of examples here on SO of the same also. – ikiK Jul 07 '20 at 23:17

2 Answers2

1

First you need to get permission for your extension to access a user's tabs, as I understand it.


Then you need to access the current tab with chrome.tabs.getCurrent()

Then I think you'll need to do something like let focusedElement = chrome.tabs.getCurrent(() => document.activeElement)


I've developed an extension, but I've never accessed tabs so I'm not entirely sure about the last part. If that doesn't work, let me know!

Slbox
  • 10,957
  • 15
  • 54
  • 106
  • 1
    getCurrent is the wrong method, it does not return the current tab, but the tab of the currently running code, which is different thing. – wOxxOm Jul 08 '20 at 03:35
0

I think I see what you mean by access now..

Just add this function to your content script and it will attach a event listener too all inputs on the page that returns the current input field.

All it does is uses a for loop to loop through all inputs on the page, then add a click addEventListener to each input, and have it return the current input

<!DOCTYPE html>
<html>
<head>
    <title>Test</title>
</head>
<body>
    <input type="text" name="text" id="input1" placeholder="Click me">
    <input type="text" name="text" id="input2" placeholder="Click me">
    <input type="text" name="text" id="input3" placeholder="Click me">
    <br><br><br>
    <div id="display"></div>
</body>
<script>




    function inputs(){
        for(let i = 0; i < document.querySelectorAll('input').length; i++){
            document.querySelectorAll('input')[i].addEventListener('click', ()=>{
                //Get the DOM element of whatever input user clicks on
                var currentInput = document.querySelectorAll('input')[i];
                console.log(currentInput);

                //Just for example purposes 
                document.getElementById('display').innerText = 'You clicked on input...' + (i+1);
            });
        }
    }
    inputs();
</script>
</html>

Now that you have the exact input field the user is typing in.. you should be able to add the predicted words, by setting the input field equal to the current value of it + your predicted text.

StrayAnt
  • 369
  • 2
  • 7