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

非 Y 不嫁゛ 提交于 2020-07-31 05:45:38

问题


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 ->

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.


回答1:


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.



来源:https://stackoverflow.com/questions/62774734/safari-web-extension-injecting-script-only-when-extension-button-is-clicked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!