Reputation: 403
Is it possible, to access DOM after completing installation of the Safari extension? I'm interested in accessing into HTML of the page from which this extension is being installed.
Upvotes: 2
Views: 1903
Reputation: 21233
You can achieve this by injecting JS scripts. The injected scripts have access to the DOM of the webpages they are injected into. Injected scripts have the same access privileges as scripts executed from the webpage’s host.
You can find more information here.
Calling a Function from an Injected Script
Code Injected.js
var initialVal=1;
var calculatedVal=0 ;
function doBigCalc(theData) {
safari.self.tab.dispatchMessage("calcThis",theData);
}
function getAnswer(theMessageEvent) {
if (theMessageEvent.name === "theAnswer") {
calculatedVal=theMessageEvent.message;
console.log(calculatedVal);
}
}
safari.self.addEventListener("message", getAnswer, false);
doBigCalc(initialVal);
Code Global.html
<!DOCTYPE HTML>
<html>
<head>
<title>global HTML page</title>
<script type="text/javascript">
function bigCalc(startVal, event) {
// imagine hundreds of lines of code here...
var endVal = startVal + 2;
// return to sender
event.target.page.dispatchMessage("theAnswer", endVal);
}
function respondToMessage(theMessageEvent) {
if(theMessageEvent.name === "calcThis") {
var startVal=theMessageEvent.message;
bigCalc(startVal, theMessageEvent);
}
}
safari.application.addEventListener("message",respondToMessage,false);
</script>
</head>
<body>
</body>
</html>
Upvotes: 4