【问题标题】:Proper way to use results of a post request to update a webpage使用发布请求结果更新网页的正确方法
【发布时间】:2020-07-22 18:31:22
【问题描述】:

我是 Web 开发的新手,我正在尝试正确更新我在发布请求后创建的弹出窗口。我这样做的方式似乎太复杂了。 基本上我有一个 chrome 扩展,它在某个时候向我的数据库发出一个 post 请求并返回一个 url。然后我想打开一个弹出窗口,并让我的数据库刚刚在弹出窗口中传递的 url。这看起来很简单,我确信我目前的设计过于复杂: 在 content.js 我调用函数 doWork:

function doWork(itemName, itemPrice) {

    var items = [{'itemName': itemName, 'price': itemPrice}]
    // ajax the JSON to the server
    $.post('https:my/url/receiver', JSON.stringify(items), 
        function(data, status){
            chrome.runtime.sendMessage({type:'open_deals_page', url:data.url})
        });
}

这是由 background.js 在以下函数中接收的:

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.type === 'open_deals_page') {
        chrome.tabs.create({
            url: chrome.extension.getURL('popup.html'),
            active: false
        }, function(tab) {
                chrome.windows.create({
                tabId: tab.id,
                type: 'panel',
                height: 200, width:200,
                focused: true,
                // incognito, top, left, ...
            });
            adjust_window(request.url)
        });
    }
});

之后,在理想情况下,函数 adjust_window 会改变 下面 popup.html 中 id='itemUrl' 的 html 元素:

<!DOCTYPE html><html><head><title>Dialog test</title></head><body>
</title>There is a better deal elsewhere on the web @</title>
<a href="giggle.com" id='itemUrl'>the url you requested</a>
</html>

不用说,我不确定如何设置 adjust_window 函数或者我是否在正确的位置调用它。我尝试了各种 jquery 选择器并不断获得空值。我也对如何确保访问刚刚打开的特定弹出窗口感到困惑。谢谢!

【问题讨论】:

  • 现代 Chrome 不允许内容脚本中的跨域请求。在后台脚本中执行此操作并使用消息进行协调。

标签: javascript jquery html google-chrome-extension web-applications


【解决方案1】:

是否需要从content.js 发出网络请求?这似乎是在后台可能发生的事情。如果问题是访问 jQuery(对于 $.post),那么我建议您查看原生的 fetch 函数。对你来说,它看起来像

fetch(
  'https://your/url/receiver', 
  { 
    method: 'POST', 
    body: JSON.stringify(items)
  }
).then(res => res.json()).then(data => data.url)

上面使用了“箭头函数表达式”,但如果这些使人难以理解,下面是等价的!​​p>

fetch(
  'https://your/url/receiver', 
  { 
    method: 'POST', 
    body: JSON.stringify(items)
  }
).then(function(res) { return res.json() }).then(function(data) { return data.url })

【讨论】:

  • 在承诺中我看到你有变量 res 和 data——我应该在哪里以及如何定义它们?这让我绊倒了。关于 content.js 中的请求没有特别的原因,所以我将它们移至 background.js
  • @NoahFriedman 明白了! resdata 都被定义为“箭头函数”中的参数我怀疑箭头函数语法会让你失望,所以我添加了一个不使用它们的示例。让我知道这是否有帮助!
猜你喜欢
  • 2022-11-28
  • 2020-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-24
  • 1970-01-01
  • 1970-01-01
  • 2022-10-04
相关资源
最近更新 更多