Search code examples
javascriptswiftsafari-extensionmanifest.jsonsfsafariviewcontroller

Safari Web Extension - injecting script only when extension button is clicked


To keep it simple, I am taking reference for SeaCreator extension example from Apple.

You can take it from here: https://drive.google.com/file/d/1loBDgkJAEtyh0QehOUlgOSyUnW9ZZDk6/view?usp=sharing

In this example as mentioned, we are replacing fish names with different emojis.

The thing is when we tap on the extension icon, it turns into blue to indicate the extension is active and whenever any page is rendered, all fish names will be automatically replaced with emojis.

See screenshot -> enter image description here

What I need is I don't want to keep the extension active always and I want the replace action to be executed only when I press the extension button. So, whenever I open a new webpage I must have to press extension toolbar button only then replacement should be done.

In the code I have attached, I did try few things but none help.

//browser.runtime.addEventListener("message", handleMessage, false);
//function handleMessage(msgEvent) {
//    alert('message received');
    var wordReplacementMap = {"Fish": "🐠", "Shark": "🦈", "Squid": "🦑", "Whale": "🐋"};
    for (var wordToReplace in wordReplacementMap) {
        replace(document.body, wordToReplace, wordReplacementMap[wordToReplace]);
    }
//}

//chrome.runtime.sendMessage("message");

I am always facing -> undefined browser or undefined chrome.

In my original extension project I have used node modules and AJAX also so there are lots of dependencies why I did took reference for Apple's example.

The main thing is I want to turn off automatic script injection and only execute my script code when user taps on extension button. I don't need popup - just execution on tap of button.

Please let me know if anyone can help.


Solution

  • Oh that's so weird. I got it so late that, I have to include background script key in manifest.json besides 'content_script' key.

    "background" : {
        "scripts" : [
          "bundle.js"
        ]
      },
      "content_scripts": [{
          "js": [ "init.bundled.js" ],
          "matches": [ "<all_urls>" ]
      }]
    

    I already have chrome.browserAction.onClicked... method written inside bundle.js which is being called everytime I press extension button from Safari toolbar.

    Whew.