如何在Chrome扩展程序弹出窗口中显示HTML代码

时间:2015-08-12 10:12:29

标签: google-chrome-extension google-chrome-app

我想在Chrome扩展程序的弹出部分中显示Amazon Affiliate Widget Code。

manifest.json看起来像这样(从Google Repository复制):

{
  "manifest_version": 2,

  "name": "Getting started example",
  "description": "This extension shows a Google Image search result for the current page",
  "version": "1.0",

  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "permissions": [
    "activeTab",
    "https://ajax.googleapis.com/"
  ]
}

backgroung.js是空白的。 Popup.html看起来像这样:

<html>
    <head>
	<title>
	Amazon
	</title>
	</head>
  <body>
    <h1>Amazon Search</h1>
	<script charset="utf-8" type="text/javascript">
amzn_assoc_ad_type = "responsive_search_widget";
amzn_assoc_tracking_id = "smart0e-21";
amzn_assoc_marketplace = "amazon";
amzn_assoc_region = "IN";
amzn_assoc_placement = "";
amzn_assoc_search_type = "search_widget";
amzn_assoc_width = "auto";
amzn_assoc_height = "auto";
amzn_assoc_default_search_category = "";
amzn_assoc_default_search_key = "";
amzn_assoc_theme = "light";
amzn_assoc_bg_color = "FFFFFF";
</script>
<script src="//z-in.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&Operation=GetScript&ID=OneJS&WS=1&MarketPlace=IN"></script>
	</body>
</html>

我是这个扩展开发的新手,也是HTML新手。 请帮帮我,我想在弹出窗口中运行搜索小部件。 这是当我点击扩展时发生的情况。  http://i.stack.imgur.com/V3gK2.png 感谢。

1 个答案:

答案 0 :(得分:0)

您无法链接到popup.html文件中的外部链接。相反,您应该在扩展程序的后台添加单独的javascript文件,并从那里调用窗口小部件的脚本。

您的清单看起来像这样(不要忘记添加Content-Security-Policy规则):

{
  "manifest_version": 2,

  "name": "Getting started example",
  "description": "This extension shows a Google Image search result for the current page",
  "version": "1.0",

  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "background" : {
    "scripts" : [ "background.js" ],
  },
  "content_security_policy" : "script-src 'self' 'unsafe-eval' http://z-in.amazon-adsystem.com; object-src 'self'",
  "permissions": [
    "activeTab",
    "https://ajax.googleapis.com/",
    "http://z-in.amazon-adsystem.com/"
  ]
}

您的background.js文件可以在iframe中调用脚本:

 (function() {
    var widget = document.createElement('iframe');
    widget.src = "//z-in.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&Operation=GetScript&ID=OneJS&WS=1&MarketPlace=IN";
    widget.id = 'widget';
    document.body.appendChild(widget);

    //assign your widget variables
  })();

您的popup.html只能有一个指向您的后台文件的脚本链接:

<script type="text/javascript" src="../background.js"></script>

我没有对此进行过测试,但这是如何在扩展程序中运行外部脚本的一般要点。