chrome.runtime.onMessage无法处理AJAX

时间:2019-12-24 19:12:58

标签: javascript google-chrome-extension xmlhttprequest

我正在开发chrome扩展程序,试图将数据发送到API。当服务器按预期方式响应时,我发现chrome.runtime.onMessage方法无法将响应发送回相应的chrome.runtime.sendMessage方法。我曾尝试将代码包装在Promises中,但到目前为止仍无法正常工作,请帮助我,thanx。

简而言之,我将数据从popup.html通过popup.js发送到进行xmlhttprequest的background.js。

这是popup.js片段:

/**
 * Sending data to js/background.js
 */
const saveData = document.querySelector('#saveData')
saveData.addEventListener('click', async () => {
    await chrome.runtime.sendMessage(
        {
            action: 'saveData',
            params: { ...store }
        },
        (response) => {
            console.log('response to saveData: ', response)
            alert(response)
        }
    )
})

和background.js:


chrome.runtime.onMessage.addListener(
    async (request, sender, sendResponse) => {

        if (request.action === 'saveData') {
            // console.log(request.params)

            await api_request(request.params)
            .then(
                data => {
                    console.log(data)
                    sendResponse(data)
                }
            )
        }
    }
)

// API Common params
const common_params = {
    'app_type': 'biz',
    'operator_id': 1
}
// Param set to be sent, will be composed later.
let params = {}

// Request API
const api_request = async (inputs) => {
    const params = {
        ...common_params,
        ...inputs
    }

    const form_data = new FormData()
    Object.keys(params).forEach(
        (key) => {
            form_data.append(key, params[key])
        }
    )

    let message = ''

    await new Promise((resolve, reject) => {
        const request = new XMLHttpRequest()

        request.open('post', 'https://api.somewhere.com/item/create', true)

        request.onload = () => {

            if (request.status === 200) {
                const result = JSON.parse(request.response)
                if (result.status === 200) {
                    message = result.content.message
                }
                else {
                    message = result.content.error.message
                }
                resolve(message)
            }
            else {
                reject(Error(request.statusText))
            }
        }
        request.onerror = () => {
            reject(Error('Network Error'))
        }
        request.send(form_data)
    })

    return message // end Promise
}

popup.js控制台打印:

response to saveData:  undefined
Unchecked runtime.lastError: The message port closed before a response was received.

background.js console.prints:

'Well Done on API'

0 个答案:

没有答案