0

I'm new to developing chrome extension, so please excuse my ignorance. I want to make a popup html button which click event open a new tab and fill input field inside new tab.

Here's my example code.

popup.html

<button onclick="test">click me</button>

popup.js

function test() {
      
            chrome.tabs.create({ 'url': "https://www.google.com" }, function (tab) {
                var new_tab_id: number = 0;
                if (tab.id != undefined) {
                    new_tab_id = tab.id;
                }
                chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
                    chrome.tabs.sendMessage(new_tab_id, { greeting: "hello" }, function (response) {
                        console.log(response.farewell);
                    });
                });
            })

        }
    }

content.js

chrome.runtime.onMessage.addListener(
    function(request:any, sender:any, sendResponse:any) {
      console.log(sender.tab ?
                  "from a content script:" + sender.tab.url :
                  "from the extension");
      if (request.greeting == "hello") {
          const inputEl:HTMLInputElement|null = document.querySelector('input[name=q]');
          if(inputEl !== null) {
              inputEl.value = 'test input'
          }
      }      
        sendResponse({farewell: "goodbye"});
    }
  );

Is there something I did wrong? console from new tab, popup, background doesn't say anything..

loone96
  • 141
  • 8

1 Answers1

0

Don't use inline code like onclick=test.
Instead, add the click listener in a separate js file, more info and examples.

Opening a new foreground tab closes the popup, which terminates its scripts so it won't send the message. The simplest solution is to use chrome.storage so the content script uses it directly.

manifest.json:

"permissions": ["storage"]

popup.html:

<body>
  <button id="foo">click me</button>
  <script src="popup.js"></script>
</body>

popup.js:

document.querySelector('#foo').onclick = () => {
  chrome.storage.sync.set({autofill: 'foo'}, () => {
    chrome.tabs.create({url: 'https://www.google.com'});
  });
};

content.js:

chrome.storage.sync.get('autofill', data => {
  if (data.autofill) {
    const el = document.querySelector('input[name=q]');
    if (el) el.value = data.autofill;
  }
});

Another solution would be to send a message from the popup to the background script so the latter creates the tab and sends a message to it, but it's more complicated at least if you want it to be reliable.

wOxxOm
  • 43,497
  • 7
  • 75
  • 96