Chrome Extension - From the DOM to Popup.js message passing

前端 未结 1 1746
一生所求
一生所求 2020-12-08 17:32

I\'m trying to get a simple Google Chrome extension working where a message/variable flows through each of the following steps ...

  1. DOM content (from specific H
相关标签:
1条回答
  • 2020-12-08 18:08

    Alright, changing a few things in your code should make it work like you want. Not all of the changes I am going to make are necessary, but this is just how I might do it.

    Content Script

    var fromDOM = $('h1.name').text();
    chrome.runtime.sendMessage({method:'setTitle',title:fromDOM});
    

    Background

    var title;
    chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){
      if(message.method == 'setTitle')
        title = message.title;
      else if(message.method == 'getTitle')
        sendResponse(title);
    });
    

    Popup.js

    chrome.runtime.sendMessage({method:'getTitle'}, function(response){
      $('.output').text(response);
    });
    
    0 讨论(0)
提交回复
热议问题