gpt4 book ai didi

javascript - Chrome 扩展程序内容脚本中的 polymer 元素

转载 作者:行者123 更新时间:2023-11-28 19:06:37 25 4
gpt4 key购买 nike

我创建了一个自定义 Polymer 元素,并尝试在我的 Chrome 扩展程序中使用它。但是,我遇到了以下问题。

我无法从内容脚本访问我的元素的 API。这就是我的意思。

我的元素的模板

<link rel="import" href="../polymer/polymer.html">
<dom-module id="my-element">
<template>
... some html...
</template>
<script src="js/my-element.js"></script>
</dom-module>

在 my-element.js

Polymer({
is: 'my-element',
init: function () {
console.log('init');
}
});

在 content.js

var link = document.createElement('link');
link.setAttribute('rel', 'import');
link.setAttribute('href', chrome.extension.getURL('my-element.html'));
link.onload = function() {
var elem = document.createElement('my-element');
document.body.appendChild(elem);
elem.init(); // Error: undefined is not a function
};
document.body.appendChild(link);

有趣的是,我可以看到 my-element 在页面上正确呈现,其中包含所有的影子 dom 和其他东西。如果我在主机网页的控制台中运行 document.querySelector('my-element').init() ,它的执行不会出现错误。但是,在内容脚本中执行相同的代码会产生错误。

我尝试将 Polymer 本身包含为内容脚本。我遇到了 registerElement 问题,但我通过 this 解决了它问题。在本例中,我在 content.js 中定义了 window.Polymer。 My-element 的 API 变得完全可访问,但现在当我将其附加到主机网页的 DOM 时,它的影子 dom 不会呈现。

最佳答案

您正在进入内容脚本的沙箱:

Content scripts execute in a special environment called an isolated world. They have access to the DOM of the page they are injected into, but not to any JavaScript variables or functions created by the page. It looks to each content script as if there is no other JavaScript executing on the page it is running on. The same is true in reverse: JavaScript running on the page cannot call any functions or access any variables defined by content scripts.

from https://developer.chrome.com/extensions/content_scripts#execution-environment

Polymer 组件的脚本在主页中运行,因此它对您的内容脚本不可见。

您可以将新的脚本标记注入(inject)主机页面,并从扩展程序中的 .js 文件获取它,例如

var script = document.createElement('<script>');
script.src = chrome.extension.getURL('something.js');
document.appendChild(script);

这将在主机页面的上下文中运行 something.js,授予其访问主机页面中所有其他脚本(包括您的 Polymer 组件)的权限,但也使其对您的内容不可见脚本。请特别关注security implications在主机页面中注入(inject)脚本。

如果您无法/不愿意将所有扩展逻辑推送到该注入(inject)的脚本中,例如因为您需要访问 chrome.* API 或主机页面和内容脚本之间的其他类型的通信,请查看 message posting .

关于javascript - Chrome 扩展程序内容脚本中的 polymer 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31537463/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com