DJK
DJK

Reputation: 9264

Inject html as the result of an API Call Chrome Extension

The Question

How do I take the json result from and API call and inject the result into and html page?

The Context

As part of a web extension I am working on, I call and API for a resulting json.

my popup.html has a button click that calls a call.js file.

call.js (example)

$.ajax({
        type: 'GET',
        url:body,
        headers: headers,
        success:function(data) {
              console.log(data);
              // use return json to update html
              // maybe open html for injection here as
              // var url = chrome.extension.getURL('location.html')
              // chrome.tabs.create({url: url, active: true});
            }

Interms of flow, i'm not sure how to pass the result of the api call, in and effective way, to a scrip that will inject HTML into the location.html file.

I tried the following flow

Get API Json -> store json in localStorage -> open location.html url -> have a content script that runs an injection.js file one https://*location.html* appears -> inject required elements

but the json was to large for local storage, and honestly, I'm unsure if that flow was even correct. Do you have any suggestions on how to resolve this issue? I feel this is a standard functionality of web extensions, but for some reason, I cannot put this piece of the puzzle together.

Thanks!

Upvotes: 0

Views: 475

Answers (1)

Hank X
Hank X

Reputation: 2044

use massage passing.

in your content script

chrome.runtime.onMessage.addListener(req =>{
if(req.action === "showJSONFromPopup"){
 showJSONResult(req.data)
}
})

in your popup script

$.ajax({
        type: 'GET',
        url:body,
        headers: headers,
        success:function(data) {
              console.log(data);
              chrome.tabs.query({currentWindow:true, active:true}, tabs=>{
              chrome.tabs.sendMessage(tabs[0].id, {action: "showJSONFromPopup", data})

})
            }

Upvotes: 1

Related Questions