javascript - 如何通过 window.open() 在跨域窗口弹出窗口中操作 dom

标签 javascript google-chrome-extension cross-domain

我想让扩展程序帮助我检查不同网站的状态。所以我需要扩展来打开不同的网站并检查网页中的一些 dom。该网站可能是一个动态网页,所以我必须在浏览器中加载该页面,以便我可以获得真正的dom(而不仅仅是源)。 通常,对于相同的域情况。可能是这样的:

var w = window.open('http://www.yahoo.com');
console.log(w);
$(w).bind('load', function() {
  //In chrome extension, i can not get "this.document"
  //And in iframe i can not get "document", either
  console.log(this.document);
});

我正在尝试使用 chrome 扩展程序的跨域 ajax 权限。所以我可以从不同的领域操纵窗口。 但它失败了。该代码片段在 Chrome 扩展下不起作用。为什么?为什么chrome扩展有跨域ajax的权限,但不能操作其他域的窗口? 我也尝试了 iframe。这也行不通。

我想问有没有办法通过chrome或chrome扩展来操作跨域文档?

最佳答案

chrome 扩展的一个优点是:它为 webapp 授予更多权限,以绕过某些安全限制,其中包括 XHR。

请查看跨站xhr上的文档:

http://code.google.com/chrome/extensions/xhr.html

一些预防措施:

  1. 您需要配置 manifest.json 文件、permissions 属性以在更多网址上启用 xhr: More possible permissions 如果您需要在 iframe 中运行扩展内容脚本,请注意 content_scripts doc 中设置的额外属性。

    {
       "name": "My extension",
       ...
       "permissions": [   
               "tabs",
               "http://*/*",
               "https://*/*" ],
       "content_scripts": [{ //note: for iframe, array
           "matches":[
               "http://*/*",
               "https://*/*" //match all url
           ],
           "run_at": "document_idle",
           "js": ["jquery.min.js", "contentscript.js"] //script you need to run in iframe
        }]
    

    }

  2. 您需要处理 background.html 中的 xhr,或者将 url 传递到扩展程序将打开的新窗口(通过 chrome.windows.create >)。您可能会对我正在开发的扩展有所了解(用于 list 和窗口打开): https://github.com/vincicat/ImageInfoPlus

希望对你有帮助。

关于javascript - 如何通过 window.open() 在跨域窗口弹出窗口中操作 dom,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9529221/

相关文章:

javascript - 允许短路评估中的零值

javascript - 如何指定哪些内容脚本将在 all_frames 上运行,哪些不会?

javascript - 递归异步函数中的 Promise

javascript - Chrome 扩展程序 : Content of localStorage is not visible in Chrome DevTools

javascript - jQuery同步跨子域POST请求

AngularJS 的 $http.post() 每次发送两个 AJAX 请求,一个没有数据,一个有

javascript - 如何进行跨域请求

javascript - 使用ajax将数据从html传递到python

javascript - 更改图像的颜色

javascript - 如何在javascript中全局访问附加到元素的对象