Chrome擴展學習Demo(一):在popup裏面跨域獲取資源

場景:在popup頁面獲取某個網站的資源。

效果圖:

代碼截圖:

manifest.json

{
  "manifest_version": 2,
  "name": "跨域獲取圖片",
  "version": "1.0",
  "description": "popup頁面獲取圖片",
  "icons": {
    "48": "icon.png"
  },
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "permissions": [
    "http://*/*", // 可以通過executeScript或者insertCSS訪問的網站
    "https://*/*"// 可以通過executeScript或者insertCSS訪問的網站
  ]
}

popup.html

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8"/>
	<title>跨域獲取圖片</title>
	<style>
		img {
			width: 500px;
		}
	</style>
</head>
<body style="width:500px;min-height:100px;">
    <div>這裏是popup:跨域獲取圖片</div>
    <script type="text/javascript" src="popup.js"></script>
</body>
</html>

popup.js

var imageGenerator = {

  searchOnRenwey: 'https://www.baidu.com/company/renwey_home/banner_images',

  requestImages: function () {
    var req = new XMLHttpRequest();
    req.open('GET', this.searchOnRenwey, true);
    // req.setRequestHeader('Authorization', token);
    req.send();
    req.onload = function () {
      if (req.readyState === 4 && req.status === 200) {
        var resultData = JSON.parse(req.responseText);
        for (var i = 0; i < resultData.total; i++) {
          var img = document.createElement('img');
          img.src = resultData.data[i].imageUrl;
          img.setAttribute('alt', resultData.data[i].imageName);
          document.body.appendChild(img);
        }
      }
    };
  }

};

document.addEventListener('DOMContentLoaded', function () {
  imageGenerator.requestImages();
});

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章