Evgeniy
Evgeniy

Reputation: 2595

Saving user input as an option into code - Google Chrome extension

I'm coding my first Chrome extension. Now I want to save user input (API key) as option into the code, so the code runs with this input.

I have a file background.js, which runs my code.js with

chrome.browserAction.onClicked.addListener(function(tab) {
    chrome.tabs.executeScript(tab.id, {file: "code.js"})
});

I have the file code.js, looking like:

(function(){var win=window.open('https://my-test-tool.com?url='+encodeURIComponent(window.location.href )+'&k=<API-KEY>','_blank');win.focus();})()

And i have the file options.html with the form to input the API key, like

<label>
Input API Key
<input type="text" id="wptk">
</label>
<button id="save" onclick="save_options()">Save</button>
<div id="status"></div>
<script src="options.js"></script>

Further i have option.js with following code:

function save_options() {
  var api = document.getElementById('wptk').value;
    chrome.storage.sync.set({
    savedApi: api,
  }, function() {
    // Update status to let user know options were saved.
    var status = document.getElementById('status');
    status.textContent = 'Options saved.';
    setTimeout(function() {
      status.textContent = '';
    }, 750);
  });
}

document.getElementById('save').addEventListener('click', save_options);

All of them are already in the manifest.json, storage too.

I'm on this point now: after installing an extension i open options from extension toolbar, input a string into the input field, and after pressing save i see triggered Option saved message.

Question: how could i put the user input, which i saved in the options into the code.js, after &k= instead of placeholder <API-KEY>.

Example: if user inputs 123 in the options and saves it, i want that in his code.js the code changes from

(function(){var win=window.open('https://my-test-tool.com?url='+encodeURIComponent(window.location.href )+'&k=<API-KEY>','_blank');win.focus();})()

to

(function(){var win=window.open('https://my-test-tool.com?url='+encodeURIComponent(window.location.href )+'&k=123','_blank');win.focus();})()

Upvotes: 2

Views: 1274

Answers (1)

woxxom
woxxom

Reputation: 73526

Open the new tab directly from your background script:

chrome.browserAction.onClicked.addListener(tab => {
  if (!tab.url) return;
  chrome.storage.sync.get('savedApi', ({savedApi}) => {
    chrome.tabs.create({
      url: `https://my-test-tool.com?url=${encodeURIComponent(tab.url)}&k=${savedApi}`,
      index: tab.index + 1,
      openerTabId: tab.id,
    });
  });
});

To open a separate window and control its size/position you can use chrome.windows.create.

Upvotes: 1

Related Questions