How to call functions in the original page(tab) in Chrome Extensions

后端 未结 2 1306
太阳男子
太阳男子 2020-12-04 20:04

I\'m now making a Chrome Extension. I want to call JS functions that are defined in the original page (tab), from Chrome Extension. It doesn\'t matter whether backgrou

相关标签:
2条回答
  • 2020-12-04 20:24

    For the first part you can use this nice answer: Insert code into the page context using a content script.

    To call a function back in your content script is easy. You can create your own event which you can then listen on in your content script. This would work like this:

    injected code:

    var evt = document.createEvent('Event');
    evt.initEvent('myCustomEvent', true, false);
    
    // fire the event
    document.dispatchEvent(evt);
    

    contentscript:

    document.addEventListener('myCustomEvent', function() {
      // do whatever is necessary
    });
    
    0 讨论(0)
  • 2020-12-04 20:29

    You can also simply write in your content script:

    location.href="javascript:greeting(); void 0";
    
    0 讨论(0)
提交回复
热议问题