【问题标题】:chrome extension post request to other web pagechrome 扩展发布请求到其他网页
【发布时间】:2018-11-15 11:44:06
【问题描述】:

我是这里的新手,我正在尝试制作一个可以与我的 rails 应用程序一起使用的 chrome 扩展。它是一个书签应用程序,所以我希望用户能够浏览其他网站,然后通过单击 chrome 扩展图标为页面添加书签,它会发出发布请求并将其添加到用户主页。

目前我只能从用户主页上使用它,但不能从任何其他主页上使用,这不是很有用。我认为的问题在于 csrf 令牌,它在设置时设置为当前选项卡的页面,但我认为它需要是用户主页的 csrf 令牌才能通过请求?我试过简单地不包括它,但这不起作用,因为它是必需的。

manifest.json:

    {
  "manifest_version": 2,
  "name": "My Cool Extension",
  "version": "0.1",
  "permissions" : [
    "tabs", 
    "<all_urls>", 
    "https://*/",
    "http://*/"
  ],
  "browser_action": {
    "default_icon": "icon.png"
  },
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js", "html2canvas.js"]
    }
  ],
  "background": {
    "scripts": ["background.js"]
  }
}

background.js

    //Called when the user clicks on the browser action.
chrome.browserAction.onClicked.addListener(function(tab) {
  // Send a message to the active tab
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    var activeTab = tabs[0];
    chrome.tabs.sendMessage(activeTab.id, {"message": "clicked_browser_action"});
  });
});

content.js

savePage = () => {
  console.log('save page called');
  var token = document.querySelector('meta[name="csrf- 
    token"]').getAttribute('content');
  var data = {"url":window.location.href, "screenshot":'tempScreen.png', 
    "user_id": 2, "title":document.title};

  var xhr = new XMLHttpRequest();
  xhr.open('POST', 'https://hidden-bastion-43962.herokuapp.com/bookmarks');
  xhr.withCredentials = true;
  xhr.setRequestHeader('Content-Type', 'application/json');
  xhr.setRequestHeader('X-CSRF-Token', token);
  xhr.send(JSON.stringify(data));
}

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    if( request.message === "clicked_browser_action" ) {
      var firstHref = window.location.href;
      console.log(firstHref);
      takeScreenshot();
    }
  }
);

【问题讨论】:

    标签: ruby-on-rails google-chrome-extension cross-domain csrf


    【解决方案1】:

    您应该从 background.js 页面发出任何跨站点请求。 让您的内容脚本将带有帖子数据的消息发布到后台页面,并让后台页面发送 xhr. 这将避免跨站点/CORS 问题。

    【讨论】:

    • 你说得对,我是倒着做的。我对其进行了改造,现在一切正常,谢谢!
    猜你喜欢
    • 2014-02-09
    • 1970-01-01
    • 1970-01-01
    • 2022-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-29
    • 1970-01-01
    相关资源
    最近更新 更多