Ajaxでオリジン間リソース共有(CORS)の壁を超える
これは商品ページ内の要素をクロスドメインの壁を超えて取引ナビに表示する例です。
(商品説明に記載した送料を取引ナビに表示したい場合など)
- 適当なサーバに商品ページのhtmlを取ってきて表示します。
header('Access-Control-Allow-Origin: *');とすることにより、別ドメインからのhtml取得を可能にします。 - 拡張機能のjsで商品ページから取ってきた適当なサーバで表示されたhtmlを表示します。
適当なサーバ/index.php
header('Access-Control-Allow-Origin: *');
$aid = $_GET['aid'];
$url = "https://page.auctions.yahoo.co.jp/jp/auction/". $aid;
//ヘッダーの設定
$header = array(
"Content-Type: application/x-www-form-urlencoded",
"User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0",
);
//オプション設定
$options =array(
'http' =>array(
'method' => "GET",
'header' => implode("\r\n", $header),
)
);
//コンテンツ取得
$html = file_get_contents($url, false, stream_context_create($options));
//出力
print_r($html);
拡張機能js
$(function () {
aid = getParam('aid')
$.ajax({
url: "適当なサーバ/?aid="+ aid, // 別ページにあるhtmlページURL
cache: false,
datatype: "html",
success: function (html) {
var html = $(html).find('.ProductExplanation__commentBody'); // 別ページにあるhtml内の一部の要素を指定
var description1 = $(html).find('商品説明内で取得したい要素1'); // 別ページにあるhtml内の一部の要素を指定
var description2 = $(html).find('商品説明内で取得したい要素2'); // 別ページにあるhtml内の一部の要素を指定
$("取引ナビ内で表示させたい場所").append(description1);
$("#取引ナビ内で表示させたい場所").append(description2);
},
});
});
こんな遠回りで面倒な事をしなくても良いプラットフォームが最高ですね。
