我正在尝试在“页面上下文”中做某事,为此我在页面中注入脚本,如下所示
var pageScript = document.createElement('script');
pageScript.textContent = actualCode;
document.body.insertBefore(pageScript, document.body.firstChild);
actualCoe
是_
var actualCode = '(' + function() {
document.addEventListener(playerEventName, function(event) {
console.log("page script fire"");
});
} + ')();'; // end actualCode
但是当我发送消息时侦听器不会触发,在控制台中我只看到发送的消息名称。
我的 script.js 文件的完整代码
document.addEventListener("DOMContentLoaded", function(event) {
safari.extension.dispatchMessage("script injected successfully");
init();
});
let playerEventName = "su.nagornyi.yam.ext.evnt";
var init = function() {
console.log("init started");
var pageScript = document.createElement('script');
pageScript.textContent = actualCode;
document.body.insertBefore(pageScript, document.body.firstChild);
}; // end init
var actualCode = '(' + function() {
document.addEventListener(playerEventName, function(event) {
console.log("page script fire");
});
} + ')();'; // end actualCode
safari.self.addEventListener("message", handleMessage);
function handleMessage(event) {
console.log(event.name);
let playerEvent = new CustomEvent(playerEventName, {
detail: {
action: event.name
}
});
document.dispatchEvent(playerEvent);
}; // end handleMessage
UPD:控制台错误:
Refused to execute a script because its hash its nonce or 'unsafe-inline'does
not appear in the script-src directive of the Content Securrity policy.
那么,是否可以在此页面上注入脚本?
UPD2:在 Safari App Extension 中,我们只能从扩展包中的文件注入脚本。